Salome HOME
07192d1cb0aec457a2bf5d86028b41844b265ea4
[modules/smesh.git] / src / SMESH_I / SMESH_Gen_i.cxx
1 //  Copyright (C) 2007-2008  CEA/DEN, EDF R&D, OPEN CASCADE
2 //
3 //  Copyright (C) 2003-2007  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 //  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
5 //
6 //  This library is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU Lesser General Public
8 //  License as published by the Free Software Foundation; either
9 //  version 2.1 of the License.
10 //
11 //  This library is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 //  Lesser General Public License for more details.
15 //
16 //  You should have received a copy of the GNU Lesser General Public
17 //  License along with this library; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 //
20 //  See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
21 //
22 //  SMESH SMESH_I : idl implementation based on 'SMESH' unit's calsses
23 //  File   : SMESH_Gen_i.cxx
24 //  Author : Paul RASCLE, EDF
25 //  Module : SMESH
26 //  $Header$
27 //
28 #include <TopExp.hxx>
29 #include <TopExp_Explorer.hxx>
30 #include <TopoDS.hxx>
31 #include <TopoDS_Iterator.hxx>
32 #include <TopoDS_Compound.hxx>
33 #include <TopoDS_CompSolid.hxx>
34 #include <TopoDS_Solid.hxx>
35 #include <TopoDS_Shell.hxx>
36 #include <TopoDS_Face.hxx>
37 #include <TopoDS_Wire.hxx>
38 #include <TopoDS_Edge.hxx>
39 #include <TopoDS_Vertex.hxx>
40 #include <TopoDS_Shape.hxx>
41 #include <TopTools_MapOfShape.hxx>
42 #include <TopTools_IndexedMapOfShape.hxx>
43 #include <TopTools_ListOfShape.hxx>
44 #include <TopTools_ListIteratorOfListOfShape.hxx>
45 #include <gp_Pnt.hxx>
46 #include <BRep_Tool.hxx>
47 #include <TCollection_AsciiString.hxx>
48 #include <OSD.hxx>
49
50 #include "Utils_CorbaException.hxx"
51
52 #include "utilities.h"
53 #include <fstream>
54 #include <stdio.h>
55
56 #ifdef WNT
57  #include <windows.h>
58 #else
59  #include <dlfcn.h>
60 #endif
61
62 #ifdef WNT
63  #define LibHandle HMODULE
64  #define LoadLib( name ) LoadLibrary( name )
65  #define GetProc GetProcAddress
66  #define UnLoadLib( handle ) FreeLibrary( handle );
67 #else
68  #define LibHandle void*
69  #define LoadLib( name ) dlopen( name, RTLD_LAZY )
70  #define GetProc dlsym
71  #define UnLoadLib( handle ) dlclose( handle );
72 #endif
73
74 #include <HDFOI.hxx>
75
76 #include "SMESH_Gen_i.hxx"
77 #include "SMESH_Mesh_i.hxx"
78 #include "SMESH_Hypothesis_i.hxx"
79 #include "SMESH_Algo_i.hxx"
80 #include "SMESH_Group_i.hxx"
81 #include "SMESH_PythonDump.hxx"
82
83 #include "SMESHDS_Document.hxx"
84 #include "SMESHDS_Group.hxx"
85 #include "SMESHDS_GroupOnGeom.hxx"
86 #include "SMESH_Mesh.hxx"
87 #include "SMESH_Hypothesis.hxx"
88 #include "SMESH_Group.hxx"
89 #include "SMESH_MeshEditor.hxx"
90
91 #include "SMDS_EdgePosition.hxx"
92 #include "SMDS_FacePosition.hxx"
93 #include "SMDS_VertexPosition.hxx"
94 #include "SMDS_SpacePosition.hxx"
95 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
96
97 #include CORBA_SERVER_HEADER(SMESH_Group)
98 #include CORBA_SERVER_HEADER(SMESH_Filter)
99 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
100
101 #include "DriverMED_W_SMESHDS_Mesh.h"
102 #include "DriverMED_R_SMESHDS_Mesh.h"
103
104 #include "SALOMEDS_Tool.hxx"
105 #include "SALOME_NamingService.hxx"
106 #include "SALOME_LifeCycleCORBA.hxx"
107 #include "Utils_SINGLETON.hxx"
108 #include "OpUtil.hxx"
109
110 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
111
112 #include "GEOM_Client.hxx"
113 #include "Utils_ExceptHandlers.hxx"
114
115 #include <map>
116
117 using namespace std;
118 using SMESH::TPythonDump;
119
120 #define NUM_TMP_FILES 2
121
122 #ifdef _DEBUG_
123 static int MYDEBUG = 0;
124 #else
125 static int MYDEBUG = 0;
126 #endif
127
128 // Static variables definition
129 GEOM::GEOM_Gen_var      SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
130 CORBA::ORB_var          SMESH_Gen_i::myOrb;
131 PortableServer::POA_var SMESH_Gen_i::myPoa;
132 SALOME_NamingService*   SMESH_Gen_i::myNS  = NULL;
133 SALOME_LifeCycleCORBA*  SMESH_Gen_i::myLCC = NULL;
134 SMESH_Gen_i*            SMESH_Gen_i::mySMESHGen = NULL;
135
136 //=============================================================================
137 /*!
138  *  GetServant [ static ]
139  *
140  *  Get servant of the CORBA object
141  */
142 //=============================================================================
143
144 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
145 {
146   if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
147     return NULL;
148   try {
149     PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
150     return aServant;
151   } 
152   catch (...) {
153     INFOS( "GetServant - Unknown exception was caught!!!" ); 
154     return NULL;
155   }
156 }
157
158 //=============================================================================
159 /*!
160  *  SObjectToObject [ static ]
161  *
162  *  Get CORBA object corresponding to the SALOMEDS::SObject
163  */
164 //=============================================================================
165
166 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
167 {
168   SALOMEDS::GenericAttribute_var anAttr;
169   CORBA::Object_var anObj;
170   if ( !theSObject->_is_nil() ) {
171     try {
172       if( theSObject->FindAttribute( anAttr, "AttributeIOR" ) ) {
173         SALOMEDS::AttributeIOR_var anIOR  = SALOMEDS::AttributeIOR::_narrow( anAttr );
174         CORBA::String_var aValue = anIOR->Value();
175         if( strcmp( aValue, "" ) != 0 )
176           anObj = GetORB()->string_to_object( aValue );
177         }
178     }
179     catch( ... ) {
180       INFOS( "SObjectToObject - Unknown exception was caught!!!" );
181     }
182   }
183   return anObj;
184 }
185
186 //=============================================================================
187 /*!
188  *  GetNS [ static ]
189  *
190  *  Get SALOME_NamingService object 
191  */
192 //=============================================================================
193
194 SALOME_NamingService* SMESH_Gen_i::GetNS()
195 {
196   if ( myNS == NULL ) {
197     myNS = SINGLETON_<SALOME_NamingService>::Instance();
198     ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
199     myNS->init_orb( GetORB() );
200   }
201   return myNS;
202 }
203
204 //=============================================================================
205 /*!
206  *  GetLCC [ static ]
207  *
208  *  Get SALOME_LifeCycleCORBA object
209  */
210 //=============================================================================     
211 SALOME_LifeCycleCORBA*  SMESH_Gen_i::GetLCC() {
212   if ( myLCC == NULL ) {
213     myLCC = new SALOME_LifeCycleCORBA( GetNS() );
214   }
215   return myLCC;
216 }
217
218
219 //=============================================================================
220 /*!
221  *  GetGeomEngine [ static ]
222  *
223  *  Get GEOM::GEOM_Gen reference
224  */
225 //=============================================================================     
226 GEOM::GEOM_Gen_ptr SMESH_Gen_i::GetGeomEngine() {
227   //CCRT GEOM::GEOM_Gen_var aGeomEngine =
228   //CCRT   GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
229   //CCRT return aGeomEngine._retn();
230   if(CORBA::is_nil(myGeomGen))
231   {
232     Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
233     myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
234   }
235   return myGeomGen;
236 }
237
238 //=============================================================================
239 /*!
240  *  SMESH_Gen_i::SMESH_Gen_i
241  *
242  *  Default constructor: not for use
243  */
244 //=============================================================================
245
246 SMESH_Gen_i::SMESH_Gen_i()
247 {
248   INFOS( "SMESH_Gen_i::SMESH_Gen_i : default constructor" );
249 }
250
251 //=============================================================================
252 /*!
253  *  SMESH_Gen_i::SMESH_Gen_i 
254  *
255  *  Standard constructor, used with Container
256  */
257 //=============================================================================
258
259 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr            orb,
260                           PortableServer::POA_ptr   poa,
261                           PortableServer::ObjectId* contId, 
262                           const char*               instanceName, 
263                           const char*               interfaceName )
264      : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
265 {
266   MESSAGE( "SMESH_Gen_i::SMESH_Gen_i : standard constructor" );
267
268   myOrb = CORBA::ORB::_duplicate(orb);
269   myPoa = PortableServer::POA::_duplicate(poa);
270   
271   _thisObj = this ;
272   _id = myPoa->activate_object( _thisObj );
273   
274   myIsEmbeddedMode = false;
275   myShapeReader = NULL;  // shape reader
276   mySMESHGen = this;
277
278   // set it in standalone mode only
279   //OSD::SetSignal( true );
280 }
281
282 //=============================================================================
283 /*!
284  *  SMESH_Gen_i::~SMESH_Gen_i
285  *
286  *  Destructor
287  */
288 //=============================================================================
289
290 SMESH_Gen_i::~SMESH_Gen_i()
291 {
292   INFOS( "SMESH_Gen_i::~SMESH_Gen_i" );
293
294   // delete hypothesis creators
295   map<string, GenericHypothesisCreator_i*>::iterator itHyp;
296   for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
297   {
298     delete (*itHyp).second;
299   }
300   myHypCreatorMap.clear();
301
302   // Clear study contexts data
303   map<int, StudyContext*>::iterator it;
304   for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
305     delete it->second;
306   }
307   myStudyContextMap.clear();
308   // delete shape reader
309   if ( !myShapeReader ) 
310     delete myShapeReader;
311 }
312   
313 //=============================================================================
314 /*!
315  *  SMESH_Gen_i::createHypothesis
316  *
317  *  Create hypothesis of given type
318  */
319 //=============================================================================
320 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
321                                                           const char* theLibName)
322      throw (SALOME::SALOME_Exception)
323 {
324   /* It's Need to tranlate lib name for WIN32 or X platform */
325   char* aPlatformLibName = 0;
326   if ( theLibName && theLibName[0] != '\0'  )
327   {
328     int libNameLen = strlen(theLibName);
329     //check for old format "libXXXXXXX.so"
330     if (libNameLen > 7 &&
331         !strncmp( theLibName, "lib", 3 ) &&
332         !strcmp( theLibName+libNameLen-3, ".so" ))
333     {
334       //the old format
335 #ifdef WNT
336       aPlatformLibName = new char[libNameLen - 1];
337       aPlatformLibName[0] = '\0';
338       aPlatformLibName = strncat( aPlatformLibName, theLibName+3, libNameLen-6  );
339       aPlatformLibName = strcat( aPlatformLibName, ".dll" );
340       aPlatformLibName[libNameLen - 2] = '\0';
341 #else
342       aPlatformLibName = new char[ libNameLen + 1];
343       aPlatformLibName[0] = '\0';
344       aPlatformLibName = strcat( aPlatformLibName, theLibName );
345       aPlatformLibName[libNameLen] = '\0';
346 #endif
347     }
348     else
349     {
350       //try to use new format 
351 #ifdef WNT
352       aPlatformLibName = new char[ libNameLen + 5 ];
353       aPlatformLibName[0] = '\0';
354       aPlatformLibName = strcat( aPlatformLibName, theLibName );
355       aPlatformLibName = strcat( aPlatformLibName, ".dll" );
356 #else
357       aPlatformLibName = new char[ libNameLen + 7 ];
358       aPlatformLibName[0] = '\0';
359       aPlatformLibName = strcat( aPlatformLibName, "lib" );
360       aPlatformLibName = strcat( aPlatformLibName, theLibName );
361       aPlatformLibName = strcat( aPlatformLibName, ".so" );
362 #endif
363     }
364   }
365
366
367   Unexpect aCatch(SALOME_SalomeException);
368   if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName/*theLibName*/);
369
370   // create a new hypothesis object servant
371   SMESH_Hypothesis_i* myHypothesis_i = 0;
372   SMESH::SMESH_Hypothesis_var hypothesis_i;
373
374   try
375   {
376     // check, if creator for this hypothesis type already exists
377     if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
378     {
379       // load plugin library
380       if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
381       LibHandle libHandle = LoadLib( aPlatformLibName/*theLibName*/ );
382       if (!libHandle)
383       {
384         // report any error, if occured
385 #ifndef WNT
386         const char* anError = dlerror();
387         throw(SALOME_Exception(anError));
388 #else
389         throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
390 #endif
391       }
392
393       // get method, returning hypothesis creator
394       if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
395       typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* theHypName);
396       GetHypothesisCreator procHandle =
397         (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
398       if (!procHandle)
399       {
400         throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
401         UnLoadLib(libHandle);
402       }
403
404       // get hypothesis creator
405       if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
406       GenericHypothesisCreator_i* aCreator = procHandle(theHypName);
407       if (!aCreator)
408       {
409         throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
410       }
411
412       // map hypothesis creator to a hypothesis name
413       myHypCreatorMap[string(theHypName)] = aCreator;
414     }
415
416     // create a new hypothesis object, store its ref. in studyContext
417     if(MYDEBUG) MESSAGE("Create Hypothesis " << theHypName);
418     myHypothesis_i =
419       myHypCreatorMap[string(theHypName)]->Create(myPoa, GetCurrentStudyID(), &myGen);
420     myHypothesis_i->SetLibName(aPlatformLibName/*theLibName*/); // for persistency assurance
421   }
422   catch (SALOME_Exception& S_ex)
423   {
424     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
425   }
426
427   if ( aPlatformLibName )
428     delete[] aPlatformLibName;
429
430   if (!myHypothesis_i)
431     return hypothesis_i._retn();
432
433   // activate the CORBA servant of hypothesis
434   hypothesis_i = SMESH::SMESH_Hypothesis::_narrow( myHypothesis_i->_this() );
435   int nextId = RegisterObject( hypothesis_i );
436   if(MYDEBUG) MESSAGE( "Add hypo to map with id = "<< nextId );  
437
438   return hypothesis_i._retn();
439 }
440
441 //=============================================================================
442 /*!
443  *  SMESH_Gen_i::createMesh
444  *
445  *  Create empty mesh on shape
446  */
447 //=============================================================================
448 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
449      throw ( SALOME::SALOME_Exception )
450 {
451   Unexpect aCatch(SALOME_SalomeException);
452   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
453
454   // Get or create the GEOM_Client instance
455   try {
456     // create a new mesh object servant, store it in a map in study context
457     SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
458     // create a new mesh object
459     meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
460
461     // activate the CORBA servant of Mesh
462     SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
463     int nextId = RegisterObject( mesh );
464     if(MYDEBUG) MESSAGE( "Add mesh to map with id = "<< nextId);
465     return mesh._retn();
466   }
467   catch (SALOME_Exception& S_ex) {
468     THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
469   }
470   return SMESH::SMESH_Mesh::_nil();
471 }
472
473 //=============================================================================
474 /*!
475  *  SMESH_Gen_i::GetShapeReader
476  *
477  *  Get shape reader
478  */
479 //=============================================================================
480 GEOM_Client* SMESH_Gen_i::GetShapeReader()
481 {
482   // create shape reader if necessary
483   if ( !myShapeReader ) 
484     myShapeReader = new GEOM_Client(GetContainerRef());
485   ASSERT( myShapeReader );
486   return myShapeReader;
487 }
488
489 //=============================================================================
490 /*!
491  *  SMESH_Gen_i::SetGeomEngine
492  *
493  *  Set GEOM::GEOM_Gen reference
494  */
495 //=============================================================================
496 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
497 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
498 {
499   //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
500   //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
501   myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
502   //return myGeomGen;
503 }
504
505 //=============================================================================
506 /*!
507  *  SMESH_Gen_i::SetEmbeddedMode
508  *
509  *  Set current mode
510  */
511 //=============================================================================
512
513 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
514 {
515   myIsEmbeddedMode = theMode;
516
517   if ( !myIsEmbeddedMode ) {
518     //PAL10867: disable signals catching with "noexcepthandler" option
519     char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
520     if (!envNoCatchSignals || !atoi(envNoCatchSignals))
521     {
522       bool raiseFPE;
523 #ifdef _DEBUG_
524       raiseFPE = true;
525       char* envDisableFPE = getenv("DISABLE_FPE");
526       if (envDisableFPE && atoi(envDisableFPE))
527         raiseFPE = false;
528 #else
529       raiseFPE = false;
530 #endif
531       OSD::SetSignal( raiseFPE );
532     }
533     // else OSD::SetSignal() is called in GUI
534   }
535 }
536
537 //=============================================================================
538 /*!
539  *  SMESH_Gen_i::IsEmbeddedMode
540  *
541  *  Get current mode
542  */
543 //=============================================================================
544
545 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
546 {
547   return myIsEmbeddedMode;
548 }
549
550 //=============================================================================
551 /*!
552  *  SMESH_Gen_i::SetCurrentStudy
553  *
554  *  Set current study
555  */
556 //=============================================================================
557
558 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
559 {
560   int curStudyId = GetCurrentStudyID();
561   myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
562   // create study context, if it doesn't exist and set current study
563   int studyId = GetCurrentStudyID();
564   if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() ) {
565     myStudyContextMap[ studyId ] = new StudyContext;      
566   }
567
568   // myCurrentStudy may be nil
569   if ( !CORBA::is_nil( myCurrentStudy ) ) {
570     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder(); 
571     if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
572       aStudyBuilder->LoadWith( myCurrentStudy->FindComponent( "GEOM" ), GetGeomEngine() );
573
574     // NPAL16168, issue 0020210
575     // Let meshes update their data depending on GEOM groups that could change
576     if ( curStudyId != studyId )
577     {
578       //SALOMEDS::SComponent_var me = PublishComponent( myCurrentStudy );
579       SALOMEDS::SComponent_var me = SALOMEDS::SComponent::_narrow
580         ( myCurrentStudy->FindComponent( ComponentDataType() ) );
581       if ( !me->_is_nil() ) {
582         SALOMEDS::ChildIterator_var anIter = myCurrentStudy->NewChildIterator( me );
583         for ( ; anIter->More(); anIter->Next() ) {
584           SALOMEDS::SObject_var so = anIter->Value();
585           CORBA::Object_var    ior = SObjectToObject( so );
586           if ( SMESH_Mesh_i*  mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
587             mesh->CheckGeomGroupModif();
588         }
589       }
590     }
591   }
592 }
593
594 //=============================================================================
595 /*!
596  *  SMESH_Gen_i::GetCurrentStudy
597  *
598  *  Get current study
599  */
600 //=============================================================================
601
602 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
603 {
604   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
605   return SALOMEDS::Study::_duplicate( myCurrentStudy );
606 }
607
608 //=============================================================================
609 /*!
610  *  SMESH_Gen_i::GetCurrentStudyContext 
611  *
612  *  Get current study context
613  */
614 //=============================================================================
615 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
616 {
617   if ( !CORBA::is_nil( myCurrentStudy ) &&
618       myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
619     return myStudyContextMap[ myCurrentStudy->StudyId() ];
620   else
621     return 0;
622 }
623
624 //=============================================================================
625 /*!
626  *  SMESH_Gen_i::CreateHypothesis 
627  *
628  *  Create hypothesis/algorothm of given type and publish it in the study
629  */
630 //=============================================================================
631
632 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
633                                                            const char* theLibName )
634      throw ( SALOME::SALOME_Exception )
635 {
636   Unexpect aCatch(SALOME_SalomeException);
637   // Create hypothesis/algorithm
638   SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
639
640   // Publish hypothesis/algorithm in the study
641   if ( CanPublishInStudy( hyp ) ) {
642     SALOMEDS::SObject_var aSO = PublishHypothesis( myCurrentStudy, hyp );
643     if ( !aSO->_is_nil() ) {
644       // Update Python script
645       TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
646                     << theHypName << "', '" << theLibName << "')";
647     }
648   }
649
650   return hyp._retn();
651 }
652
653 //================================================================================
654 /*!
655  * \brief Return hypothesis of given type holding parameter values of the existing mesh
656   * \param theHypType - hypothesis type name
657   * \param theLibName - plugin library name
658   * \param theMesh - The mesh of interest
659   * \param theGeom - The shape to get parameter values from
660   * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
661   *    in a study and used to compute the mesh, or a temporary one created just to pass
662   *    parameter values
663  */
664 //================================================================================
665
666 SMESH::SMESH_Hypothesis_ptr
667 SMESH_Gen_i::GetHypothesisParameterValues (const char*           theHypType,
668                                            const char*           theLibName,
669                                            SMESH::SMESH_Mesh_ptr theMesh,
670                                            GEOM::GEOM_Object_ptr theGeom)
671     throw ( SALOME::SALOME_Exception )
672 {
673   Unexpect aCatch(SALOME_SalomeException);
674   if ( CORBA::is_nil( theMesh ) )
675     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
676   if ( CORBA::is_nil( theGeom ) )
677     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
678
679   // -----------------------------------------------
680   // find hypothesis used to mesh theGeom
681   // -----------------------------------------------
682
683   // get mesh and shape
684   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
685   TopoDS_Shape shape = GeomObjectToShape( theGeom );
686   if ( !meshServant || shape.IsNull() )
687     return SMESH::SMESH_Hypothesis::_nil();
688   ::SMESH_Mesh& mesh = meshServant->GetImpl();
689
690   if ( mesh.NbNodes() == 0 ) // empty mesh
691     return SMESH::SMESH_Hypothesis::_nil();
692
693   // create a temporary hypothesis to know its dimention
694   SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
695   SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
696   if ( !hypServant )
697     return SMESH::SMESH_Hypothesis::_nil();
698   ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
699
700   // look for a hypothesis of theHypType used to mesh the shape
701   if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
702   {
703     // check local shape
704     SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
705     int nbLocalHyps = aHypList->length();
706     for ( int i = 0; i < nbLocalHyps; i++ )
707       if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND local!
708         return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
709     // check super shapes
710     TopTools_ListIteratorOfListOfShape itShape( mesh.GetAncestors( shape ));
711     while ( nbLocalHyps == 0 && itShape.More() ) {
712       GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
713       if ( ! CORBA::is_nil( geomObj )) {
714         SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
715         nbLocalHyps = aHypList->length();
716         for ( int i = 0; i < nbLocalHyps; i++ )
717           if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
718             return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
719       }
720       itShape.Next();
721     }
722   }
723
724   // let the temporary hypothesis find out some how parameter values
725   if ( hyp->SetParametersByMesh( &mesh, shape ))
726     return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
727     
728   return SMESH::SMESH_Hypothesis::_nil();
729 }
730
731 //=============================================================================
732 /*!
733  *  SMESH_Gen_i::CreateMesh
734  *
735  *  Create empty mesh on a shape and publish it in the study
736  */
737 //=============================================================================
738
739 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
740      throw ( SALOME::SALOME_Exception )
741 {
742   Unexpect aCatch(SALOME_SalomeException);
743   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
744   // create mesh
745   SMESH::SMESH_Mesh_var mesh = this->createMesh();
746   // set shape
747   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
748   ASSERT( meshServant );
749   meshServant->SetShape( theShapeObject );
750
751   // publish mesh in the study
752   if ( CanPublishInStudy( mesh ) ) {
753     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
754     aStudyBuilder->NewCommand();  // There is a transaction
755     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
756     aStudyBuilder->CommitCommand();
757     if ( !aSO->_is_nil() ) {
758       // Update Python script
759       TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
760     }
761   }
762
763   return mesh._retn();
764 }
765
766 //=============================================================================
767 /*!
768  *  SMESH_Gen_i::CreateEmptyMesh
769  *
770  *  Create empty mesh
771  */
772 //=============================================================================
773
774 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
775      throw ( SALOME::SALOME_Exception )
776 {
777   Unexpect aCatch(SALOME_SalomeException);
778   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
779   // create mesh
780   SMESH::SMESH_Mesh_var mesh = this->createMesh();
781
782   // publish mesh in the study
783   if ( CanPublishInStudy( mesh ) ) {
784     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
785     aStudyBuilder->NewCommand();  // There is a transaction
786     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
787     aStudyBuilder->CommitCommand();
788     if ( !aSO->_is_nil() ) {
789       // Update Python script
790       TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
791     }
792   }
793
794   return mesh._retn();
795 }
796
797 //=============================================================================
798 /*!
799  *  SMESH_Gen_i::CreateMeshFromUNV
800  *
801  *  Create mesh and import data from UNV file
802  */
803 //=============================================================================
804
805 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
806   throw ( SALOME::SALOME_Exception )
807 {
808   Unexpect aCatch(SALOME_SalomeException);
809   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromUNV" );
810
811   SMESH::SMESH_Mesh_var aMesh = createMesh();
812   string aFileName;
813   // publish mesh in the study
814   if ( CanPublishInStudy( aMesh ) ) {
815     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
816     aStudyBuilder->NewCommand();  // There is a transaction
817     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
818     aStudyBuilder->CommitCommand();
819     if ( !aSO->_is_nil() ) {
820       // Update Python script
821       TPythonDump() << aSO << " = smeshgen.CreateMeshesFromUNV('" << theFileName << "')";
822     }
823   }
824
825   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
826   ASSERT( aServant );
827   aServant->ImportUNVFile( theFileName );
828
829   // Dump creation of groups
830   aServant->GetGroups();
831
832   return aMesh._retn();
833 }
834
835 //=============================================================================
836 /*!
837  *  SMESH_Gen_i::CreateMeshFromMED
838  *
839  *  Create mesh and import data from MED file
840  */
841 //=============================================================================
842
843 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
844                                                      SMESH::DriverMED_ReadStatus& theStatus)
845      throw ( SALOME::SALOME_Exception )
846 {
847   Unexpect aCatch(SALOME_SalomeException);
848   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshFromMED" );
849
850   // Retrieve mesh names from the file
851   DriverMED_R_SMESHDS_Mesh myReader;
852   myReader.SetFile( theFileName );
853   myReader.SetMeshId( -1 );
854   Driver_Mesh::Status aStatus;
855   list<string> aNames = myReader.GetMeshNames(aStatus);
856   SMESH::mesh_array_var aResult = new SMESH::mesh_array();
857   theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
858
859   { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
860
861   // Python Dump
862   TPythonDump aPythonDump;
863   aPythonDump << "([";
864   //TCollection_AsciiString aStr ("([");
865
866   if (theStatus == SMESH::DRS_OK) {
867     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
868     aStudyBuilder->NewCommand();  // There is a transaction
869     aResult->length( aNames.size() );
870     int i = 0;
871     
872     // Iterate through all meshes and create mesh objects
873     for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ ) {
874       // Python Dump
875       //if (i > 0) aStr += ", ";
876       if (i > 0) aPythonDump << ", ";
877
878       // create mesh
879       SMESH::SMESH_Mesh_var mesh = createMesh();
880       
881       // publish mesh in the study
882       SALOMEDS::SObject_var aSO;
883       if ( CanPublishInStudy( mesh ) )
884         aSO = PublishMesh( myCurrentStudy, mesh.in(), (*it).c_str() );
885       if ( !aSO->_is_nil() ) {
886         // Python Dump
887         aPythonDump << aSO;
888         //aStr += aSO->GetID();
889       } else {
890         // Python Dump
891         aPythonDump << "mesh_" << i;
892 //         aStr += "mesh_";
893 //         aStr += TCollection_AsciiString(i);
894       }
895
896       // Read mesh data (groups are published automatically by ImportMEDFile())
897       SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
898       ASSERT( meshServant );
899       SMESH::DriverMED_ReadStatus status1 =
900         meshServant->ImportMEDFile( theFileName, (*it).c_str() );
901       if (status1 > theStatus)
902         theStatus = status1;
903
904       aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
905     }
906     aStudyBuilder->CommitCommand();
907   }
908
909   // Update Python script
910   aPythonDump << "], status) = " << this << ".CreateMeshesFromMED('" << theFileName << "')";
911   }
912   // Dump creation of groups
913   for ( int i = 0; i < aResult->length(); ++i )
914     aResult[ i ]->GetGroups();
915
916   return aResult._retn();
917 }
918
919 //=============================================================================
920 /*!
921  *  SMESH_Gen_i::CreateMeshFromSTL
922  *
923  *  Create mesh and import data from STL file
924  */
925 //=============================================================================
926
927 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
928   throw ( SALOME::SALOME_Exception )
929 {
930   Unexpect aCatch(SALOME_SalomeException);
931   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromSTL" );
932
933   SMESH::SMESH_Mesh_var aMesh = createMesh();
934   string aFileName;
935   // publish mesh in the study
936   if ( CanPublishInStudy( aMesh ) ) {
937     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
938     aStudyBuilder->NewCommand();  // There is a transaction
939     SALOMEDS::SObject_var aSO = PublishInStudy
940       ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
941     aStudyBuilder->CommitCommand();
942     if ( !aSO->_is_nil() ) {
943       // Update Python script
944       TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL('" << theFileName << "')";
945     }
946   }
947
948   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
949   ASSERT( aServant );
950   aServant->ImportSTLFile( theFileName );
951   return aMesh._retn();
952 }
953
954 //=============================================================================
955 /*!
956  *  SMESH_Gen_i::IsReadyToCompute
957  *
958  *  Returns true if mesh contains enough data to be computed
959  */
960 //=============================================================================
961
962 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
963                                               GEOM::GEOM_Object_ptr theShapeObject )
964   throw ( SALOME::SALOME_Exception )
965 {
966   Unexpect aCatch(SALOME_SalomeException);
967   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
968
969   if ( CORBA::is_nil( theShapeObject ) )
970     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
971                                   SALOME::BAD_PARAM );
972
973   if ( CORBA::is_nil( theMesh ) )
974     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
975                                   SALOME::BAD_PARAM );
976
977   try {
978     // get mesh servant
979     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
980     ASSERT( meshServant );
981     if ( meshServant ) {
982       // get local TopoDS_Shape
983       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
984       // call implementation
985       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
986       return myGen.CheckAlgoState( myLocMesh, myLocShape );
987     }
988   }
989   catch ( SALOME_Exception& S_ex ) {
990     INFOS( "catch exception "<< S_ex.what() );
991   }
992   return false;
993 }
994
995 //================================================================================
996 /*!
997  * \brief  Find SObject for an algo
998  */
999 //================================================================================
1000
1001 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1002 {
1003   if ( algo ) {
1004     if ( !myCurrentStudy->_is_nil() ) {
1005       // find algo in the study
1006       SALOMEDS::SComponent_var father = SALOMEDS::SComponent::_narrow
1007         ( myCurrentStudy->FindComponent( ComponentDataType() ) );
1008       if ( !father->_is_nil() ) {
1009         SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( father );
1010         for ( ; itBig->More(); itBig->Next() ) {
1011           SALOMEDS::SObject_var gotBranch = itBig->Value();
1012           if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1013             SALOMEDS::ChildIterator_var algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1014             for ( ; algoIt->More(); algoIt->Next() ) {
1015               SALOMEDS::SObject_var algoSO = algoIt->Value();
1016               CORBA::Object_var     algoIOR = SObjectToObject( algoSO );
1017               if ( !CORBA::is_nil( algoIOR )) {
1018                 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1019                 if ( impl && impl->GetImpl() == algo )
1020                   return algoSO._retn();
1021               }
1022             } // loop on algo SO's
1023             break;
1024           } // if algo tag
1025         } // SMESH component iterator
1026       }
1027     }
1028   }
1029   return SALOMEDS::SObject::_nil();
1030 }
1031
1032 //================================================================================
1033 /*!
1034  * \brief Return errors of mesh computation
1035  */
1036 //================================================================================
1037
1038 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh, 
1039                                                            GEOM::GEOM_Object_ptr theSubObject )
1040   throw ( SALOME::SALOME_Exception )
1041 {
1042   Unexpect aCatch(SALOME_SalomeException);
1043   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1044
1045   if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1046     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1047
1048   if ( CORBA::is_nil( theMesh ) )
1049     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1050
1051   SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1052   try {
1053     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1054     {
1055       TopoDS_Shape shape;
1056       if(theMesh->HasShapeToMesh())
1057         shape = GeomObjectToShape( theSubObject );
1058       else
1059         shape = SMESH_Mesh::PseudoShape();
1060       
1061       ::SMESH_Mesh& mesh = meshServant->GetImpl();
1062
1063       error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1064       int nbErr = 0;
1065
1066       SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1067       const bool includeSelf = true, complexShapeFirst = true;
1068       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1069                                                                complexShapeFirst);
1070       while ( smIt->more() )
1071       {
1072         sm = smIt->next();
1073         if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1074           break;
1075         SMESH_ComputeErrorPtr error = sm->GetComputeError();
1076         if ( error && !error->IsOK() && error->myAlgo )
1077         {
1078           SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1079           errStruct.code       = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1080           errStruct.comment    = error->myComment.c_str();
1081           errStruct.subShapeID = sm->GetId();
1082           SALOMEDS::SObject_var algoSO = GetAlgoSO( error->myAlgo );
1083           if ( !algoSO->_is_nil() )
1084             errStruct.algoName = algoSO->GetName();
1085           else
1086             errStruct.algoName = error->myAlgo->GetName();
1087           errStruct.hasBadMesh = !error->myBadElements.empty();
1088         }
1089       }
1090       error_array->length( nbErr );
1091     }
1092   }
1093   catch ( SALOME_Exception& S_ex ) {
1094     INFOS( "catch exception "<< S_ex.what() );
1095   }
1096
1097   return error_array._retn();
1098 }
1099
1100 // 
1101 //================================================================================
1102 /*!
1103  * \brief Return mesh elements preventing computation of a subshape
1104  */
1105 //================================================================================
1106
1107 SMESH::MeshPreviewStruct*
1108 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1109                                   CORBA::Short          theSubShapeID )
1110   throw ( SALOME::SALOME_Exception )
1111 {
1112   Unexpect aCatch(SALOME_SalomeException);
1113   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1114
1115   if ( CORBA::is_nil( theMesh ) )
1116     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1117
1118   SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1119   try {
1120     // mesh servant
1121     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1122     {
1123       // mesh implementation
1124       ::SMESH_Mesh& mesh = meshServant->GetImpl();
1125       // submesh by subshape id
1126       if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1127       {
1128         // compute error
1129         SMESH_ComputeErrorPtr error = sm->GetComputeError();
1130         if ( error && !error->myBadElements.empty())
1131         {
1132           typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1133           typedef TNode2LocalIDMap::iterator         TNodeLocalID;
1134
1135           // get nodes of elements and count elements
1136           TNode2LocalIDMap mapNode2LocalID;
1137           list< TNodeLocalID > connectivity;
1138           int i, nbElements = 0, nbConnNodes = 0;
1139
1140           list<const SMDS_MeshElement*>::iterator elemIt  = error->myBadElements.begin();
1141           list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1142           for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1143           {
1144             SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1145             while ( nIt->more() )
1146               connectivity.push_back
1147                 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1148           }
1149           // fill node coords and assign local ids to the nodes
1150           int nbNodes = mapNode2LocalID.size();
1151           result->nodesXYZ.length( nbNodes );
1152           TNodeLocalID node2ID = mapNode2LocalID.begin();
1153           for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1154             node2ID->second = i;
1155             const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1156             result->nodesXYZ[i].x = node->X();
1157             result->nodesXYZ[i].y = node->Y();
1158             result->nodesXYZ[i].z = node->Z();
1159           }
1160           // fill connectivity
1161           result->elementConnectivities.length( nbConnNodes );
1162           list< TNodeLocalID >::iterator connIt = connectivity.begin();
1163           for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1164             result->elementConnectivities[i] = (*connIt)->second;
1165           }
1166           // fill element types
1167           result->elementTypes.length( nbElements );
1168           for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1169           {
1170             const SMDS_MeshElement* elem = *elemIt;
1171             result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1172             result->elementTypes[i].isPoly           = elem->IsPoly();
1173             result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1174           }
1175         }
1176       }
1177     }
1178   }
1179   catch ( SALOME_Exception& S_ex ) {
1180     INFOS( "catch exception "<< S_ex.what() );
1181   }
1182
1183   return result._retn();
1184 }
1185
1186 //================================================================================
1187 /*!
1188  * \brief Returns errors of hypotheses definintion
1189  * \param theMesh - the mesh
1190  * \param theSubObject - the main or sub- shape
1191  * \retval SMESH::algo_error_array* - sequence of errors
1192  */
1193 //================================================================================
1194
1195 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh, 
1196                                                     GEOM::GEOM_Object_ptr theSubObject )
1197       throw ( SALOME::SALOME_Exception )
1198 {
1199   Unexpect aCatch(SALOME_SalomeException);
1200   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1201
1202   if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1203     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1204
1205   if ( CORBA::is_nil( theMesh ) )
1206     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1207
1208   SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1209   try {
1210     SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1211     ASSERT( meshServant );
1212     if ( meshServant ) {
1213       TopoDS_Shape myLocShape;
1214       if(theMesh->HasShapeToMesh())
1215         myLocShape = GeomObjectToShape( theSubObject );
1216       else
1217         myLocShape = SMESH_Mesh::PseudoShape();
1218       
1219       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1220       list< ::SMESH_Gen::TAlgoStateError > error_list;
1221       list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1222       // call ::SMESH_Gen::GetAlgoState()
1223       myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1224       error_array->length( error_list.size() );
1225       int i = 0;
1226       for ( error = error_list.begin(); error != error_list.end(); ++error )
1227       {
1228         // fill AlgoStateError structure
1229         SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1230         errStruct.state        = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1231         errStruct.algoDim      = error->_algoDim;
1232         errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1233         errStruct.algoName     = "";
1234         SALOMEDS::SObject_var algoSO = GetAlgoSO( error->_algo );
1235         if ( !algoSO->_is_nil() )
1236           errStruct.algoName   = algoSO->GetName();
1237       }
1238     }
1239   }
1240   catch ( SALOME_Exception& S_ex ) {
1241     INFOS( "catch exception "<< S_ex.what() );
1242   }
1243   return error_array._retn();
1244 }
1245
1246 //=============================================================================
1247 /*!
1248  *  SMESH_Gen_i::GetSubShapesId
1249  *
1250  *  Get sub-shapes unique ID's list
1251  */
1252 //=============================================================================
1253
1254 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1255                                             const SMESH::object_array& theListOfSubShapeObject )
1256      throw ( SALOME::SALOME_Exception )
1257 {
1258   Unexpect aCatch(SALOME_SalomeException);
1259   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1260
1261   SMESH::long_array_var shapesId = new SMESH::long_array;
1262   set<int> setId;
1263
1264   if ( CORBA::is_nil( theMainShapeObject ) )
1265     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1266                                   SALOME::BAD_PARAM );
1267
1268   try
1269     {
1270       TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1271       TopTools_IndexedMapOfShape myIndexToShape;      
1272       TopExp::MapShapes(myMainShape,myIndexToShape);
1273
1274       for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
1275         {
1276           GEOM::GEOM_Object_var aShapeObject
1277             = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1278           if ( CORBA::is_nil( aShapeObject ) )
1279             THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1280                                         SALOME::BAD_PARAM );
1281
1282           TopoDS_Shape locShape  = GeomObjectToShape(aShapeObject);
1283           for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1284             {
1285               const TopoDS_Face& F = TopoDS::Face(exp.Current());
1286               setId.insert(myIndexToShape.FindIndex(F));
1287               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1288             }
1289           for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1290             {
1291               const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1292               setId.insert(myIndexToShape.FindIndex(E));
1293               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1294             }
1295           for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1296             {
1297               const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1298               setId.insert(myIndexToShape.FindIndex(V));
1299               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1300             }
1301         }
1302       shapesId->length(setId.size());
1303       set<int>::iterator iind;
1304       int i=0;
1305       for (iind = setId.begin(); iind != setId.end(); iind++)
1306         {
1307           if(MYDEBUG) SCRUTE((*iind));
1308           shapesId[i] = (*iind);
1309           if(MYDEBUG) SCRUTE(shapesId[i]);
1310           i++;
1311         }
1312     }
1313   catch (SALOME_Exception& S_ex)
1314     {
1315       THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1316     }
1317
1318   return shapesId._retn();
1319 }
1320
1321 //=============================================================================
1322 /*!
1323  *  SMESH_Gen_i::Compute
1324  *
1325  *  Compute mesh on a shape
1326  */
1327 //=============================================================================
1328
1329 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1330                                      GEOM::GEOM_Object_ptr theShapeObject )
1331      throw ( SALOME::SALOME_Exception )
1332 {
1333   Unexpect aCatch(SALOME_SalomeException);
1334   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1335
1336   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1337     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
1338                                   SALOME::BAD_PARAM );
1339
1340   if ( CORBA::is_nil( theMesh ) )
1341     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1342                                   SALOME::BAD_PARAM );
1343
1344   // Update Python script
1345   TPythonDump() << "isDone = " << this << ".Compute( "
1346                 << theMesh << ", " << theShapeObject << ")";
1347
1348   try {
1349     // get mesh servant
1350     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1351     ASSERT( meshServant );
1352     if ( meshServant ) {
1353       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1354       meshServant->CheckGeomGroupModif();
1355       // get local TopoDS_Shape
1356       TopoDS_Shape myLocShape;
1357       if(theMesh->HasShapeToMesh())
1358         myLocShape = GeomObjectToShape( theShapeObject );
1359       else
1360         myLocShape = SMESH_Mesh::PseudoShape();
1361       // call implementation compute
1362       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1363       return myGen.Compute( myLocMesh, myLocShape);
1364     }
1365   }
1366   catch ( std::bad_alloc ) {
1367     INFOS( "Compute(): lack of memory" );
1368   }
1369   catch ( SALOME_Exception& S_ex ) {
1370     INFOS( "Compute(): catch exception "<< S_ex.what() );
1371   }
1372   catch ( ... ) {
1373     INFOS( "Compute(): unknown exception " );
1374   }
1375   return false;
1376 }
1377
1378 //================================================================================
1379 /*!
1380  * \brief Return geometrical object the given element is built on
1381  *  \param theMesh - the mesh the element is in
1382  *  \param theElementID - the element ID
1383  *  \param theGeomName - the name of the result geom object if it is not yet published
1384  *  \retval GEOM::GEOM_Object_ptr - the found or just published geom object
1385  */
1386 //================================================================================
1387
1388 GEOM::GEOM_Object_ptr
1389 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
1390                                        CORBA::Long            theElementID,
1391                                        const char*            theGeomName)
1392   throw ( SALOME::SALOME_Exception )
1393 {
1394   Unexpect aCatch(SALOME_SalomeException);
1395  
1396   GEOM::GEOM_Object_var geom = FindGeometryByMeshElement(theMesh, theElementID);
1397   if ( !geom->_is_nil() ) {
1398     GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
1399     GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
1400
1401     // try to find the corresponding SObject
1402     SALOMEDS::SObject_var SObj = ObjectToSObject( myCurrentStudy, geom.in() );
1403     if ( SObj->_is_nil() ) // submesh can be not found even if published
1404     {
1405       // try to find published submesh
1406       GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
1407       if ( !geom->IsMainShape() && list->length() == 1 ) {
1408         SALOMEDS::SObject_var mainSO = ObjectToSObject( myCurrentStudy, mainShape );
1409         SALOMEDS::ChildIterator_var it;
1410         if ( !mainSO->_is_nil() )
1411           it = myCurrentStudy->NewChildIterator( mainSO );
1412         if ( !it->_is_nil() ) {
1413           for ( it->InitEx(true); SObj->_is_nil() && it->More(); it->Next() ) {
1414             GEOM::GEOM_Object_var subGeom =
1415               GEOM::GEOM_Object::_narrow( SObjectToObject( it->Value() ));
1416             if ( !subGeom->_is_nil() ) {
1417               GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
1418               if ( subList->length() == 1 && list[0] == subList[0] ) {
1419                 SObj = it->Value();
1420                 geom = subGeom;
1421               }
1422             }
1423           }
1424         }
1425       }
1426     }
1427     if ( SObj->_is_nil() ) // publish a new subshape
1428       SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
1429
1430     // return only published geometry
1431     if ( !SObj->_is_nil() )
1432       return geom._retn();
1433   }
1434   return GEOM::GEOM_Object::_nil();
1435 }
1436
1437 //================================================================================
1438 /*!
1439  * \brief Return geometrical object the given element is built on.
1440  *  \param theMesh - the mesh the element is in
1441  *  \param theElementID - the element ID
1442  *  \retval GEOM::GEOM_Object_ptr - the found geom object
1443  */
1444 //================================================================================
1445
1446 GEOM::GEOM_Object_ptr
1447 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
1448                                         CORBA::Long            theElementID)
1449   throw ( SALOME::SALOME_Exception )
1450 {
1451   Unexpect aCatch(SALOME_SalomeException);
1452   if ( CORBA::is_nil( theMesh ) )
1453     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
1454
1455   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
1456   GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
1457
1458   // get a core mesh DS
1459   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1460   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
1461   {
1462     ::SMESH_Mesh & mesh = meshServant->GetImpl();
1463     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
1464     // find the element in mesh
1465     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
1466       // find a shape id by the element
1467       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
1468         // get a geom object by the shape id
1469         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
1470         if ( geom->_is_nil() ) {
1471           // try to find a published sub-shape
1472           SALOMEDS::SObject_var mainSO = ObjectToSObject( myCurrentStudy, mainShape );
1473           SALOMEDS::ChildIterator_var it;
1474           if ( !mainSO->_is_nil() )
1475             it = myCurrentStudy->NewChildIterator( mainSO );
1476           if ( !it->_is_nil() ) {
1477             for ( it->InitEx(true); it->More(); it->Next() ) {
1478               GEOM::GEOM_Object_var subGeom =
1479                 GEOM::GEOM_Object::_narrow( SObjectToObject( it->Value() ));
1480               if ( !subGeom->_is_nil() ) {
1481                 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
1482                 if ( subList->length() == 1 && shapeID == subList[0] ) {
1483                   geom = subGeom;
1484                   break;
1485                 }
1486               }
1487             }
1488           }
1489         }
1490         if ( geom->_is_nil() ) {
1491           // explode
1492           GEOM::GEOM_IShapesOperations_var op =
1493             geomGen->GetIShapesOperations( GetCurrentStudyID() );
1494           if ( !op->_is_nil() )
1495             geom = op->GetSubShape( mainShape, shapeID );
1496         }
1497         if ( !geom->_is_nil() ) {
1498           GeomObjectToShape( geom ); // let geom client remember the found shape
1499           return geom._retn();
1500         }
1501       }
1502     }
1503   }
1504   return GEOM::GEOM_Object::_nil();
1505 }
1506
1507 //================================================================================
1508 /*!
1509  *  SMESH_Gen_i::Concatenate
1510  *
1511  *  Concatenate the given meshes into one mesh
1512  */
1513 //================================================================================
1514
1515 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::Concatenate(const SMESH::mesh_array& theMeshesArray,
1516                                                CORBA::Boolean           theUniteIdenticalGroups, 
1517                                                CORBA::Boolean           theMergeNodesAndElements, 
1518                                                CORBA::Double            theMergeTolerance)
1519   throw ( SALOME::SALOME_Exception )
1520 {
1521   return ConcatenateCommon(theMeshesArray,
1522                            theUniteIdenticalGroups,
1523                            theMergeNodesAndElements,
1524                            theMergeTolerance,
1525                            false);
1526 }
1527
1528 //================================================================================
1529 /*!
1530  *  SMESH_Gen_i::ConcatenateWithGroups
1531  *
1532  *  Concatenate the given meshes into one mesh
1533  *  Create the groups of all elements from initial meshes
1534  */
1535 //================================================================================
1536
1537 SMESH::SMESH_Mesh_ptr
1538 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::mesh_array& theMeshesArray,
1539                                    CORBA::Boolean           theUniteIdenticalGroups, 
1540                                    CORBA::Boolean           theMergeNodesAndElements, 
1541                                    CORBA::Double            theMergeTolerance)
1542   throw ( SALOME::SALOME_Exception )
1543 {
1544   return ConcatenateCommon(theMeshesArray,
1545                            theUniteIdenticalGroups,
1546                            theMergeNodesAndElements,
1547                            theMergeTolerance,
1548                            true);
1549 }
1550
1551 //================================================================================
1552 /*!
1553  *  SMESH_Gen_i::ConcatenateCommon
1554  *
1555  *  Concatenate the given meshes into one mesh
1556  */
1557 //================================================================================
1558
1559 SMESH::SMESH_Mesh_ptr
1560 SMESH_Gen_i::ConcatenateCommon(const SMESH::mesh_array& theMeshesArray,
1561                                CORBA::Boolean           theUniteIdenticalGroups, 
1562                                CORBA::Boolean           theMergeNodesAndElements, 
1563                                CORBA::Double            theMergeTolerance,
1564                                CORBA::Boolean           theCommonGroups)
1565   throw ( SALOME::SALOME_Exception )
1566 {
1567   typedef map<int, int> TIDsMap;
1568   typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
1569   typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
1570   typedef std::set<SMESHDS_GroupBase*> TGroups;
1571
1572   TPythonDump aPythonDump; // prevent dump of called methods
1573
1574   // create mesh
1575   SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
1576   
1577   if ( !aNewMesh->_is_nil() ) {
1578     SMESH_Mesh_i* aNewImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( aNewMesh ).in() );
1579     if ( aNewImpl ) {
1580       ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
1581       SMESHDS_Mesh* aNewMeshDS = aLocMesh.GetMeshDS();
1582
1583       TGroupsMap aGroupsMap;
1584       TListOfNewGroups aListOfNewGroups;
1585       SMESH_MeshEditor aNewEditor = ::SMESH_MeshEditor(&aLocMesh);
1586       SMESH::ListOfGroups_var aListOfGroups = new SMESH::ListOfGroups();
1587
1588       // loop on meshes
1589       for ( int i = 0; i < theMeshesArray.length(); i++) {
1590         SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i];
1591         if ( !anInitMesh->_is_nil() ) {
1592           SMESH_Mesh_i* anInitImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( anInitMesh ).in() );
1593           if ( anInitImpl ) {
1594             ::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
1595             SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
1596
1597             TIDsMap nodesMap;
1598             TIDsMap elemsMap;
1599
1600             // loop on elements of mesh
1601             SMDS_ElemIteratorPtr itElems = anInitMeshDS->elementsIterator();
1602             const SMDS_MeshElement* anElem = 0;
1603             const SMDS_MeshElement* aNewElem = 0;
1604             int anElemNbNodes = 0;
1605
1606             int anNbNodes   = 0;
1607             int anNbEdges   = 0;
1608             int anNbFaces   = 0;
1609             int anNbVolumes = 0;
1610
1611             SMESH::long_array_var anIDsNodes   = new SMESH::long_array();
1612             SMESH::long_array_var anIDsEdges   = new SMESH::long_array();
1613             SMESH::long_array_var anIDsFaces   = new SMESH::long_array();
1614             SMESH::long_array_var anIDsVolumes = new SMESH::long_array();
1615
1616             if( theCommonGroups ) {
1617               anIDsNodes->length(   anInitMeshDS->NbNodes()   );
1618               anIDsEdges->length(   anInitMeshDS->NbEdges()   );
1619               anIDsFaces->length(   anInitMeshDS->NbFaces()   );
1620               anIDsVolumes->length( anInitMeshDS->NbVolumes() );
1621             }
1622
1623             for ( int j = 0; itElems->more(); j++) {
1624               anElem = itElems->next();
1625               SMDSAbs_ElementType anElemType = anElem->GetType();
1626               anElemNbNodes = anElem->NbNodes();
1627               std::vector<const SMDS_MeshNode*> aNodesArray (anElemNbNodes);
1628
1629               // loop on nodes of element
1630               const SMDS_MeshNode* aNode = 0;
1631               const SMDS_MeshNode* aNewNode = 0;
1632               SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
1633
1634               for ( int k = 0; itNodes->more(); k++) {
1635                 aNode = static_cast<const SMDS_MeshNode*>(itNodes->next());
1636                 if ( nodesMap.find(aNode->GetID()) == nodesMap.end() ) {
1637                   aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
1638                   nodesMap.insert( make_pair(aNode->GetID(), aNewNode->GetID()) );
1639                   if( theCommonGroups )
1640                     anIDsNodes[anNbNodes++] = aNewNode->GetID();
1641                 }
1642                 else
1643                   aNewNode = aNewMeshDS->FindNode( nodesMap.find(aNode->GetID())->second );
1644                 aNodesArray[k] = aNewNode;
1645               }//nodes loop
1646
1647               // creates a corresponding element on existent nodes in new mesh
1648               if ( anElem->IsPoly() && anElemType == SMDSAbs_Volume )
1649                 {
1650                   const SMDS_PolyhedralVolumeOfNodes* aVolume =
1651                     dynamic_cast<const SMDS_PolyhedralVolumeOfNodes*> (anElem);
1652                   if ( aVolume ) {
1653                     aNewElem = aNewMeshDS->AddPolyhedralVolume(aNodesArray, 
1654                                                                aVolume->GetQuanities());
1655                     elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
1656                     if( theCommonGroups )
1657                       anIDsVolumes[anNbVolumes++] = aNewElem->GetID();
1658                   }
1659                 }
1660               else {
1661                 
1662                 aNewElem = aNewEditor.AddElement(aNodesArray,
1663                                                  anElemType,
1664                                                  anElem->IsPoly());
1665                 elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
1666                 if( theCommonGroups ) {
1667                   if( anElemType == SMDSAbs_Edge )
1668                     anIDsEdges[anNbEdges++] = aNewElem->GetID();
1669                   else if( anElemType == SMDSAbs_Face )
1670                     anIDsFaces[anNbFaces++] = aNewElem->GetID();
1671                   else if( anElemType == SMDSAbs_Volume )
1672                     anIDsVolumes[anNbVolumes++] = aNewElem->GetID();
1673                 }
1674               } 
1675             }//elems loop
1676             
1677             aListOfGroups = anInitImpl->GetGroups();
1678             SMESH::SMESH_GroupBase_ptr aGroup;
1679
1680             // loop on groups of mesh
1681             SMESH::long_array_var anInitIDs = new SMESH::long_array();
1682             SMESH::long_array_var anNewIDs = new SMESH::long_array();
1683             SMESH::SMESH_Group_var aNewGroup;
1684
1685             SMESH::ElementType aGroupType;
1686             CORBA::String_var aGroupName;
1687             if ( theCommonGroups ) {
1688               for(aGroupType=SMESH::NODE;aGroupType<=SMESH::VOLUME;aGroupType=(SMESH::ElementType)(aGroupType+1)) {
1689                 string str = "Gr";
1690                 SALOMEDS::SObject_var aMeshSObj = ObjectToSObject( myCurrentStudy, anInitMesh );
1691                 if(aMeshSObj)
1692                   str += aMeshSObj->GetName();
1693                 str += "_";
1694
1695                 int anLen = 0;
1696
1697                 switch(aGroupType) {
1698                 case SMESH::NODE:
1699                   str += "Nodes";
1700                   anIDsNodes->length(anNbNodes);
1701                   anLen = anNbNodes;
1702                   break;
1703                 case SMESH::EDGE:
1704                   str += "Edges";
1705                   anIDsEdges->length(anNbEdges);
1706                   anLen = anNbEdges;
1707                   break;
1708                 case SMESH::FACE:
1709                   str += "Faces";
1710                   anIDsFaces->length(anNbFaces);
1711                   anLen = anNbFaces;
1712                   break;
1713                 case SMESH::VOLUME:
1714                   str += "Volumes";
1715                   anIDsVolumes->length(anNbVolumes);
1716                   anLen = anNbVolumes;
1717                   break;
1718                 default:
1719                   break;
1720                 }
1721
1722                 if(anLen) {
1723                   aGroupName = str.c_str();
1724
1725                   // add a new group in the mesh
1726                   aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
1727
1728                   switch(aGroupType) {
1729                   case SMESH::NODE:
1730                     aNewGroup->Add( anIDsNodes );
1731                     break;
1732                   case SMESH::EDGE:
1733                     aNewGroup->Add( anIDsEdges );
1734                     break;
1735                   case SMESH::FACE:
1736                     aNewGroup->Add( anIDsFaces );
1737                     break;
1738                   case SMESH::VOLUME:
1739                     aNewGroup->Add( anIDsVolumes );
1740                     break;
1741                   default:
1742                     break;
1743                   }
1744                 
1745                   aListOfNewGroups.clear();
1746                   aListOfNewGroups.push_back(aNewGroup);
1747                   aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
1748                 }
1749               }
1750             }
1751
1752             // check that current group name and type don't have identical ones in union mesh
1753             for (int i = 0; i < aListOfGroups->length(); i++) {
1754               aGroup = aListOfGroups[i];
1755               aListOfNewGroups.clear();
1756               aGroupType = aGroup->GetType();
1757               aGroupName = aGroup->GetName();
1758
1759               TGroupsMap::iterator anIter = aGroupsMap.find(make_pair(aGroupName, aGroupType));
1760
1761               // convert a list of IDs
1762               anInitIDs = aGroup->GetListOfID();
1763               anNewIDs->length(anInitIDs->length());
1764               if ( aGroupType == SMESH::NODE )
1765                 for (int j = 0; j < anInitIDs->length(); j++) {
1766                   anNewIDs[j] = nodesMap.find(anInitIDs[j])->second;
1767                 }
1768               else
1769                 for (int j = 0; j < anInitIDs->length(); j++) {
1770                   anNewIDs[j] = elemsMap.find(anInitIDs[j])->second;
1771                 }
1772               
1773               // check that current group name and type don't have identical ones in union mesh
1774               if ( anIter == aGroupsMap.end() ) {
1775                 // add a new group in the mesh
1776                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
1777                 // add elements into new group
1778                 aNewGroup->Add( anNewIDs );
1779                 
1780                 aListOfNewGroups.push_back(aNewGroup);
1781                 aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
1782               }
1783
1784               else if ( theUniteIdenticalGroups ) {
1785                 // unite identical groups
1786                 TListOfNewGroups& aNewGroups = anIter->second;
1787                 aNewGroups.front()->Add( anNewIDs );
1788               }
1789
1790               else {
1791                 // rename identical groups
1792                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
1793                 aNewGroup->Add( anNewIDs );
1794                 
1795                 TListOfNewGroups& aNewGroups = anIter->second;
1796                 string aNewGroupName;
1797                 if (aNewGroups.size() == 1) {
1798                   aNewGroupName = string(aGroupName) + "_1";
1799                   aNewGroups.front()->SetName(aNewGroupName.c_str());
1800                 }
1801                 char aGroupNum[128];
1802                 sprintf(aGroupNum, "%u", aNewGroups.size()+1);
1803                 aNewGroupName = string(aGroupName) + "_" + string(aGroupNum);
1804                 aNewGroup->SetName(aNewGroupName.c_str());
1805                 aNewGroups.push_back(aNewGroup);
1806               }
1807             }//groups loop
1808           }
1809         }
1810       }//meshes loop
1811
1812       if (theMergeNodesAndElements) {
1813         // merge nodes
1814         set<const SMDS_MeshNode*> aMeshNodes; // no input nodes
1815         SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
1816         aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes );
1817         aNewEditor.MergeNodes( aGroupsOfNodes );
1818         // merge elements
1819         aNewEditor.MergeEqualElements();
1820       }
1821     }
1822   }
1823   
1824   // Update Python script
1825   aPythonDump << aNewMesh << " = " << this;
1826   if( !theCommonGroups )
1827     aPythonDump << ".Concatenate(";
1828   else
1829     aPythonDump << ".ConcatenateWithGroups(";
1830   aPythonDump << "[";
1831   for ( int i = 0; i < theMeshesArray.length(); i++) {
1832     if (i > 0) aPythonDump << ", ";
1833     aPythonDump << theMeshesArray[i];
1834   }
1835   aPythonDump << "], ";
1836   aPythonDump << theUniteIdenticalGroups << ", "
1837               << theMergeNodesAndElements << ", "
1838               << theMergeTolerance << ")";
1839
1840   return aNewMesh._retn();
1841 }
1842
1843 //=============================================================================
1844 /*!
1845  *  SMESH_Gen_i::Save
1846  *
1847  *  Save SMESH module's data
1848  */
1849 //=============================================================================
1850 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
1851                                       const char*              theURL,
1852                                       bool                     isMultiFile )
1853 {
1854   INFOS( "SMESH_Gen_i::Save" );
1855
1856   //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
1857   // san -- in case <myCurrentStudy> differs from theComponent's study,
1858   // use that of the component
1859   if ( myCurrentStudy->_is_nil() || 
1860     theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
1861     SetCurrentStudy( theComponent->GetStudy() );
1862
1863   // Store study contents as a set of python commands
1864   SavePython(myCurrentStudy);
1865
1866   StudyContext* myStudyContext = GetCurrentStudyContext();
1867
1868   // Declare a byte stream
1869   SALOMEDS::TMPFile_var aStreamFile;
1870
1871   // Obtain a temporary dir
1872   TCollection_AsciiString tmpDir =
1873     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
1874
1875   // Create a sequence of files processed
1876   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
1877   aFileSeq->length( NUM_TMP_FILES );
1878
1879   TCollection_AsciiString aStudyName( "" );
1880   if ( isMultiFile ) 
1881     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
1882
1883   // Set names of temporary files
1884   TCollection_AsciiString filename =
1885     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
1886   TCollection_AsciiString meshfile =
1887     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
1888   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
1889   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
1890   filename = tmpDir + filename;
1891   meshfile = tmpDir + meshfile;
1892
1893   HDFfile*    aFile;
1894   HDFdataset* aDataset;
1895   HDFgroup*   aTopGroup;
1896   HDFgroup*   aGroup;
1897   HDFgroup*   aSubGroup;
1898   HDFgroup*   aSubSubGroup;
1899   hdf_size    aSize[ 1 ];
1900
1901
1902   //Remove the files if they exist: BugID: 11225
1903 #ifndef WNT /* unix functionality */
1904   TCollection_AsciiString cmd("rm -f \"");
1905 #else /* windows */
1906   TCollection_AsciiString cmd("del /F \"");
1907 #endif
1908
1909   cmd+=filename;
1910   cmd+="\" \"";
1911   cmd+=meshfile;
1912   cmd+="\"";
1913   system(cmd.ToCString());
1914
1915   // MED writer to be used by storage process
1916   DriverMED_W_SMESHDS_Mesh myWriter;
1917   myWriter.SetFile( meshfile.ToCString() );
1918
1919   // Write data
1920   // ---> create HDF file
1921   aFile = new HDFfile( (char*) filename.ToCString() );
1922   aFile->CreateOnDisk();
1923
1924   // --> iterator for top-level objects
1925   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
1926   for ( ; itBig->More(); itBig->Next() ) {
1927     SALOMEDS::SObject_var gotBranch = itBig->Value();
1928
1929     // --> hypotheses root branch (only one for the study)
1930     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
1931       // create hypotheses root HDF group
1932       aTopGroup = new HDFgroup( "Hypotheses", aFile );
1933       aTopGroup->CreateOnDisk();
1934
1935       // iterator for all hypotheses
1936       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
1937       for ( ; it->More(); it->Next() ) {
1938         SALOMEDS::SObject_var mySObject = it->Value();
1939         CORBA::Object_var anObject = SObjectToObject( mySObject );
1940         if ( !CORBA::is_nil( anObject ) ) {
1941           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
1942           if ( !myHyp->_is_nil() ) {
1943             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1944             if ( myImpl ) {
1945               string hypname = string( myHyp->GetName() );
1946               string libname = string( myHyp->GetLibName() );
1947               // BUG SWP13062
1948               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
1949               // WNT and ".so" for X-system) must be deleted
1950               int libname_len = libname.length();
1951 #ifdef WNT
1952               if( libname_len > 4 )
1953                 libname.resize( libname_len - 4 );
1954 #else
1955               // PAL17753 (Regresion: missing hypothesis in restored study)
1956               // "lib" also should be removed from the beginning
1957               //if( libname_len > 3 )
1958                 //libname.resize( libname_len - 3 );
1959               if( libname_len > 6 )
1960                 libname = libname.substr( 3, libname_len - 3 - 3 );
1961 #endif
1962               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
1963               int    id      = myStudyContext->findId( string( objStr.in() ) );
1964               string hypdata = string( myImpl->SaveTo() );
1965
1966               // for each hypothesis create HDF group basing on its id
1967               char hypGrpName[30];
1968               sprintf( hypGrpName, "Hypothesis %d", id );
1969               aGroup = new HDFgroup( hypGrpName, aTopGroup );
1970               aGroup->CreateOnDisk();
1971               // --> type name of hypothesis
1972               aSize[ 0 ] = hypname.length() + 1;
1973               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
1974               aDataset->CreateOnDisk();
1975               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
1976               aDataset->CloseOnDisk();
1977               // --> server plugin library name of hypothesis
1978               aSize[ 0 ] = libname.length() + 1;
1979               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
1980               aDataset->CreateOnDisk();
1981               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
1982               aDataset->CloseOnDisk();
1983               // --> persistent data of hypothesis
1984               aSize[ 0 ] = hypdata.length() + 1;
1985               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
1986               aDataset->CreateOnDisk();
1987               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
1988               aDataset->CloseOnDisk();
1989               // close hypothesis HDF group
1990               aGroup->CloseOnDisk();
1991             }
1992           }
1993         }
1994       }
1995       // close hypotheses root HDF group
1996       aTopGroup->CloseOnDisk();
1997     }
1998     // --> algorithms root branch (only one for the study)
1999     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
2000       // create algorithms root HDF group
2001       aTopGroup = new HDFgroup( "Algorithms", aFile );
2002       aTopGroup->CreateOnDisk();
2003
2004       // iterator for all algorithms
2005       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
2006       for ( ; it->More(); it->Next() ) {
2007         SALOMEDS::SObject_var mySObject = it->Value();
2008         CORBA::Object_var anObject = SObjectToObject( mySObject );
2009         if ( !CORBA::is_nil( anObject ) ) {
2010           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
2011           if ( !myHyp->_is_nil() ) {
2012             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2013             if ( myImpl ) {
2014               string hypname = string( myHyp->GetName() );
2015               string libname = string( myHyp->GetLibName() );
2016               // BUG SWP13062
2017               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
2018               // WNT and ".so" for X-system) must be deleted
2019               int libname_len = libname.length();
2020 #ifdef WNT
2021               if( libname_len > 4 )
2022                 libname.resize( libname_len - 4 );
2023 #else
2024               // PAL17753 (Regresion: missing hypothesis in restored study)
2025               // "lib" also should be removed from the beginning
2026               //if( libname_len > 3 )
2027                 //libname.resize( libname_len - 3 );
2028               if( libname_len > 6 )
2029                 libname = libname.substr( 3, libname_len - 3 - 3 );
2030 #endif
2031               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2032               int    id      = myStudyContext->findId( string( objStr.in() ) );
2033               string hypdata = string( myImpl->SaveTo() );
2034
2035               // for each algorithm create HDF group basing on its id
2036               char hypGrpName[30];
2037               sprintf( hypGrpName, "Algorithm %d", id );
2038               aGroup = new HDFgroup( hypGrpName, aTopGroup );
2039               aGroup->CreateOnDisk();
2040               // --> type name of algorithm
2041               aSize[0] = hypname.length() + 1;
2042               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
2043               aDataset->CreateOnDisk();
2044               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
2045               aDataset->CloseOnDisk();
2046               // --> server plugin library name of hypothesis
2047               aSize[0] = libname.length() + 1;
2048               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
2049               aDataset->CreateOnDisk();
2050               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
2051               aDataset->CloseOnDisk();
2052               // --> persistent data of algorithm
2053               aSize[0] = hypdata.length() + 1;
2054               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
2055               aDataset->CreateOnDisk();
2056               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
2057               aDataset->CloseOnDisk();
2058               // close algorithm HDF group
2059               aGroup->CloseOnDisk();
2060             }
2061           }
2062         }
2063       }
2064       // close algorithms root HDF group
2065       aTopGroup->CloseOnDisk();
2066     }
2067     // --> mesh objects roots branches
2068     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
2069       CORBA::Object_var anObject = SObjectToObject( gotBranch );
2070       if ( !CORBA::is_nil( anObject ) ) {
2071         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
2072         if ( !myMesh->_is_nil() ) {
2073           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
2074           if ( myImpl ) {
2075             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2076             int id = myStudyContext->findId( string( objStr.in() ) );
2077             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
2078             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
2079             bool hasShape = myLocMesh.HasShapeToMesh();
2080
2081             // for each mesh open the HDF group basing on its id
2082             char meshGrpName[ 30 ];
2083             sprintf( meshGrpName, "Mesh %d", id );
2084             aTopGroup = new HDFgroup( meshGrpName, aFile );
2085             aTopGroup->CreateOnDisk();
2086
2087             // --> put dataset to hdf file which is a flag that mesh has data
2088             string strHasData = "0";
2089             // check if the mesh is not empty
2090             if ( mySMESHDSMesh->NbNodes() > 0 ) {
2091               // write mesh data to med file
2092               myWriter.SetMesh( mySMESHDSMesh );
2093               myWriter.SetMeshId( id );
2094               strHasData = "1";
2095             }
2096             aSize[ 0 ] = strHasData.length() + 1;
2097             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
2098             aDataset->CreateOnDisk();
2099             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
2100             aDataset->CloseOnDisk();
2101
2102             // ouv : NPAL12872
2103             // for each mesh open the HDF group basing on its auto color parameter
2104             char meshAutoColorName[ 30 ];
2105             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
2106             int anAutoColor[1];
2107             anAutoColor[0] = myImpl->GetAutoColor();
2108             aSize[ 0 ] = 1;
2109             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
2110             aDataset->CreateOnDisk();
2111             aDataset->WriteOnDisk( anAutoColor );
2112             aDataset->CloseOnDisk();
2113
2114             // write reference on a shape if exists
2115             SALOMEDS::SObject_var myRef;
2116             bool shapeRefFound = false;
2117             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
2118             if ( found ) {
2119               SALOMEDS::SObject_var myShape;
2120               bool ok = myRef->ReferencedObject( myShape );
2121               if ( ok ) {
2122                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
2123                 string myRefOnObject = myShape->GetID();
2124                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
2125                   aSize[ 0 ] = myRefOnObject.length() + 1;
2126                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
2127                   aDataset->CreateOnDisk();
2128                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2129                   aDataset->CloseOnDisk();
2130                 }
2131               }
2132             }
2133
2134             // write applied hypotheses if exist
2135             SALOMEDS::SObject_var myHypBranch;
2136             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
2137             if ( found && !shapeRefFound && hasShape) { // remove applied hyps
2138               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
2139             }
2140             if ( found && (shapeRefFound || !hasShape) ) {
2141               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
2142               aGroup->CreateOnDisk();
2143
2144               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
2145               int hypNb = 0;
2146               for ( ; it->More(); it->Next() ) {
2147                 SALOMEDS::SObject_var mySObject = it->Value();
2148                 SALOMEDS::SObject_var myRefOnHyp;
2149                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
2150                 if ( ok ) {
2151                   // san - it is impossible to recover applied hypotheses
2152                   //       using their entries within Load() method,
2153                   // for there are no AttributeIORs in the study when Load() is working. 
2154                   // Hence, it is better to store persistent IDs of hypotheses as references to them
2155
2156                   //string myRefOnObject = myRefOnHyp->GetID();
2157                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
2158                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2159                   int id = myStudyContext->findId( string( objStr.in() ) );
2160                   //if ( myRefOnObject.length() > 0 ) {
2161                   //aSize[ 0 ] = myRefOnObject.length() + 1;
2162                   char hypName[ 30 ], hypId[ 30 ];
2163                   sprintf( hypName, "Hyp %d", ++hypNb );
2164                   sprintf( hypId, "%d", id );
2165                   aSize[ 0 ] = strlen( hypId ) + 1;
2166                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
2167                   aDataset->CreateOnDisk();
2168                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2169                   aDataset->WriteOnDisk( hypId );
2170                   aDataset->CloseOnDisk();
2171                   //}
2172                 }
2173               }
2174               aGroup->CloseOnDisk();
2175             }
2176
2177             // write applied algorithms if exist
2178             SALOMEDS::SObject_var myAlgoBranch;
2179             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
2180             if ( found && !shapeRefFound && hasShape) { // remove applied algos
2181               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
2182             }
2183             if ( found && (shapeRefFound || !hasShape)) {
2184               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
2185               aGroup->CreateOnDisk();
2186
2187               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
2188               int algoNb = 0;
2189               for ( ; it->More(); it->Next() ) {
2190                 SALOMEDS::SObject_var mySObject = it->Value();
2191                 SALOMEDS::SObject_var myRefOnAlgo;
2192                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
2193                 if ( ok ) {
2194                   // san - it is impossible to recover applied algorithms
2195                   //       using their entries within Load() method,
2196                   // for there are no AttributeIORs in the study when Load() is working. 
2197                   // Hence, it is better to store persistent IDs of algorithms as references to them
2198
2199                   //string myRefOnObject = myRefOnAlgo->GetID();
2200                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
2201                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2202                   int id = myStudyContext->findId( string( objStr.in() ) );
2203                   //if ( myRefOnObject.length() > 0 ) {
2204                   //aSize[ 0 ] = myRefOnObject.length() + 1;
2205                   char algoName[ 30 ], algoId[ 30 ];
2206                   sprintf( algoName, "Algo %d", ++algoNb );
2207                   sprintf( algoId, "%d", id );
2208                   aSize[ 0 ] = strlen( algoId ) + 1;
2209                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
2210                   aDataset->CreateOnDisk();
2211                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2212                   aDataset->WriteOnDisk( algoId );
2213                   aDataset->CloseOnDisk();
2214                   //}
2215                 }
2216               }
2217               aGroup->CloseOnDisk();
2218             }
2219
2220             // --> submesh objects sub-branches
2221
2222             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
2223               SALOMEDS::SObject_var mySubmeshBranch;
2224               found = gotBranch->FindSubObject( i, mySubmeshBranch );
2225
2226               if ( found ) // check if there is shape reference in submeshes
2227               {
2228                 bool hasShapeRef = false;
2229                 SALOMEDS::ChildIterator_var itSM =
2230                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
2231                 for ( ; itSM->More(); itSM->Next() ) {
2232                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
2233                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
2234                     mySubRef->ReferencedObject( myShape );
2235                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
2236                     hasShapeRef = true;
2237                   else
2238                   { // remove one submesh
2239                     if ( shapeRefFound )
2240                     { // unassign hypothesis
2241                       SMESH::SMESH_subMesh_var mySubMesh =
2242                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
2243                       if ( !mySubMesh->_is_nil() ) {
2244                         int shapeID = mySubMesh->GetId();
2245                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
2246                         const list<const SMESHDS_Hypothesis*>& hypList =
2247                           mySMESHDSMesh->GetHypothesis( S );
2248                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
2249                         while ( hyp != hypList.end() ) {
2250                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
2251                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
2252                         }
2253                       }
2254                     }
2255                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
2256                   }
2257                 } // loop on submeshes of a type
2258                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
2259                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
2260                   found = false;
2261                 }
2262               }  // end check if there is shape reference in submeshes
2263               if ( found ) {
2264                 char name_meshgroup[ 30 ];
2265                 if ( i == GetSubMeshOnVertexTag() )
2266                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
2267                 else if ( i == GetSubMeshOnEdgeTag() )
2268                   strcpy( name_meshgroup, "SubMeshes On Edge" );
2269                 else if ( i == GetSubMeshOnWireTag() )
2270                   strcpy( name_meshgroup, "SubMeshes On Wire" );
2271                 else if ( i == GetSubMeshOnFaceTag() )
2272                   strcpy( name_meshgroup, "SubMeshes On Face" );
2273                 else if ( i == GetSubMeshOnShellTag() )
2274                   strcpy( name_meshgroup, "SubMeshes On Shell" );
2275                 else if ( i == GetSubMeshOnSolidTag() )
2276                   strcpy( name_meshgroup, "SubMeshes On Solid" );
2277                 else if ( i == GetSubMeshOnCompoundTag() )
2278                   strcpy( name_meshgroup, "SubMeshes On Compound" );
2279
2280                 // for each type of submeshes create container HDF group
2281                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
2282                 aGroup->CreateOnDisk();
2283
2284                 // iterator for all submeshes of given type
2285                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
2286                 for ( ; itSM->More(); itSM->Next() ) {
2287                   SALOMEDS::SObject_var mySObject = itSM->Value();
2288                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
2289                   if ( !CORBA::is_nil( anSubObject ))
2290                   {
2291                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
2292                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
2293                     int subid = myStudyContext->findId( string( objStr.in() ) );
2294
2295                     // for each mesh open the HDF group basing on its id
2296                     char submeshGrpName[ 30 ];
2297                     sprintf( submeshGrpName, "SubMesh %d", subid );
2298                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
2299                     aSubGroup->CreateOnDisk();
2300
2301                     // write reference on a shape, already checked if it exists
2302                     SALOMEDS::SObject_var mySubRef, myShape;
2303                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
2304                       mySubRef->ReferencedObject( myShape );
2305                     string myRefOnObject = myShape->GetID();
2306                     if ( myRefOnObject.length() > 0 ) {
2307                       aSize[ 0 ] = myRefOnObject.length() + 1;
2308                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
2309                       aDataset->CreateOnDisk();
2310                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2311                       aDataset->CloseOnDisk();
2312                     }
2313
2314                     // write applied hypotheses if exist
2315                     SALOMEDS::SObject_var mySubHypBranch;
2316                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
2317                     if ( found ) {
2318                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
2319                       aSubSubGroup->CreateOnDisk();
2320
2321                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
2322                       int hypNb = 0;
2323                       for ( ; it->More(); it->Next() ) {
2324                         SALOMEDS::SObject_var mySubSObject = it->Value();
2325                         SALOMEDS::SObject_var myRefOnHyp;
2326                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
2327                         if ( ok ) {
2328                           //string myRefOnObject = myRefOnHyp->GetID();
2329                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
2330                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2331                           int id = myStudyContext->findId( string( objStr.in() ) );
2332                           //if ( myRefOnObject.length() > 0 ) {
2333                           //aSize[ 0 ] = myRefOnObject.length() + 1;
2334                           char hypName[ 30 ], hypId[ 30 ];
2335                           sprintf( hypName, "Hyp %d", ++hypNb );
2336                           sprintf( hypId, "%d", id );
2337                           aSize[ 0 ] = strlen( hypId ) + 1;
2338                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
2339                           aDataset->CreateOnDisk();
2340                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2341                           aDataset->WriteOnDisk( hypId );
2342                           aDataset->CloseOnDisk();
2343                           //}
2344                         }
2345                       }
2346                       aSubSubGroup->CloseOnDisk();
2347                     }
2348
2349                     // write applied algorithms if exist
2350                     SALOMEDS::SObject_var mySubAlgoBranch;
2351                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
2352                     if ( found ) {
2353                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
2354                       aSubSubGroup->CreateOnDisk();
2355
2356                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
2357                       int algoNb = 0;
2358                       for ( ; it->More(); it->Next() ) {
2359                         SALOMEDS::SObject_var mySubSObject = it->Value();
2360                         SALOMEDS::SObject_var myRefOnAlgo;
2361                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
2362                         if ( ok ) {
2363                           //string myRefOnObject = myRefOnAlgo->GetID();
2364                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
2365                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2366                           int id = myStudyContext->findId( string( objStr.in() ) );
2367                           //if ( myRefOnObject.length() > 0 ) {
2368                           //aSize[ 0 ] = myRefOnObject.length() + 1;
2369                           char algoName[ 30 ], algoId[ 30 ];
2370                           sprintf( algoName, "Algo %d", ++algoNb );
2371                           sprintf( algoId, "%d", id );
2372                           aSize[ 0 ] = strlen( algoId ) + 1;
2373                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
2374                           aDataset->CreateOnDisk();
2375                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2376                           aDataset->WriteOnDisk( algoId );
2377                           aDataset->CloseOnDisk();
2378                           //}
2379                         }
2380                       }
2381                       aSubSubGroup->CloseOnDisk();
2382                     }
2383                     // close submesh HDF group
2384                     aSubGroup->CloseOnDisk();
2385                   }
2386                 }
2387                 // close container of submeshes by type HDF group
2388                 aGroup->CloseOnDisk();
2389               }
2390             }
2391             // All sub-meshes will be stored in MED file
2392             // .. will NOT (PAL 12992)
2393             //if ( shapeRefFound )
2394             //myWriter.AddAllSubMeshes();
2395
2396             // groups root sub-branch
2397             SALOMEDS::SObject_var myGroupsBranch;
2398             for ( int i = GetNodeGroupsTag(); i <= GetVolumeGroupsTag(); i++ ) {
2399               found = gotBranch->FindSubObject( i, myGroupsBranch );
2400               if ( found ) {
2401                 char name_group[ 30 ];
2402                 if ( i == GetNodeGroupsTag() )
2403                   strcpy( name_group, "Groups of Nodes" );
2404                 else if ( i == GetEdgeGroupsTag() )
2405                   strcpy( name_group, "Groups of Edges" );
2406                 else if ( i == GetFaceGroupsTag() )
2407                   strcpy( name_group, "Groups of Faces" );
2408                 else if ( i == GetVolumeGroupsTag() )
2409                   strcpy( name_group, "Groups of Volumes" );
2410
2411                 aGroup = new HDFgroup( name_group, aTopGroup );
2412                 aGroup->CreateOnDisk();
2413
2414                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
2415                 for ( ; it->More(); it->Next() ) {
2416                   SALOMEDS::SObject_var mySObject = it->Value();
2417                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
2418                   if ( !CORBA::is_nil( aSubObject ) ) {
2419                     SMESH_GroupBase_i* myGroupImpl =
2420                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
2421                     if ( !myGroupImpl )
2422                       continue;
2423                     
2424                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
2425                     int anId = myStudyContext->findId( string( objStr.in() ) );
2426                     
2427                     // For each group, create a dataset named "Group <group_persistent_id>"
2428                     // and store the group's user name into it
2429                     char grpName[ 30 ];
2430                     sprintf( grpName, "Group %d", anId );
2431                     char* aUserName = myGroupImpl->GetName();
2432                     aSize[ 0 ] = strlen( aUserName ) + 1;
2433                     
2434                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
2435                     aDataset->CreateOnDisk();
2436                     aDataset->WriteOnDisk( aUserName );
2437                     aDataset->CloseOnDisk();
2438
2439                     // ouv : NPAL12872
2440                     // For each group, create a dataset named "Group <group_persistent_id> Color"
2441                     // and store the group's color into it
2442                     char grpColorName[ 30 ];
2443                     sprintf( grpColorName, "ColorGroup %d", anId );
2444                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
2445                     double anRGB[3];
2446                     anRGB[ 0 ] = aColor.R;
2447                     anRGB[ 1 ] = aColor.G;
2448                     anRGB[ 2 ] = aColor.B;
2449                     aSize[ 0 ] = 3;
2450                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
2451                     aDataset->CreateOnDisk();
2452                     aDataset->WriteOnDisk( anRGB );
2453                     aDataset->CloseOnDisk();
2454
2455                     // Store the group contents into MED file
2456                     if ( myLocMesh.GetGroup( myGroupImpl->GetLocalID() ) ) {
2457                       
2458                       if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen_i::Save(): saving group with StoreName = "
2459                                           << grpName << " to MED file" );
2460                       SMESHDS_GroupBase* aGrpBaseDS =
2461                         myLocMesh.GetGroup( myGroupImpl->GetLocalID() )->GetGroupDS();
2462                       aGrpBaseDS->SetStoreName( grpName );
2463
2464                       // Pass SMESHDS_Group to MED writer 
2465                       SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
2466                       if ( aGrpDS )
2467                         myWriter.AddGroup( aGrpDS );
2468                       
2469                       // write reference on a shape if exists
2470                       SMESHDS_GroupOnGeom* aGeomGrp =
2471                         dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
2472                       if ( aGeomGrp ) {
2473                         SALOMEDS::SObject_var mySubRef, myShape;
2474                         if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
2475                             mySubRef->ReferencedObject( myShape ) &&
2476                             !CORBA::is_nil( myShape->GetObject() ))
2477                         {
2478                           string myRefOnObject = myShape->GetID();
2479                           if ( myRefOnObject.length() > 0 ) {
2480                             char aRefName[ 30 ];
2481                             sprintf( aRefName, "Ref on shape %d", anId);
2482                             aSize[ 0 ] = myRefOnObject.length() + 1;
2483                             aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
2484                             aDataset->CreateOnDisk();
2485                             aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2486                             aDataset->CloseOnDisk();
2487                           }
2488                         }
2489                         else // shape ref is invalid:
2490                         {
2491                           // save a group on geometry as ordinary group
2492                           myWriter.AddGroup( aGeomGrp );
2493                         }
2494                       }
2495                     }
2496                   }
2497                 }
2498                 aGroup->CloseOnDisk();
2499               }
2500             } // loop on groups 
2501             
2502             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
2503             {
2504               // Flush current mesh information into MED file
2505               myWriter.Perform();
2506               
2507               // maybe a shape was deleted in the study
2508               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
2509                 TopoDS_Shape nullShape;
2510                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
2511               }
2512               
2513               if ( !mySMESHDSMesh->SubMeshes().empty() )
2514               {
2515                 // Store submeshes
2516                 // ----------------
2517                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
2518                 aGroup->CreateOnDisk();
2519                 
2520                 // each element belongs to one or none submesh,
2521                 // so for each node/element, we store a submesh ID
2522                 
2523                 // Make maps of submesh IDs of elements sorted by element IDs
2524                 typedef int TElemID;
2525                 typedef int TSubMID;
2526                 map< TElemID, TSubMID > eId2smId, nId2smId;
2527                 map< TElemID, TSubMID >::iterator hint; // insertion to map is done before hint
2528                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
2529                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
2530                 SMDS_NodeIteratorPtr itNode;
2531                 SMDS_ElemIteratorPtr itElem;
2532                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
2533                 {
2534                   TSubMID          aSubMeID = itSubM->first;
2535                   SMESHDS_SubMesh* aSubMesh = itSubM->second;
2536                   if ( aSubMesh->IsComplexSubmesh() )
2537                     continue; // submesh containing other submeshs
2538                   // nodes
2539                   hint = nId2smId.begin(); // optimize insertion basing on increasing order of elem Ids in submesh
2540                   for ( itNode = aSubMesh->GetNodes(); itNode->more(); ++hint)
2541                     hint = nId2smId.insert( hint, make_pair( itNode->next()->GetID(), aSubMeID ));
2542                   // elements
2543                   hint = eId2smId.begin();
2544                   for ( itElem = aSubMesh->GetElements(); itElem->more(); ++hint)
2545                     hint = eId2smId.insert( hint, make_pair( itElem->next()->GetID(), aSubMeID ));
2546                 }
2547                 
2548                 // Care of elements that are not on submeshes
2549                 if ( mySMESHDSMesh->NbNodes() != nId2smId.size() ) {
2550                   for ( itNode = mySMESHDSMesh->nodesIterator(); itNode->more(); )
2551                     /*  --- stl_map.h says : */
2552                     /*  A %map relies on unique keys and thus a %pair is only inserted if its */
2553                     /*  first element (the key) is not already present in the %map.           */
2554                     nId2smId.insert( make_pair( itNode->next()->GetID(), 0 ));
2555                 }
2556                 int nbElems = mySMESHDSMesh->NbEdges() + mySMESHDSMesh->NbFaces() + mySMESHDSMesh->NbVolumes();
2557                 if ( nbElems != eId2smId.size() ) {
2558                   for ( itElem = mySMESHDSMesh->elementsIterator(); itElem->more(); )
2559                     eId2smId.insert( make_pair( itElem->next()->GetID(), 0 ));
2560                 }
2561                 
2562                 // Store submesh IDs
2563                 for ( int isNode = 0; isNode < 2; ++isNode )
2564                 {
2565                   map< TElemID, TSubMID >& id2smId = isNode ? nId2smId : eId2smId;
2566                   if ( id2smId.empty() ) continue;
2567                   map< TElemID, TSubMID >::const_iterator id_smId = id2smId.begin();
2568                   // make and fill array of submesh IDs
2569                   int* smIDs = new int [ id2smId.size() ];
2570                   for ( int i = 0; id_smId != id2smId.end(); ++id_smId, ++i )
2571                     smIDs[ i ] = id_smId->second;
2572                   // write HDF group
2573                   aSize[ 0 ] = id2smId.size();
2574                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
2575                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
2576                   aDataset->CreateOnDisk();
2577                   aDataset->WriteOnDisk( smIDs );
2578                   aDataset->CloseOnDisk();
2579                   //
2580                   delete smIDs;
2581                 }
2582                 
2583                 // Store node positions on sub-shapes (SMDS_Position):
2584                 // ----------------------------------------------------
2585                 
2586                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
2587                 aGroup->CreateOnDisk();
2588                 
2589                 // in aGroup, create 5 datasets to contain:
2590                 // "Nodes on Edges" - ID of node on edge
2591                 // "Edge positions" - U parameter on node on edge
2592                 // "Nodes on Faces" - ID of node on face
2593                 // "Face U positions" - U parameter of node on face
2594                 // "Face V positions" - V parameter of node on face
2595                 
2596                 // Find out nb of nodes on edges and faces
2597                 // Collect corresponing sub-meshes
2598                 int nbEdgeNodes = 0, nbFaceNodes = 0;
2599                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
2600                 // loop on SMESHDS_SubMesh'es
2601                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
2602                 {
2603                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
2604                   if ( aSubMesh->IsComplexSubmesh() )
2605                     continue; // submesh containing other submeshs
2606                   int nbNodes = aSubMesh->NbNodes();
2607                   if ( nbNodes == 0 ) continue;
2608                   
2609                   int aShapeID = (*itSubM).first;
2610                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
2611                   // write only SMDS_FacePosition and SMDS_EdgePosition
2612                   switch ( aShapeType ) {
2613                   case TopAbs_FACE:
2614                     nbFaceNodes += nbNodes;
2615                     aFaceSM.push_back( aSubMesh );
2616                     break;
2617                   case TopAbs_EDGE:
2618                     nbEdgeNodes += nbNodes;
2619                     aEdgeSM.push_back( aSubMesh );
2620                     break;
2621                   default:
2622                     continue;
2623                   }
2624                 }
2625                 // Treat positions on edges or faces
2626                 for ( int onFace = 0; onFace < 2; onFace++ )
2627                 {
2628                   // Create arrays to store in datasets
2629                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
2630                   if (!nbNodes) continue;
2631                   int* aNodeIDs = new int [ nbNodes ];
2632                   double* aUPos = new double [ nbNodes ];
2633                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
2634                   
2635                   // Fill arrays
2636                   // loop on sub-meshes
2637                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
2638                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
2639                   for ( ; itSM != pListSM->end(); itSM++ )
2640                   {
2641                     SMESHDS_SubMesh* aSubMesh = (*itSM);
2642                     
2643                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
2644                     // loop on nodes in aSubMesh
2645                     while ( itNode->more() )
2646                     {
2647                       //node ID
2648                       const SMDS_MeshNode* node = itNode->next();
2649                       aNodeIDs [ iNode ] = node->GetID();
2650                       
2651                       // Position
2652                       const SMDS_PositionPtr pos = node->GetPosition();
2653                       if ( onFace ) { // on FACE
2654                         const SMDS_FacePosition* fPos =
2655                           dynamic_cast<const SMDS_FacePosition*>( pos.get() );
2656                         if ( fPos ) {
2657                           aUPos[ iNode ] = fPos->GetUParameter();
2658                           aVPos[ iNode ] = fPos->GetVParameter();
2659                           iNode++;
2660                         }
2661                         else
2662                           nbNodes--;
2663                       }
2664                       else { // on EDGE
2665                         const SMDS_EdgePosition* ePos =
2666                           dynamic_cast<const SMDS_EdgePosition*>( pos.get() );
2667                         if ( ePos ) {
2668                           aUPos[ iNode ] = ePos->GetUParameter();
2669                           iNode++;
2670                         }
2671                         else
2672                           nbNodes--;
2673                       }
2674                     } // loop on nodes in aSubMesh
2675                   } // loop on sub-meshes
2676                   
2677                   // Write datasets
2678                   if ( nbNodes )
2679                   {
2680                     aSize[ 0 ] = nbNodes;
2681                     // IDS
2682                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
2683                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
2684                     aDataset->CreateOnDisk();
2685                     aDataset->WriteOnDisk( aNodeIDs );
2686                     aDataset->CloseOnDisk();
2687                 
2688                     // U Positions
2689                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
2690                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
2691                     aDataset->CreateOnDisk();
2692                     aDataset->WriteOnDisk( aUPos );
2693                     aDataset->CloseOnDisk();
2694                     // V Positions
2695                     if ( onFace ) {
2696                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
2697                       aDataset->CreateOnDisk();
2698                       aDataset->WriteOnDisk( aVPos );
2699                       aDataset->CloseOnDisk();
2700                     }
2701                   }
2702                   delete [] aNodeIDs;
2703                   delete [] aUPos;
2704                   if ( aVPos ) delete [] aVPos;
2705                   
2706                 } // treat positions on edges or faces
2707                 
2708                 // close "Node Positions" group
2709                 aGroup->CloseOnDisk(); 
2710                 
2711               } // if ( there are submeshes in SMESHDS_Mesh )
2712             } // if ( hasData )
2713             
2714             // close mesh HDF group
2715             aTopGroup->CloseOnDisk();
2716           }
2717         }
2718       }
2719     }
2720   }
2721   
2722   // close HDF file
2723   aFile->CloseOnDisk();
2724   delete aFile;
2725
2726   // Convert temporary files to stream
2727   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
2728
2729   // Remove temporary files and directory
2730   if ( !isMultiFile ) 
2731     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
2732
2733   INFOS( "SMESH_Gen_i::Save() completed" );
2734   return aStreamFile._retn();
2735 }
2736
2737 //=============================================================================
2738 /*!
2739  *  SMESH_Gen_i::SaveASCII
2740  *
2741  *  Save SMESH module's data in ASCII format
2742  */
2743 //=============================================================================
2744
2745 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
2746                                            const char*              theURL,
2747                                            bool                     isMultiFile ) {
2748   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
2749   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
2750   return aStreamFile._retn();
2751
2752   //after usual saving needs to encipher binary to text string
2753   //Any binary symbol will be represent as "|xx" () hexadecimal format number
2754   int size = aStreamFile.in().length();
2755   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
2756   for ( int i = 0; i < size; i++ )
2757     sprintf( (char*)&(buffer[i*3]), "|%02x", (char*)(aStreamFile[i]) );
2758
2759   buffer[size * 3] = '\0';
2760
2761   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
2762   
2763   return anAsciiStreamFile._retn();
2764 }
2765
2766 //=============================================================================
2767 /*!
2768  *  SMESH_Gen_i::loadGeomData
2769  *
2770  *  Load GEOM module data
2771  */
2772 //=============================================================================
2773
2774 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
2775 {
2776   if ( theCompRoot->_is_nil() )
2777     return;
2778
2779   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
2780   if ( aStudy->_is_nil() )
2781     return;
2782
2783   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder(); 
2784   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
2785 }
2786 //=============================================================================
2787 /*!
2788  * \brief Creates SMDS_Position according to shape type
2789  */
2790 //=============================================================================
2791
2792 class PositionCreator {
2793 public:
2794   SMDS_PositionPtr MakePosition(const TopAbs_ShapeEnum type) {
2795     return (this->*myFuncTable[ type ])();
2796   }
2797   PositionCreator() {
2798     myFuncTable.resize( (size_t) TopAbs_SHAPE, & PositionCreator::defaultPosition );
2799     myFuncTable[ TopAbs_FACE ] = & PositionCreator::facePosition;
2800     myFuncTable[ TopAbs_EDGE ] = & PositionCreator::edgePosition;
2801     myFuncTable[ TopAbs_VERTEX ] = & PositionCreator::vertexPosition;
2802   }
2803 private:
2804   SMDS_PositionPtr edgePosition()    const { return SMDS_PositionPtr( new SMDS_EdgePosition  ); }
2805   SMDS_PositionPtr facePosition()    const { return SMDS_PositionPtr( new SMDS_FacePosition  ); }
2806   SMDS_PositionPtr vertexPosition()  const { return SMDS_PositionPtr( new SMDS_VertexPosition); }
2807   SMDS_PositionPtr defaultPosition() const { return SMDS_SpacePosition::originSpacePosition();  }
2808   typedef SMDS_PositionPtr (PositionCreator:: * FmakePos)() const;
2809   vector<FmakePos> myFuncTable;
2810 };
2811
2812 //=============================================================================
2813 /*!
2814  *  SMESH_Gen_i::Load
2815  *
2816  *  Load SMESH module's data
2817  */
2818 //=============================================================================
2819
2820 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
2821                         const SALOMEDS::TMPFile& theStream,
2822                         const char*              theURL,
2823                         bool                     isMultiFile )
2824 {
2825   INFOS( "SMESH_Gen_i::Load" );
2826
2827   if ( myCurrentStudy->_is_nil() || 
2828        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
2829     SetCurrentStudy( theComponent->GetStudy() );
2830
2831   /*  if( !theComponent->_is_nil() )
2832       {
2833       //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
2834       if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
2835       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
2836       }*/
2837
2838   StudyContext* myStudyContext = GetCurrentStudyContext();
2839
2840   // Get temporary files location
2841   TCollection_AsciiString tmpDir =
2842     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2843     
2844     INFOS( "THE URL++++++++++++++" )
2845     INFOS( theURL );
2846     INFOS( "THE TMP PATH+++++++++" );
2847     INFOS( tmpDir );
2848
2849   // Convert the stream into sequence of files to process
2850   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
2851                                                                             tmpDir.ToCString(),
2852                                                                             isMultiFile );
2853   TCollection_AsciiString aStudyName( "" );
2854   if ( isMultiFile ) 
2855     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2856
2857   // Set names of temporary files
2858   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
2859   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
2860
2861   int size;
2862   HDFfile*    aFile;
2863   HDFdataset* aDataset;
2864   HDFgroup*   aTopGroup;
2865   HDFgroup*   aGroup;
2866   HDFgroup*   aSubGroup;
2867   HDFgroup*   aSubSubGroup;
2868
2869   // Read data
2870   // ---> open HDF file
2871   aFile = new HDFfile( (char*) filename.ToCString() );
2872   try {
2873     aFile->OpenOnDisk( HDF_RDONLY );
2874   }
2875   catch ( HDFexception ) {
2876     INFOS( "Load(): " << filename << " not found!" );
2877     return false;
2878   }
2879
2880   DriverMED_R_SMESHDS_Mesh myReader;
2881   myReader.SetFile( meshfile.ToCString() );
2882
2883   // For PAL13473 ("Repetitive mesh") implementation.
2884   // New dependencies between SMESH objects are established:
2885   // now hypotheses can refer to meshes, shapes and other hypotheses.
2886   // To keep data consistent, the following order of data restoration
2887   // imposed:
2888   // 1. Create hypotheses
2889   // 2. Create all meshes
2890   // 3. Load hypotheses' data
2891   // 4. All the rest
2892
2893   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
2894   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
2895
2896   // get total number of top-level groups
2897   int aNbGroups = aFile->nInternalObjects(); 
2898   if ( aNbGroups > 0 ) {
2899     // --> in first turn we should read&create hypotheses
2900     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
2901       // open hypotheses root HDF group
2902       aTopGroup = new HDFgroup( "Hypotheses", aFile ); 
2903       aTopGroup->OpenOnDisk();
2904
2905       // get number of hypotheses
2906       int aNbObjects = aTopGroup->nInternalObjects(); 
2907       for ( int j = 0; j < aNbObjects; j++ ) {
2908         // try to identify hypothesis
2909         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
2910         aTopGroup->InternalObjectIndentify( j, hypGrpName );
2911
2912         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
2913           // open hypothesis group
2914           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
2915           aGroup->OpenOnDisk();
2916
2917           // --> get hypothesis id
2918           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
2919           string hypname;
2920           string libname;
2921           string hypdata;
2922
2923           // get number of datasets
2924           int aNbSubObjects = aGroup->nInternalObjects();
2925           for ( int k = 0; k < aNbSubObjects; k++ ) {
2926             // identify dataset
2927             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
2928             aGroup->InternalObjectIndentify( k, name_of_subgroup );
2929             // --> get hypothesis name
2930             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
2931               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2932               aDataset->OpenOnDisk();
2933               size = aDataset->GetSize();
2934               char* hypname_str = new char[ size ];
2935               aDataset->ReadFromDisk( hypname_str );
2936               hypname = string( hypname_str );
2937               delete [] hypname_str;
2938               aDataset->CloseOnDisk();
2939             }
2940             // --> get hypothesis plugin library name
2941             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
2942               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2943               aDataset->OpenOnDisk();
2944               size = aDataset->GetSize();
2945               char* libname_str = new char[ size ];
2946               aDataset->ReadFromDisk( libname_str );
2947               if(MYDEBUG) SCRUTE( libname_str );
2948               libname = string( libname_str );
2949               delete [] libname_str;
2950               aDataset->CloseOnDisk();
2951             }
2952             // --> get hypothesis data
2953             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
2954               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2955               aDataset->OpenOnDisk();
2956               size = aDataset->GetSize();
2957               char* hypdata_str = new char[ size ];
2958               aDataset->ReadFromDisk( hypdata_str );
2959               hypdata = string( hypdata_str );
2960               delete [] hypdata_str;
2961               aDataset->CloseOnDisk();
2962             }
2963           }
2964           // close hypothesis HDF group
2965           aGroup->CloseOnDisk();
2966
2967           // --> restore hypothesis from data
2968           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
2969             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
2970                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
2971             SMESH::SMESH_Hypothesis_var myHyp;
2972
2973             try { // protect persistence mechanism against exceptions
2974               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
2975             }
2976             catch (...) {
2977               INFOS( "Exception during hypothesis creation" );
2978             }
2979
2980             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2981             if ( myImpl ) {
2982               // myImpl->LoadFrom( hypdata.c_str() );
2983               hypDataList.push_back( make_pair( myImpl, hypdata ));
2984               string iorString = GetORB()->object_to_string( myHyp );
2985               int newId = myStudyContext->findId( iorString );
2986               myStudyContext->mapOldToNew( id, newId );
2987             }
2988             else
2989               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
2990           }
2991         }
2992       }
2993       // close hypotheses root HDF group
2994       aTopGroup->CloseOnDisk();
2995       aTopGroup = 0;
2996     }
2997
2998     // --> then we should read&create algorithms
2999     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
3000       // open algorithms root HDF group
3001       aTopGroup = new HDFgroup( "Algorithms", aFile ); 
3002       aTopGroup->OpenOnDisk();
3003
3004       // get number of algorithms
3005       int aNbObjects = aTopGroup->nInternalObjects(); 
3006       for ( int j = 0; j < aNbObjects; j++ ) {
3007         // try to identify algorithm
3008         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
3009         aTopGroup->InternalObjectIndentify( j, hypGrpName );
3010
3011         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
3012           // open algorithm group
3013           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
3014           aGroup->OpenOnDisk();
3015
3016           // --> get algorithm id
3017           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
3018           string hypname;
3019           string libname;
3020           string hypdata;
3021
3022           // get number of datasets
3023           int aNbSubObjects = aGroup->nInternalObjects();
3024           for ( int k = 0; k < aNbSubObjects; k++ ) {
3025             // identify dataset
3026             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
3027             aGroup->InternalObjectIndentify( k, name_of_subgroup );
3028             // --> get algorithm name
3029             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
3030               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3031               aDataset->OpenOnDisk();
3032               size = aDataset->GetSize();
3033               char* hypname_str = new char[ size ];
3034               aDataset->ReadFromDisk( hypname_str );
3035               hypname = string( hypname_str );
3036               delete [] hypname_str;
3037               aDataset->CloseOnDisk();
3038             }
3039             // --> get algorithm plugin library name
3040             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
3041               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3042               aDataset->OpenOnDisk();
3043               size = aDataset->GetSize();
3044               char* libname_str = new char[ size ];
3045               aDataset->ReadFromDisk( libname_str );
3046               if(MYDEBUG) SCRUTE( libname_str );
3047               libname = string( libname_str );
3048               delete [] libname_str;
3049               aDataset->CloseOnDisk();
3050             }
3051             // --> get algorithm data
3052             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
3053               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3054               aDataset->OpenOnDisk();
3055               size = aDataset->GetSize();
3056               char* hypdata_str = new char[ size ];
3057               aDataset->ReadFromDisk( hypdata_str );
3058               if(MYDEBUG) SCRUTE( hypdata_str );
3059               hypdata = string( hypdata_str );
3060               delete [] hypdata_str;
3061               aDataset->CloseOnDisk();
3062             }
3063           }
3064           // close algorithm HDF group
3065           aGroup->CloseOnDisk();
3066
3067           // --> restore algorithm from data
3068           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
3069             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
3070                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
3071             SMESH::SMESH_Hypothesis_var myHyp;
3072
3073             try { // protect persistence mechanism against exceptions
3074               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
3075             }
3076             catch (...) {
3077               INFOS( "Exception during hypothesis creation" );
3078             }
3079
3080             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3081             if ( myImpl ) {
3082               //myImpl->LoadFrom( hypdata.c_str() );
3083               hypDataList.push_back( make_pair( myImpl, hypdata ));
3084               string iorString = GetORB()->object_to_string( myHyp );
3085               int newId = myStudyContext->findId( iorString );
3086               myStudyContext->mapOldToNew( id, newId );
3087             }
3088             else
3089               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
3090           }
3091         }
3092       }
3093       // close algorithms root HDF group
3094       aTopGroup->CloseOnDisk();
3095       aTopGroup = 0;
3096     }
3097
3098     // --> the rest groups should be meshes
3099     for ( int i = 0; i < aNbGroups; i++ ) {
3100       // identify next group
3101       char meshName[ HDF_NAME_MAX_LEN+1 ];
3102       aFile->InternalObjectIndentify( i, meshName );
3103
3104       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
3105         // --> get mesh id
3106         int id = atoi( string( meshName ).substr( 4 ).c_str() );
3107         if ( id <= 0 )
3108           continue;
3109
3110         // open mesh HDF group
3111         aTopGroup = new HDFgroup( meshName, aFile ); 
3112         aTopGroup->OpenOnDisk();
3113
3114         // get number of child HDF objects
3115         int aNbObjects = aTopGroup->nInternalObjects(); 
3116         if ( aNbObjects > 0 ) {
3117           // create mesh
3118           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
3119           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
3120           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
3121           if ( !myNewMeshImpl )
3122             continue;
3123           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
3124
3125           string iorString = GetORB()->object_to_string( myNewMesh );
3126           int newId = myStudyContext->findId( iorString );
3127           myStudyContext->mapOldToNew( id, newId );
3128
3129           // ouv : NPAL12872
3130           // try to read and set auto color flag
3131           char aMeshAutoColorName[ 30 ];
3132           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
3133           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
3134           {
3135             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
3136             aDataset->OpenOnDisk();
3137             size = aDataset->GetSize();
3138             int* anAutoColor = new int[ size ];
3139             aDataset->ReadFromDisk( anAutoColor );
3140             aDataset->CloseOnDisk();
3141             myNewMeshImpl->SetAutoColor( (bool)anAutoColor[0] );
3142           }
3143
3144           // try to read and set reference to shape
3145           GEOM::GEOM_Object_var aShapeObject;
3146           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
3147             // load mesh "Ref on shape" - it's an entry to SObject
3148             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
3149             aDataset->OpenOnDisk();
3150             size = aDataset->GetSize();
3151             char* refFromFile = new char[ size ];
3152             aDataset->ReadFromDisk( refFromFile );
3153             aDataset->CloseOnDisk();
3154             if ( strlen( refFromFile ) > 0 ) {
3155               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
3156
3157               // Make sure GEOM data are loaded first
3158               //loadGeomData( shapeSO->GetFatherComponent() );
3159
3160               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
3161               if ( !CORBA::is_nil( shapeObject ) ) {
3162                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
3163                 if ( !aShapeObject->_is_nil() )
3164                   myNewMeshImpl->SetShape( aShapeObject );
3165               }
3166             }
3167           }
3168
3169         }
3170       }
3171     }
3172
3173     // As all object that can be referred by hypothesis are created,
3174     // we can restore hypothesis data
3175
3176     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
3177     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
3178     {
3179       SMESH_Hypothesis_i* hyp  = hyp_data->first;
3180       string &            data = hyp_data->second;
3181       hyp->LoadFrom( data.c_str() );
3182     }
3183
3184     // Restore the rest mesh data
3185
3186     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
3187     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
3188     {
3189       aTopGroup                   = meshi_group->second;
3190       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
3191       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
3192       SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3193
3194       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
3195       bool hasData = false;
3196
3197       // get mesh old id
3198       string iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
3199       int newId = myStudyContext->findId( iorString );
3200       int id = myStudyContext->getOldId( newId );
3201
3202       // try to find mesh data dataset
3203       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
3204         // load mesh "has data" flag
3205         aDataset = new HDFdataset( "Has data", aTopGroup );
3206         aDataset->OpenOnDisk();
3207         size = aDataset->GetSize();
3208         char* strHasData = new char[ size ];
3209         aDataset->ReadFromDisk( strHasData );
3210         aDataset->CloseOnDisk();
3211         if ( strcmp( strHasData, "1") == 0 ) {
3212           // read mesh data from MED file
3213           myReader.SetMesh( mySMESHDSMesh );
3214           myReader.SetMeshId( id );
3215           myReader.Perform();
3216           hasData = true;
3217         }
3218       }
3219
3220       // try to get applied algorithms
3221       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
3222         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3223         aGroup->OpenOnDisk();
3224         // get number of applied algorithms
3225         int aNbSubObjects = aGroup->nInternalObjects(); 
3226         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
3227         for ( int j = 0; j < aNbSubObjects; j++ ) {
3228           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3229           aGroup->InternalObjectIndentify( j, name_dataset );
3230           // check if it is an algorithm
3231           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
3232             aDataset = new HDFdataset( name_dataset, aGroup );
3233             aDataset->OpenOnDisk();
3234             size = aDataset->GetSize();
3235             char* refFromFile = new char[ size ];
3236             aDataset->ReadFromDisk( refFromFile );
3237             aDataset->CloseOnDisk();
3238
3239             // san - it is impossible to recover applied algorithms using their entries within Load() method
3240
3241             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3242             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3243             int id = atoi( refFromFile );
3244             string anIOR = myStudyContext->getIORbyOldId( id );
3245             if ( !anIOR.empty() ) {
3246               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3247               if ( !CORBA::is_nil( hypObject ) ) {
3248                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3249                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
3250                                            || !myNewMeshImpl->HasShapeToMesh()) )
3251                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
3252               }
3253             }
3254           }
3255         }
3256         aGroup->CloseOnDisk();
3257       }
3258
3259       // try to get applied hypotheses
3260       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
3261         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3262         aGroup->OpenOnDisk();
3263         // get number of applied hypotheses
3264         int aNbSubObjects = aGroup->nInternalObjects(); 
3265         for ( int j = 0; j < aNbSubObjects; j++ ) {
3266           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3267           aGroup->InternalObjectIndentify( j, name_dataset );
3268           // check if it is a hypothesis
3269           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
3270             aDataset = new HDFdataset( name_dataset, aGroup );
3271             aDataset->OpenOnDisk();
3272             size = aDataset->GetSize();
3273             char* refFromFile = new char[ size ];
3274             aDataset->ReadFromDisk( refFromFile );
3275             aDataset->CloseOnDisk();
3276
3277             // san - it is impossible to recover applied hypotheses using their entries within Load() method
3278
3279             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3280             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3281             int id = atoi( refFromFile );
3282             string anIOR = myStudyContext->getIORbyOldId( id );
3283             if ( !anIOR.empty() ) {
3284               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3285               if ( !CORBA::is_nil( hypObject ) ) {
3286                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3287                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
3288                                            || !myNewMeshImpl->HasShapeToMesh()) )
3289                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
3290               }
3291             }
3292           }
3293         }
3294         aGroup->CloseOnDisk();
3295       }
3296
3297       // --> try to find submeshes containers for each type of submesh
3298       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
3299         char name_meshgroup[ 30 ];
3300         if ( j == GetSubMeshOnVertexTag() )
3301           strcpy( name_meshgroup, "SubMeshes On Vertex" );
3302         else if ( j == GetSubMeshOnEdgeTag() )
3303           strcpy( name_meshgroup, "SubMeshes On Edge" );
3304         else if ( j == GetSubMeshOnWireTag() )
3305           strcpy( name_meshgroup, "SubMeshes On Wire" );
3306         else if ( j == GetSubMeshOnFaceTag() )
3307           strcpy( name_meshgroup, "SubMeshes On Face" );
3308         else if ( j == GetSubMeshOnShellTag() )
3309           strcpy( name_meshgroup, "SubMeshes On Shell" );
3310         else if ( j == GetSubMeshOnSolidTag() )
3311           strcpy( name_meshgroup, "SubMeshes On Solid" );
3312         else if ( j == GetSubMeshOnCompoundTag() )
3313           strcpy( name_meshgroup, "SubMeshes On Compound" );
3314
3315         // try to get submeshes container HDF group
3316         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
3317           // open submeshes containers HDF group
3318           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3319           aGroup->OpenOnDisk();
3320
3321           // get number of submeshes
3322           int aNbSubMeshes = aGroup->nInternalObjects(); 
3323           for ( int k = 0; k < aNbSubMeshes; k++ ) {
3324             // identify submesh
3325             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
3326             aGroup->InternalObjectIndentify( k, name_submeshgroup );
3327             if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
3328               // --> get submesh id
3329               int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
3330               if ( subid <= 0 )
3331                 continue;
3332               // open submesh HDF group
3333               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
3334               aSubGroup->OpenOnDisk();
3335
3336               // try to read and set reference to subshape
3337               GEOM::GEOM_Object_var aSubShapeObject;
3338               SMESH::SMESH_subMesh_var aSubMesh;
3339
3340               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
3341                 // load submesh "Ref on shape" - it's an entry to SObject
3342                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
3343                 aDataset->OpenOnDisk();
3344                 size = aDataset->GetSize();
3345                 char* refFromFile = new char[ size ];
3346                 aDataset->ReadFromDisk( refFromFile );
3347                 aDataset->CloseOnDisk();
3348                 if ( strlen( refFromFile ) > 0 ) {
3349                   SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
3350                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
3351                   if ( !CORBA::is_nil( subShapeObject ) ) {
3352                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
3353                     if ( !aSubShapeObject->_is_nil() )
3354                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
3355                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
3356                     if ( aSubMesh->_is_nil() )
3357                       continue;
3358                     string iorSubString = GetORB()->object_to_string( aSubMesh );
3359                     int newSubId = myStudyContext->findId( iorSubString );
3360                     myStudyContext->mapOldToNew( subid, newSubId );
3361                   }
3362                 }
3363               }
3364
3365               if ( aSubMesh->_is_nil() )
3366                 continue;
3367
3368               // VSR: Get submesh data from MED convertor
3369               //                  int anInternalSubmeshId = aSubMesh->GetId(); // this is not a persistent ID, it's an internal one computed from sub-shape
3370               //                  if (myNewMeshImpl->_mapSubMesh.find(anInternalSubmeshId) != myNewMeshImpl->_mapSubMesh.end()) {
3371               //                    if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): loading from MED file submesh with ID = " <<
3372               //                            subid << " for subshape # " << anInternalSubmeshId);
3373               //                    SMESHDS_SubMesh* aSubMeshDS =
3374               //                      myNewMeshImpl->_mapSubMesh[anInternalSubmeshId]->CreateSubMeshDS();
3375               //                    if ( !aSubMeshDS ) {
3376               //                      if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): FAILED to create a submesh for subshape # " <<
3377               //                              anInternalSubmeshId << " in current mesh!");
3378               //                    }
3379               //                    else
3380               //                      myReader.GetSubMesh( aSubMeshDS, subid );
3381               //                  }
3382
3383               // try to get applied algorithms
3384               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
3385                 // open "applied algorithms" HDF group
3386                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3387                 aSubSubGroup->OpenOnDisk();
3388                 // get number of applied algorithms
3389                 int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
3390                 for ( int l = 0; l < aNbSubObjects; l++ ) {
3391                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3392                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
3393                   // check if it is an algorithm
3394                   if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
3395                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
3396                     aDataset->OpenOnDisk();
3397                     size = aDataset->GetSize();
3398                     char* refFromFile = new char[ size ];
3399                     aDataset->ReadFromDisk( refFromFile );
3400                     aDataset->CloseOnDisk();
3401
3402                     //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3403                     //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3404                     int id = atoi( refFromFile );
3405                     string anIOR = myStudyContext->getIORbyOldId( id );
3406                     if ( !anIOR.empty() ) {
3407                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3408                       if ( !CORBA::is_nil( hypObject ) ) {
3409                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3410                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
3411                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
3412                       }
3413                     }
3414                   }
3415                 }
3416                 // close "applied algorithms" HDF group
3417                 aSubSubGroup->CloseOnDisk();
3418               }
3419
3420               // try to get applied hypotheses
3421               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
3422                 // open "applied hypotheses" HDF group
3423                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3424                 aSubSubGroup->OpenOnDisk();
3425                 // get number of applied hypotheses
3426                 int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
3427                 for ( int l = 0; l < aNbSubObjects; l++ ) {
3428                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3429                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
3430                   // check if it is a hypothesis
3431                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
3432                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
3433                     aDataset->OpenOnDisk();
3434                     size = aDataset->GetSize();
3435                     char* refFromFile = new char[ size ];
3436                     aDataset->ReadFromDisk( refFromFile );
3437                     aDataset->CloseOnDisk();
3438
3439                     //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3440                     //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3441                     int id = atoi( refFromFile );
3442                     string anIOR = myStudyContext->getIORbyOldId( id );
3443                     if ( !anIOR.empty() ) {
3444                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3445                       if ( !CORBA::is_nil( hypObject ) ) {
3446                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3447                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
3448                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
3449                       }
3450                     }
3451                   }
3452                 }
3453                 // close "applied hypotheses" HDF group
3454                 aSubSubGroup->CloseOnDisk();
3455               }
3456
3457               // close submesh HDF group
3458               aSubGroup->CloseOnDisk();
3459             }
3460           }
3461           // close submeshes containers HDF group
3462           aGroup->CloseOnDisk();
3463         }
3464       }
3465
3466       if(hasData) {
3467
3468         // Read sub-meshes from MED
3469         // -------------------------
3470         if(MYDEBUG) MESSAGE("Create all sub-meshes");
3471         bool submeshesInFamilies = ( ! aTopGroup->ExistInternalObject( "Submeshes" ));
3472         if ( submeshesInFamilies )
3473         {
3474           // old way working before fix of PAL 12992
3475           myReader.CreateAllSubMeshes();
3476         }
3477         else
3478         {
3479           // open a group
3480           aGroup = new HDFgroup( "Submeshes", aTopGroup ); 
3481           aGroup->OpenOnDisk();
3482
3483           int maxID = mySMESHDSMesh->MaxShapeIndex();
3484           vector< SMESHDS_SubMesh * > subMeshes( maxID + 1, (SMESHDS_SubMesh*) 0 );
3485           vector< TopAbs_ShapeEnum  > smType   ( maxID + 1, TopAbs_SHAPE ); 
3486
3487           PositionCreator aPositionCreator;
3488
3489           SMDS_NodeIteratorPtr nIt = mySMESHDSMesh->nodesIterator();
3490           SMDS_ElemIteratorPtr eIt = mySMESHDSMesh->elementsIterator();
3491           for ( int isNode = 0; isNode < 2; ++isNode )
3492           {
3493             string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3494             if ( aGroup->ExistInternalObject( (char*) aDSName.c_str() ))
3495             {
3496               aDataset = new HDFdataset( (char*) aDSName.c_str(), aGroup );
3497               aDataset->OpenOnDisk();
3498               // read submesh IDs for all elements sorted by ID
3499               int nbElems = aDataset->GetSize();
3500               int* smIDs = new int [ nbElems ];
3501               aDataset->ReadFromDisk( smIDs );
3502               aDataset->CloseOnDisk();
3503
3504               // get elements sorted by ID
3505               TIDSortedElemSet elemSet;
3506               if ( isNode )
3507                 while ( nIt->more() ) elemSet.insert( nIt->next() );
3508               else
3509                 while ( eIt->more() ) elemSet.insert( eIt->next() );
3510               //ASSERT( elemSet.size() == nbElems ); -- issue 20182
3511               // -- Most probably a bad study was saved when there were
3512               // not fixed bugs in SMDS_MeshInfo
3513               if ( elemSet.size() < nbElems ) {
3514                 cout << "SMESH_Gen_i::Load(), warning: Node position data is invalid" << endl;
3515                 nbElems = elemSet.size();
3516               }
3517               // add elements to submeshes
3518               TIDSortedElemSet::iterator iE = elemSet.begin();
3519               for ( int i = 0; i < nbElems; ++i, ++iE )
3520               {
3521                 int smID = smIDs[ i ];
3522                 if ( smID == 0 ) continue;
3523                 const SMDS_MeshElement* elem = *iE;
3524                 if( smID >= maxID ) {
3525                   // corresponding subshape no longer exists: maybe geom group has been edited
3526                   if ( myNewMeshImpl->HasShapeToMesh() )
3527                     mySMESHDSMesh->RemoveElement( elem );
3528                   continue;
3529                 }
3530                 // get or create submesh
3531                 SMESHDS_SubMesh* & sm = subMeshes[ smID ];
3532                 if ( ! sm ) {
3533                   sm = mySMESHDSMesh->NewSubMesh( smID );
3534                   smType[ smID ] = mySMESHDSMesh->IndexToShape( smID ).ShapeType();
3535                 }
3536                 // add
3537                 if ( isNode ) {
3538                   SMDS_PositionPtr pos = aPositionCreator.MakePosition( smType[ smID ]);
3539                   pos->SetShapeId( smID );
3540                   SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>( static_cast<const SMDS_MeshNode*>( elem ));
3541                   node->SetPosition( pos );
3542                   sm->AddNode( node );
3543                 } else {
3544                   sm->AddElement( elem );
3545                 }
3546               }
3547               delete [] smIDs;
3548             }
3549           }
3550         } // end reading submeshes
3551
3552         // Read node positions on sub-shapes (SMDS_Position)
3553
3554         if ( aTopGroup->ExistInternalObject( "Node Positions" ))
3555         {
3556           // There are 5 datasets to read:
3557           // "Nodes on Edges" - ID of node on edge
3558           // "Edge positions" - U parameter on node on edge
3559           // "Nodes on Faces" - ID of node on face
3560           // "Face U positions" - U parameter of node on face
3561           // "Face V positions" - V parameter of node on face
3562           char* aEid_DSName = "Nodes on Edges";
3563           char* aEu_DSName  = "Edge positions";
3564           char* aFu_DSName  = "Face U positions";
3565           //char* aFid_DSName = "Nodes on Faces";
3566           //char* aFv_DSName  = "Face V positions";
3567
3568           // data to retrieve
3569           int nbEids = 0, nbFids = 0;
3570           int *aEids = 0, *aFids  = 0;
3571           double *aEpos = 0, *aFupos = 0, *aFvpos = 0;
3572
3573           // open a group
3574           aGroup = new HDFgroup( "Node Positions", aTopGroup ); 
3575           aGroup->OpenOnDisk();
3576
3577           // loop on 5 data sets
3578           int aNbObjects = aGroup->nInternalObjects();
3579           for ( int i = 0; i < aNbObjects; i++ )
3580           {
3581             // identify dataset
3582             char aDSName[ HDF_NAME_MAX_LEN+1 ];
3583             aGroup->InternalObjectIndentify( i, aDSName );
3584             // read data
3585             aDataset = new HDFdataset( aDSName, aGroup );
3586             aDataset->OpenOnDisk();
3587             if ( aDataset->GetType() == HDF_FLOAT64 ) // Positions
3588             {
3589               double* pos = new double [ aDataset->GetSize() ];
3590               aDataset->ReadFromDisk( pos );
3591               // which one?
3592               if ( strncmp( aDSName, aEu_DSName, strlen( aEu_DSName )) == 0 )
3593                 aEpos = pos;
3594               else if ( strncmp( aDSName, aFu_DSName, strlen( aFu_DSName )) == 0 )
3595                 aFupos = pos;
3596               else
3597                 aFvpos = pos;
3598             }
3599             else // NODE IDS
3600             {
3601               int aSize = aDataset->GetSize();
3602
3603               // for reading files, created from 18.07.2005 till 10.10.2005
3604               if (aDataset->GetType() == HDF_STRING)
3605                 aSize /= sizeof(int);
3606
3607               int* ids = new int [aSize];
3608               aDataset->ReadFromDisk( ids );
3609               // on face or nodes?
3610               if ( strncmp( aDSName, aEid_DSName, strlen( aEid_DSName )) == 0 ) {
3611                 aEids = ids;
3612                 nbEids = aSize;
3613               }
3614               else {
3615                 aFids = ids;
3616                 nbFids = aSize;
3617               }
3618             }
3619             aDataset->CloseOnDisk();
3620           } // loop on 5 datasets
3621
3622           // Set node positions on edges or faces
3623           for ( int onFace = 0; onFace < 2; onFace++ )
3624           {
3625             int nbNodes = ( onFace ? nbFids : nbEids );
3626             if ( nbNodes == 0 ) continue;
3627             int* aNodeIDs = ( onFace ? aFids : aEids );
3628             double* aUPos = ( onFace ? aFupos : aEpos );
3629             double* aVPos = ( onFace ? aFvpos : 0 );
3630             // loop on node IDs
3631             for ( int iNode = 0; iNode < nbNodes; iNode++ )
3632             {
3633               const SMDS_MeshNode* node = mySMESHDSMesh->FindNode( aNodeIDs[ iNode ]);
3634               if ( !node ) continue; // maybe removed while Loading() if geometry changed
3635               SMDS_PositionPtr aPos = node->GetPosition();
3636               ASSERT( aPos );
3637               if ( onFace ) {
3638                 // ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_FACE );-- issue 20182
3639                 // -- Most probably a bad study was saved when there were
3640                 // not fixed bugs in SMDS_MeshInfo
3641                 if ( aPos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
3642                   SMDS_FacePosition* fPos = const_cast<SMDS_FacePosition*>
3643                     ( static_cast<const SMDS_FacePosition*>( aPos.get() ));
3644                   fPos->SetUParameter( aUPos[ iNode ]);
3645                   fPos->SetVParameter( aVPos[ iNode ]);
3646                 }
3647               }
3648               else {
3649                 // ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE );-- issue 20182
3650                 if ( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE ) {
3651                   SMDS_EdgePosition* fPos = const_cast<SMDS_EdgePosition*>
3652                     ( static_cast<const SMDS_EdgePosition*>( aPos.get() ));
3653                   fPos->SetUParameter( aUPos[ iNode ]);
3654                 }
3655               }
3656             }
3657           }
3658           if ( aEids ) delete [] aEids;
3659           if ( aFids ) delete [] aFids;
3660           if ( aEpos ) delete [] aEpos;
3661           if ( aFupos ) delete [] aFupos;
3662           if ( aFvpos ) delete [] aFvpos;
3663
3664           aGroup->CloseOnDisk();
3665
3666         } // if ( aTopGroup->ExistInternalObject( "Node Positions" ) )
3667       } // if ( hasData )
3668
3669       // Recompute State (as computed sub-meshes are restored from MED)
3670       if ( !aShapeObject->_is_nil() || !myNewMeshImpl->HasShapeToMesh()) {
3671         MESSAGE("Compute State Engine ...");
3672         TopoDS_Shape myLocShape;
3673         if(myNewMeshImpl->HasShapeToMesh())
3674           myLocShape = GeomObjectToShape( aShapeObject );
3675         else
3676           myLocShape = SMESH_Mesh::PseudoShape();
3677         
3678         myNewMeshImpl->GetImpl().GetSubMesh(myLocShape)->ComputeStateEngine
3679           (SMESH_subMesh::SUBMESH_RESTORED);
3680         MESSAGE("Compute State Engine finished");
3681       }
3682
3683       // try to get groups
3684       for ( int ii = GetNodeGroupsTag(); ii <= GetVolumeGroupsTag(); ii++ ) {
3685         char name_group[ 30 ];
3686         if ( ii == GetNodeGroupsTag() )
3687           strcpy( name_group, "Groups of Nodes" );
3688         else if ( ii == GetEdgeGroupsTag() )
3689           strcpy( name_group, "Groups of Edges" );
3690         else if ( ii == GetFaceGroupsTag() )
3691           strcpy( name_group, "Groups of Faces" );
3692         else if ( ii == GetVolumeGroupsTag() )
3693           strcpy( name_group, "Groups of Volumes" );
3694
3695         if ( aTopGroup->ExistInternalObject( name_group ) ) {
3696           aGroup = new HDFgroup( name_group, aTopGroup );
3697           aGroup->OpenOnDisk();
3698           // get number of groups
3699           int aNbSubObjects = aGroup->nInternalObjects(); 
3700           for ( int j = 0; j < aNbSubObjects; j++ ) {
3701             char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3702             aGroup->InternalObjectIndentify( j, name_dataset );
3703             // check if it is an group
3704             if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
3705               // --> get group id
3706               int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
3707               if ( subid <= 0 )
3708                 continue;
3709               aDataset = new HDFdataset( name_dataset, aGroup );
3710               aDataset->OpenOnDisk();
3711
3712               // Retrieve actual group name
3713               size = aDataset->GetSize();
3714               char* nameFromFile = new char[ size ];
3715               aDataset->ReadFromDisk( nameFromFile );
3716               aDataset->CloseOnDisk();
3717
3718               // Try to find a shape reference
3719               TopoDS_Shape aShape;
3720               char aRefName[ 30 ];
3721               sprintf( aRefName, "Ref on shape %d", subid);
3722               if ( aGroup->ExistInternalObject( aRefName ) ) {
3723                 // load mesh "Ref on shape" - it's an entry to SObject
3724                 aDataset = new HDFdataset( aRefName, aGroup );
3725                 aDataset->OpenOnDisk();
3726                 size = aDataset->GetSize();
3727                 char* refFromFile = new char[ size ];
3728                 aDataset->ReadFromDisk( refFromFile );
3729                 aDataset->CloseOnDisk();
3730                 if ( strlen( refFromFile ) > 0 ) {
3731                   SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
3732                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
3733                   if ( !CORBA::is_nil( shapeObject ) ) {
3734                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
3735                     if ( !aShapeObject->_is_nil() )
3736                       aShape = GeomObjectToShape( aShapeObject );
3737                   }
3738                 }
3739               }
3740               // Create group servant
3741               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
3742               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
3743                 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape ) );
3744               // Obtain a SMESHDS_Group object 
3745               if ( aNewGroup->_is_nil() )
3746                 continue;
3747
3748               string iorSubString = GetORB()->object_to_string( aNewGroup );
3749               int newSubId = myStudyContext->findId( iorSubString );
3750               myStudyContext->mapOldToNew( subid, newSubId );
3751
3752               SMESH_GroupBase_i* aGroupImpl =
3753                 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aNewGroup ).in() );
3754               if ( !aGroupImpl )
3755                 continue;
3756
3757               SMESH_Group* aLocalGroup  = myLocMesh.GetGroup( aGroupImpl->GetLocalID() );
3758               if ( !aLocalGroup )
3759                 continue;
3760
3761               SMESHDS_GroupBase* aGroupBaseDS = aLocalGroup->GetGroupDS();
3762               aGroupBaseDS->SetStoreName( name_dataset );
3763
3764               // ouv : NPAL12872
3765               // Read color of the group
3766               char aGroupColorName[ 30 ];
3767               sprintf( aGroupColorName, "ColorGroup %d", subid);
3768               if ( aGroup->ExistInternalObject( aGroupColorName ) )
3769               {
3770                 aDataset = new HDFdataset( aGroupColorName, aGroup );
3771                 aDataset->OpenOnDisk();
3772                 size = aDataset->GetSize();
3773                 double* anRGB = new double[ size ];
3774                 aDataset->ReadFromDisk( anRGB );
3775                 aDataset->CloseOnDisk();
3776                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
3777                 aGroupBaseDS->SetColor( aColor );
3778               }
3779
3780               // Fill group with contents from MED file
3781               SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
3782               if ( aGrp )
3783                 myReader.GetGroup( aGrp );
3784             }
3785           }
3786           aGroup->CloseOnDisk();
3787         }
3788       }
3789     }
3790     // close mesh group
3791     if(aTopGroup)
3792       aTopGroup->CloseOnDisk();   
3793   }
3794   // close HDF file
3795   aFile->CloseOnDisk();
3796   delete aFile;
3797
3798   // Remove temporary files created from the stream
3799   if ( !isMultiFile ) 
3800     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3801
3802   INFOS( "SMESH_Gen_i::Load completed" );
3803   return true;
3804 }
3805
3806 //=============================================================================
3807 /*!
3808  *  SMESH_Gen_i::LoadASCII
3809  *
3810  *  Load SMESH module's data in ASCII format
3811  */
3812 //=============================================================================
3813
3814 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
3815                              const SALOMEDS::TMPFile& theStream,
3816                              const char*              theURL,
3817                              bool                     isMultiFile ) {
3818   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
3819   return Load( theComponent, theStream, theURL, isMultiFile );
3820
3821   //before call main ::Load method it's need for decipher text format to
3822   //binary ( "|xx" => x' )
3823   int size = theStream.length();
3824   if ( int((size / 3 )*3) != size ) //error size of buffer
3825     return false;
3826
3827   int real_size = int(size / 3);
3828
3829   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
3830   char tmp[3];
3831   tmp[2]='\0';
3832   int c = -1;
3833   for ( int i = 0; i < real_size; i++ )
3834   {
3835     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
3836     sscanf( tmp, "%x", &c );
3837     sprintf( (char*)&(buffer[i]), "%c", (char)c );
3838   }
3839
3840   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
3841   
3842   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
3843 }
3844
3845 //=============================================================================
3846 /*!
3847  *  SMESH_Gen_i::Close
3848  *
3849  *  Clears study-connected data when it is closed
3850  */
3851 //=============================================================================
3852
3853 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
3854 {
3855   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
3856
3857   // set correct current study
3858   if (theComponent->GetStudy()->StudyId() != GetCurrentStudyID())
3859     SetCurrentStudy(theComponent->GetStudy());
3860
3861   // Clear study contexts data
3862   int studyId = GetCurrentStudyID();
3863   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
3864     delete myStudyContextMap[ studyId ];
3865     myStudyContextMap.erase( studyId );
3866   }
3867
3868   // delete SMESH_Mesh's
3869   StudyContextStruct* context = myGen.GetStudyContext( studyId );
3870   map< int, SMESH_Mesh* >::iterator i_mesh = context->mapMesh.begin();
3871   for ( ; i_mesh != context->mapMesh.end(); ++i_mesh )
3872     delete i_mesh->second;
3873   // delete SMESHDS_Mesh's
3874   // it's too long on big meshes
3875 //   if ( context->myDocument ) {
3876 //     delete context->myDocument;
3877 //     context->myDocument = 0;
3878 //   }
3879   
3880   return;
3881 }
3882
3883 //=============================================================================
3884 /*!
3885  *  SMESH_Gen_i::ComponentDataType
3886  * 
3887  *  Get component data type
3888  */
3889 //=============================================================================
3890
3891 char* SMESH_Gen_i::ComponentDataType()
3892 {
3893   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
3894   return CORBA::string_dup( "SMESH" );
3895 }
3896
3897     
3898 //=============================================================================
3899 /*!
3900  *  SMESH_Gen_i::IORToLocalPersistentID
3901  *  
3902  *  Transform data from transient form to persistent
3903  */
3904 //=============================================================================
3905
3906 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
3907                                            const char*           IORString,
3908                                            CORBA::Boolean        /*isMultiFile*/,
3909                                            CORBA::Boolean        /*isASCII*/ )
3910 {
3911   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
3912   StudyContext* myStudyContext = GetCurrentStudyContext();
3913   
3914   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
3915     int anId = myStudyContext->findId( IORString );
3916     if ( anId ) {
3917       if(MYDEBUG) MESSAGE( "VSR " << anId )
3918       char strId[ 20 ];
3919       sprintf( strId, "%d", anId );
3920       return  CORBA::string_dup( strId );
3921     }
3922   }
3923   return CORBA::string_dup( "" );
3924 }
3925
3926 //=============================================================================
3927 /*!
3928  *  SMESH_Gen_i::LocalPersistentIDToIOR
3929  *
3930  *  Transform data from persistent form to transient
3931  */
3932 //=============================================================================
3933
3934 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
3935                                            const char*           aLocalPersistentID,
3936                                            CORBA::Boolean        /*isMultiFile*/,
3937                                            CORBA::Boolean        /*isASCII*/ )
3938 {
3939   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
3940   StudyContext* myStudyContext = GetCurrentStudyContext();
3941
3942   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
3943     int anId = atoi( aLocalPersistentID );
3944     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
3945   }
3946   return CORBA::string_dup( "" );
3947 }
3948
3949 //=======================================================================
3950 //function : RegisterObject
3951 //purpose  : 
3952 //=======================================================================
3953
3954 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
3955 {
3956   StudyContext* myStudyContext = GetCurrentStudyContext();
3957   if ( myStudyContext && !CORBA::is_nil( theObject )) {
3958     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
3959     return myStudyContext->addObject( string( iorString.in() ) );
3960   }
3961   return 0;
3962 }
3963
3964 //================================================================================
3965 /*!
3966  * \brief Return id of registered object
3967   * \param theObject - the Object
3968   * \retval int - Object id
3969  */
3970 //================================================================================
3971
3972 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
3973 {
3974   StudyContext* myStudyContext = GetCurrentStudyContext();
3975   if ( myStudyContext && !CORBA::is_nil( theObject )) {
3976     string iorString = GetORB()->object_to_string( theObject );
3977     return myStudyContext->findId( iorString );
3978   }
3979   return 0;
3980 }
3981
3982 //=============================================================================
3983 /*! 
3984  *  SMESHEngine_factory
3985  *
3986  *  C factory, accessible with dlsym, after dlopen  
3987  */
3988 //=============================================================================
3989
3990 extern "C"
3991 { SMESH_I_EXPORT
3992   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
3993                                                  PortableServer::POA_ptr   poa, 
3994                                                  PortableServer::ObjectId* contId,
3995                                                  const char*               instanceName, 
3996                                                  const char*               interfaceName )
3997   {
3998     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
3999     if(MYDEBUG) SCRUTE(interfaceName);
4000     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
4001     return aSMESHGen->getId() ;
4002   }
4003 }