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