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