Salome HOME
PAL12992. Store/restore submeshesh directly using HDF but not med families
[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 #include <dlfcn.h>
57
58 #include <HDFOI.hxx>
59
60 #include "SMESH_Gen_i.hxx"
61 #include "SMESH_Mesh_i.hxx"
62 #include "SMESH_Hypothesis_i.hxx"
63 #include "SMESH_Algo_i.hxx"
64 #include "SMESH_Group_i.hxx"
65 #include "SMESH_PythonDump.hxx"
66
67 #include "SMESHDS_Document.hxx"
68 #include "SMESHDS_Group.hxx"
69 #include "SMESHDS_GroupOnGeom.hxx"
70 #include "SMESH_Mesh.hxx"
71 #include "SMESH_Hypothesis.hxx"
72 #include "SMESH_Group.hxx"
73 #include "SMESH_MeshEditor.hxx"
74
75 #include "SMDS_EdgePosition.hxx"
76 #include "SMDS_FacePosition.hxx"
77 #include "SMDS_VertexPosition.hxx"
78 #include "SMDS_SpacePosition.hxx"
79
80 #include CORBA_SERVER_HEADER(SMESH_Group)
81 #include CORBA_SERVER_HEADER(SMESH_Filter)
82
83 #include "DriverMED_W_SMESHDS_Mesh.h"
84 #include "DriverMED_R_SMESHDS_Mesh.h"
85
86 #include "SALOMEDS_Tool.hxx"
87 #include "SALOME_NamingService.hxx"
88 #include "SALOME_LifeCycleCORBA.hxx"
89 #include "Utils_SINGLETON.hxx"
90 #include "OpUtil.hxx"
91
92 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
93
94 #include "GEOM_Client.hxx"
95 #include "Utils_ExceptHandlers.hxx"
96
97 #include <map>
98
99 using namespace std;
100 using SMESH::TPythonDump;
101
102 #define NUM_TMP_FILES 2
103
104 #ifdef _DEBUG_
105 static int MYDEBUG = 1;
106 #else
107 static int MYDEBUG = 0;
108 #endif
109
110 // Static variables definition
111 CORBA::ORB_var          SMESH_Gen_i::myOrb;
112 PortableServer::POA_var SMESH_Gen_i::myPoa;
113 SALOME_NamingService*   SMESH_Gen_i::myNS  = NULL;
114 SALOME_LifeCycleCORBA*  SMESH_Gen_i::myLCC = NULL;
115 SMESH_Gen_i*            SMESH_Gen_i::mySMESHGen = NULL;
116
117 //=============================================================================
118 /*!
119  *  GetServant [ static ]
120  *
121  *  Get servant of the CORBA object
122  */
123 //=============================================================================
124
125 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
126 {
127   if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
128     return NULL;
129   try {
130     PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
131     return aServant;
132   } 
133   catch (...) {
134     INFOS( "GetServant - Unknown exception was caught!!!" ); 
135     return NULL;
136   }
137 }
138
139 //=============================================================================
140 /*!
141  *  SObjectToObject [ static ]
142  *
143  *  Get CORBA object corresponding to the SALOMEDS::SObject
144  */
145 //=============================================================================
146
147 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
148 {
149   SALOMEDS::GenericAttribute_var anAttr;
150   CORBA::Object_var anObj;
151   if ( !theSObject->_is_nil() ) {
152     try {
153       if( theSObject->FindAttribute( anAttr, "AttributeIOR" ) ) {
154         SALOMEDS::AttributeIOR_var anIOR  = SALOMEDS::AttributeIOR::_narrow( anAttr );
155         CORBA::String_var aValue = anIOR->Value();
156         if( strcmp( aValue, "" ) != 0 )
157           anObj = GetORB()->string_to_object( aValue );
158         }
159     }
160     catch( ... ) {
161       INFOS( "SObjectToObject - Unknown exception was caught!!!" );
162     }
163   }
164   return anObj;
165 }
166
167 //=============================================================================
168 /*!
169  *  GetNS [ static ]
170  *
171  *  Get SALOME_NamingService object 
172  */
173 //=============================================================================
174
175 SALOME_NamingService* SMESH_Gen_i::GetNS()
176 {
177   if ( myNS == NULL ) {
178     myNS = SINGLETON_<SALOME_NamingService>::Instance();
179     ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
180     myNS->init_orb( GetORB() );
181   }
182   return myNS;
183 }
184
185 //=============================================================================
186 /*!
187  *  GetLCC [ static ]
188  *
189  *  Get SALOME_LifeCycleCORBA object
190  */
191 //=============================================================================     
192 SALOME_LifeCycleCORBA*  SMESH_Gen_i::GetLCC() {
193   if ( myLCC == NULL ) {
194     myLCC = new SALOME_LifeCycleCORBA( GetNS() );
195   }
196   return myLCC;
197 }
198
199
200 //=============================================================================
201 /*!
202  *  GetGeomEngine [ static ]
203  *
204  *  Get GEOM::GEOM_Gen reference
205  */
206 //=============================================================================     
207 GEOM::GEOM_Gen_ptr SMESH_Gen_i::GetGeomEngine() {
208   GEOM::GEOM_Gen_var aGeomEngine =
209     GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
210   return aGeomEngine._retn();
211 }
212
213 //=============================================================================
214 /*!
215  *  SMESH_Gen_i::SMESH_Gen_i
216  *
217  *  Default constructor: not for use
218  */
219 //=============================================================================
220
221 SMESH_Gen_i::SMESH_Gen_i()
222 {
223   INFOS( "SMESH_Gen_i::SMESH_Gen_i : default constructor" );
224 }
225
226 //=============================================================================
227 /*!
228  *  SMESH_Gen_i::SMESH_Gen_i 
229  *
230  *  Standard constructor, used with Container
231  */
232 //=============================================================================
233
234 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr            orb,
235                           PortableServer::POA_ptr   poa,
236                           PortableServer::ObjectId* contId, 
237                           const char*               instanceName, 
238                           const char*               interfaceName )
239      : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
240 {
241   INFOS( "SMESH_Gen_i::SMESH_Gen_i : standard constructor" );
242
243   myOrb = CORBA::ORB::_duplicate(orb);
244   myPoa = PortableServer::POA::_duplicate(poa);
245   
246   _thisObj = this ;
247   _id = myPoa->activate_object( _thisObj );
248   
249   myIsEmbeddedMode = false;
250   myShapeReader = NULL;  // shape reader
251   mySMESHGen = this;
252
253   // set it in standalone mode only
254   //OSD::SetSignal( true );
255 }
256
257 //=============================================================================
258 /*!
259  *  SMESH_Gen_i::~SMESH_Gen_i
260  *
261  *  Destructor
262  */
263 //=============================================================================
264
265 SMESH_Gen_i::~SMESH_Gen_i()
266 {
267   INFOS( "SMESH_Gen_i::~SMESH_Gen_i" );
268
269   // delete hypothesis creators
270   map<string, GenericHypothesisCreator_i*>::iterator itHyp;
271   for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
272   {
273     delete (*itHyp).second;
274   }
275   myHypCreatorMap.clear();
276
277   // Clear study contexts data
278   map<int, StudyContext*>::iterator it;
279   for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
280     delete it->second;
281   }
282   myStudyContextMap.clear();
283   // delete shape reader
284   if ( !myShapeReader ) 
285     delete myShapeReader;
286 }
287   
288 //=============================================================================
289 /*!
290  *  SMESH_Gen_i::createHypothesis
291  *
292  *  Create hypothesis of given type
293  */
294 //=============================================================================
295 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
296                                                           const char* theLibName)
297      throw (SALOME::SALOME_Exception)
298 {
299   Unexpect aCatch(SALOME_SalomeException);
300   if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << theLibName);
301
302   // create a new hypothesis object servant
303   SMESH_Hypothesis_i* myHypothesis_i = 0;
304   SMESH::SMESH_Hypothesis_var hypothesis_i;
305
306   try
307   {
308     // check, if creator for this hypothesis type already exists
309     if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
310     {
311       // load plugin library
312       if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
313       void* libHandle = dlopen (theLibName, RTLD_LAZY);
314       if (!libHandle)
315       {
316         // report any error, if occured
317         const char* anError = dlerror();
318         throw(SALOME_Exception(anError));
319       }
320
321       // get method, returning hypothesis creator
322       if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
323       typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* theHypName);
324       GetHypothesisCreator procHandle =
325         (GetHypothesisCreator)dlsym( libHandle, "GetHypothesisCreator" );
326       if (!procHandle)
327       {
328         throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
329         dlclose(libHandle);
330       }
331
332       // get hypothesis creator
333       if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
334       GenericHypothesisCreator_i* aCreator = procHandle(theHypName);
335       if (!aCreator)
336       {
337         throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
338       }
339
340       // map hypothesis creator to a hypothesis name
341       myHypCreatorMap[string(theHypName)] = aCreator;
342     }
343
344     // create a new hypothesis object, store its ref. in studyContext
345     if(MYDEBUG) MESSAGE("Create Hypothesis " << theHypName);
346     myHypothesis_i =
347       myHypCreatorMap[string(theHypName)]->Create (myPoa, GetCurrentStudyID(), &myGen);
348     // _CS_gbo Explicit activation (no longer made in the constructor).
349     myHypothesis_i->Activate();
350     myHypothesis_i->SetLibName(theLibName); // for persistency assurance
351   }
352   catch (SALOME_Exception& S_ex)
353   {
354     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
355   }
356
357   if (!myHypothesis_i)
358     return hypothesis_i._retn();
359
360   // activate the CORBA servant of hypothesis
361   hypothesis_i = SMESH::SMESH_Hypothesis::_narrow( myHypothesis_i->_this() );
362   int nextId = RegisterObject( hypothesis_i );
363   if(MYDEBUG) MESSAGE( "Add hypo to map with id = "<< nextId );
364
365   return hypothesis_i._retn();
366 }
367   
368 //=============================================================================
369 /*!
370  *  SMESH_Gen_i::createMesh
371  *
372  *  Create empty mesh on shape
373  */
374 //=============================================================================
375 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
376      throw ( SALOME::SALOME_Exception )
377 {
378   Unexpect aCatch(SALOME_SalomeException);
379   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
380
381   // Get or create the GEOM_Client instance
382   try {
383     // create a new mesh object servant, store it in a map in study context
384     SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
385     // create a new mesh object
386     meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
387
388     // activate the CORBA servant of Mesh
389     SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
390     int nextId = RegisterObject( mesh );
391     if(MYDEBUG) MESSAGE( "Add mesh to map with id = "<< nextId);
392     return mesh._retn();
393   }
394   catch (SALOME_Exception& S_ex) {
395     THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
396   }
397   return SMESH::SMESH_Mesh::_nil();
398 }
399
400 //=============================================================================
401 /*!
402  *  SMESH_Gen_i::GetShapeReader
403  *
404  *  Get shape reader
405  */
406 //=============================================================================
407 GEOM_Client* SMESH_Gen_i::GetShapeReader()
408 {
409   // create shape reader if necessary
410   if ( !myShapeReader ) 
411     myShapeReader = new GEOM_Client(GetContainerRef());
412   ASSERT( myShapeReader );
413   return myShapeReader;
414 }
415
416 //=============================================================================
417 /*!
418  *  SMESH_Gen_i::SetEmbeddedMode
419  *
420  *  Set current mode
421  */
422 //=============================================================================
423
424 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
425 {
426   myIsEmbeddedMode = theMode;
427
428   if ( !myIsEmbeddedMode ) {
429     bool raiseFPE;
430 #ifdef _DEBUG_
431     raiseFPE = true;
432     char* envDisableFPE = getenv("DISABLE_FPE");
433     if (envDisableFPE && atoi(envDisableFPE))
434       raiseFPE = false;
435 #else
436     raiseFPE = false;
437 #endif
438     OSD::SetSignal( raiseFPE );
439   }
440   // else OSD::SetSignal() is called in GUI
441 }
442
443 //=============================================================================
444 /*!
445  *  SMESH_Gen_i::IsEmbeddedMode
446  *
447  *  Get current mode
448  */
449 //=============================================================================
450
451 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
452 {
453   return myIsEmbeddedMode;
454 }
455
456 //=============================================================================
457 /*!
458  *  SMESH_Gen_i::SetCurrentStudy
459  *
460  *  Set current study
461  */
462 //=============================================================================
463
464 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
465 {
466   //if(MYDEBUG)
467   //MESSAGE( "SMESH_Gen_i::SetCurrentStudy" );
468   myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
469   // create study context, if it doesn't exist and set current study
470   int studyId = GetCurrentStudyID();
471   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SetCurrentStudy: study Id = " << studyId );
472   if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() ) {
473     myStudyContextMap[ studyId ] = new StudyContext;      
474   }
475
476   // myCurrentStudy may be nil
477   if ( !CORBA::is_nil( myCurrentStudy ) ) {
478     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder(); 
479     if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
480       aStudyBuilder->LoadWith( myCurrentStudy->FindComponent( "GEOM" ), GetGeomEngine() );
481
482   // set current study for geom engine
483   //if ( !CORBA::is_nil( GetGeomEngine() ) )
484   //  GetGeomEngine()->GetCurrentStudy( myCurrentStudy->StudyId() );
485   }
486 }
487
488 //=============================================================================
489 /*!
490  *  SMESH_Gen_i::GetCurrentStudy
491  *
492  *  Get current study
493  */
494 //=============================================================================
495
496 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
497 {
498   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
499   return SALOMEDS::Study::_duplicate( myCurrentStudy );
500 }
501
502 //=============================================================================
503 /*!
504  *  SMESH_Gen_i::GetCurrentStudyContext 
505  *
506  *  Get current study context
507  */
508 //=============================================================================
509 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
510 {
511   if ( !CORBA::is_nil( myCurrentStudy ) &&
512       myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
513     return myStudyContextMap[ myCurrentStudy->StudyId() ];
514   else
515     return 0;
516 }
517
518 //=============================================================================
519 /*!
520  *  SMESH_Gen_i::CreateHypothesis 
521  *
522  *  Create hypothesis/algorothm of given type and publish it in the study
523  */
524 //=============================================================================
525
526 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
527                                                            const char* theLibName )
528      throw ( SALOME::SALOME_Exception )
529 {
530   Unexpect aCatch(SALOME_SalomeException);
531   // Create hypothesis/algorithm
532   SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
533
534   // Publish hypothesis/algorithm in the study
535   if ( CanPublishInStudy( hyp ) ) {
536     SALOMEDS::SObject_var aSO = PublishHypothesis( myCurrentStudy, hyp );
537     if ( !aSO->_is_nil() ) {
538       // Update Python script
539       TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
540                     << theHypName << "', '" << theLibName << "')";
541     }
542   }
543
544   return hyp._retn();
545 }
546
547 //================================================================================
548 /*!
549  * \brief Return hypothesis of given type holding parameter values of the existing mesh
550   * \param theHypType - hypothesis type name
551   * \param theLibName - plugin library name
552   * \param theMesh - The mesh of interest
553   * \param theGeom - The shape to get parameter values from
554   * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
555   *    in a study and used to compute the mesh, or a temporary one created just to pass
556   *    parameter values
557  */
558 //================================================================================
559
560 SMESH::SMESH_Hypothesis_ptr
561 SMESH_Gen_i::GetHypothesisParameterValues (const char*           theHypType,
562                                            const char*           theLibName,
563                                            SMESH::SMESH_Mesh_ptr theMesh,
564                                            GEOM::GEOM_Object_ptr theGeom)
565     throw ( SALOME::SALOME_Exception )
566 {
567   Unexpect aCatch(SALOME_SalomeException);
568   if ( CORBA::is_nil( theMesh ) )
569     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
570   if ( CORBA::is_nil( theGeom ) )
571     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
572
573   // -----------------------------------------------
574   // find hypothesis used to mesh theGeom
575   // -----------------------------------------------
576
577   // get mesh and shape
578   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
579   TopoDS_Shape shape = GeomObjectToShape( theGeom );
580   if ( !meshServant || shape.IsNull() )
581     return SMESH::SMESH_Hypothesis::_nil();
582   ::SMESH_Mesh& mesh = meshServant->GetImpl();
583
584   if ( mesh.NbNodes() == 0 ) // empty mesh
585     return SMESH::SMESH_Hypothesis::_nil();
586
587   // create a temporary hypothesis to know its dimention
588   SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
589   SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
590   if ( !hypServant )
591     return SMESH::SMESH_Hypothesis::_nil();
592   ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
593
594   // look for a hypothesis of theHypType used to mesh the shape
595   if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
596   {
597     // check local shape
598     SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
599     int nbLocalHyps = aHypList->length();
600     for ( int i = 0; i < nbLocalHyps; i++ )
601       if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND local!
602         return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
603     // check super shapes
604     TopTools_ListIteratorOfListOfShape itShape( mesh.GetAncestors( shape ));
605     while ( nbLocalHyps == 0 && itShape.More() ) {
606       GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
607       if ( ! CORBA::is_nil( geomObj )) {
608         SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
609         nbLocalHyps = aHypList->length();
610         for ( int i = 0; i < nbLocalHyps; i++ )
611           if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
612             return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
613       }
614       itShape.Next();
615     }
616   }
617
618   // let the temporary hypothesis find out some how parameter values
619   if ( hyp->SetParametersByMesh( &mesh, shape ))
620     return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
621     
622   return SMESH::SMESH_Hypothesis::_nil();
623 }
624
625 //=============================================================================
626 /*!
627  *  SMESH_Gen_i::CreateMesh
628  *
629  *  Create empty mesh on a shape and publish it in the study
630  */
631 //=============================================================================
632
633 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
634      throw ( SALOME::SALOME_Exception )
635 {
636   Unexpect aCatch(SALOME_SalomeException);
637   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
638   // create mesh
639   SMESH::SMESH_Mesh_var mesh = this->createMesh();
640   // set shape
641   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
642   ASSERT( meshServant );
643   meshServant->SetShape( theShapeObject );
644
645   // publish mesh in the study
646   if ( CanPublishInStudy( mesh ) ) {
647     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
648     aStudyBuilder->NewCommand();  // There is a transaction
649     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
650     aStudyBuilder->CommitCommand();
651     if ( !aSO->_is_nil() ) {
652       // Update Python script
653       TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
654     }
655   }
656
657   return mesh._retn();
658 }
659
660 //=============================================================================
661 /*!
662  *  SMESH_Gen_i::CreateEmptyMesh
663  *
664  *  Create empty mesh
665  */
666 //=============================================================================
667
668 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
669      throw ( SALOME::SALOME_Exception )
670 {
671   Unexpect aCatch(SALOME_SalomeException);
672   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
673   // create mesh
674   SMESH::SMESH_Mesh_var mesh = this->createMesh();
675
676   // publish mesh in the study
677   if ( CanPublishInStudy( mesh ) ) {
678     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
679     aStudyBuilder->NewCommand();  // There is a transaction
680     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
681     aStudyBuilder->CommitCommand();
682     if ( !aSO->_is_nil() ) {
683       // Update Python script
684       TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
685     }
686   }
687
688   return mesh._retn();
689 }
690
691 //=============================================================================
692 /*!
693  *  SMESH_Gen_i::CreateMeshFromUNV
694  *
695  *  Create mesh and import data from UNV file
696  */
697 //=============================================================================
698
699 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
700   throw ( SALOME::SALOME_Exception )
701 {
702   Unexpect aCatch(SALOME_SalomeException);
703   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromUNV" );
704
705   SMESH::SMESH_Mesh_var aMesh = createMesh();
706   string aFileName;
707   // publish mesh in the study
708   if ( CanPublishInStudy( aMesh ) ) {
709     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
710     aStudyBuilder->NewCommand();  // There is a transaction
711     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
712     aStudyBuilder->CommitCommand();
713     if ( !aSO->_is_nil() ) {
714       // Update Python script
715       TPythonDump() << aSO << " = smeshgen.CreateMeshesFromUNV('" << theFileName << "')";
716     }
717   }
718
719   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
720   ASSERT( aServant );
721   aServant->ImportUNVFile( theFileName );
722
723   // Dump creation of groups
724   aServant->GetGroups();
725
726   return aMesh._retn();
727 }
728
729 //=============================================================================
730 /*!
731  *  SMESH_Gen_i::CreateMeshFromMED
732  *
733  *  Create mesh and import data from MED file
734  */
735 //=============================================================================
736
737 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
738                                                      SMESH::DriverMED_ReadStatus& theStatus)
739      throw ( SALOME::SALOME_Exception )
740 {
741   Unexpect aCatch(SALOME_SalomeException);
742   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshFromMED" );
743
744   // Retrieve mesh names from the file
745   DriverMED_R_SMESHDS_Mesh myReader;
746   myReader.SetFile( theFileName );
747   myReader.SetMeshId( -1 );
748   Driver_Mesh::Status aStatus;
749   list<string> aNames = myReader.GetMeshNames(aStatus);
750   SMESH::mesh_array_var aResult = new SMESH::mesh_array();
751   theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
752
753   { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
754
755   // Python Dump
756   TPythonDump aPythonDump;
757   aPythonDump << "([";
758   //TCollection_AsciiString aStr ("([");
759
760   if (theStatus == SMESH::DRS_OK) {
761     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
762     aStudyBuilder->NewCommand();  // There is a transaction
763     aResult->length( aNames.size() );
764     int i = 0;
765     
766     // Iterate through all meshes and create mesh objects
767     for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ ) {
768       // Python Dump
769       //if (i > 0) aStr += ", ";
770       if (i > 0) aPythonDump << ", ";
771
772       // create mesh
773       SMESH::SMESH_Mesh_var mesh = createMesh();
774       
775       // publish mesh in the study
776       SALOMEDS::SObject_var aSO;
777       if ( CanPublishInStudy( mesh ) )
778         aSO = PublishMesh( myCurrentStudy, mesh.in(), (*it).c_str() );
779       if ( !aSO->_is_nil() ) {
780         // Python Dump
781         aPythonDump << aSO;
782         //aStr += aSO->GetID();
783       } else {
784         // Python Dump
785         aPythonDump << "mesh_" << i;
786 //         aStr += "mesh_";
787 //         aStr += TCollection_AsciiString(i);
788       }
789
790       // Read mesh data (groups are published automatically by ImportMEDFile())
791       SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
792       ASSERT( meshServant );
793       SMESH::DriverMED_ReadStatus status1 =
794         meshServant->ImportMEDFile( theFileName, (*it).c_str() );
795       if (status1 > theStatus)
796         theStatus = status1;
797
798       aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
799     }
800     aStudyBuilder->CommitCommand();
801   }
802
803   // Update Python script
804   aPythonDump << "], status) = " << this << ".CreateMeshesFromMED('" << theFileName << "')";
805   }
806   // Dump creation of groups
807   for ( int i = 0; i < aResult->length(); ++i )
808     aResult[ i ]->GetGroups();
809
810   return aResult._retn();
811 }
812
813 //=============================================================================
814 /*!
815  *  SMESH_Gen_i::CreateMeshFromSTL
816  *
817  *  Create mesh and import data from STL file
818  */
819 //=============================================================================
820
821 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
822   throw ( SALOME::SALOME_Exception )
823 {
824   Unexpect aCatch(SALOME_SalomeException);
825   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromSTL" );
826
827   SMESH::SMESH_Mesh_var aMesh = createMesh();
828   string aFileName;
829   // publish mesh in the study
830   if ( CanPublishInStudy( aMesh ) ) {
831     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
832     aStudyBuilder->NewCommand();  // There is a transaction
833     SALOMEDS::SObject_var aSO = PublishInStudy
834       ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
835     aStudyBuilder->CommitCommand();
836     if ( !aSO->_is_nil() ) {
837       // Update Python script
838       TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL('" << theFileName << "')";
839     }
840   }
841
842   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
843   ASSERT( aServant );
844   aServant->ImportSTLFile( theFileName );
845   return aMesh._retn();
846 }
847
848 //=============================================================================
849 /*!
850  *  SMESH_Gen_i::IsReadyToCompute
851  *
852  *  Returns true if mesh contains enough data to be computed
853  */
854 //=============================================================================
855
856 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
857                                               GEOM::GEOM_Object_ptr theShapeObject )
858   throw ( SALOME::SALOME_Exception )
859 {
860   Unexpect aCatch(SALOME_SalomeException);
861   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
862
863   if ( CORBA::is_nil( theShapeObject ) )
864     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
865                                   SALOME::BAD_PARAM );
866
867   if ( CORBA::is_nil( theMesh ) )
868     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
869                                   SALOME::BAD_PARAM );
870
871   try {
872     // get mesh servant
873     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
874     ASSERT( meshServant );
875     if ( meshServant ) {
876       // get local TopoDS_Shape
877       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
878       // call implementation
879       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
880       return myGen.CheckAlgoState( myLocMesh, myLocShape );
881     }
882   }
883   catch ( SALOME_Exception& S_ex ) {
884     INFOS( "catch exception "<< S_ex.what() );
885   }
886   return false;
887 }
888
889 //================================================================================
890 /*!
891  * \brief Returns errors of hypotheses definintion
892   * \param theMesh - the mesh
893   * \param theSubObject - the main or sub- shape
894   * \retval SMESH::algo_error_array* - sequence of errors
895  */
896 //================================================================================
897
898 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh, 
899                                                     GEOM::GEOM_Object_ptr theSubObject )
900       throw ( SALOME::SALOME_Exception )
901 {
902   Unexpect aCatch(SALOME_SalomeException);
903   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
904
905   if ( CORBA::is_nil( theSubObject ) )
906     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
907
908   if ( CORBA::is_nil( theMesh ) )
909     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
910
911   SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
912   try {
913     SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
914     ASSERT( meshServant );
915     if ( meshServant ) {
916       TopoDS_Shape myLocShape = GeomObjectToShape( theSubObject );
917       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
918       list< ::SMESH_Gen::TAlgoStateError > error_list;
919       list< ::SMESH_Gen::TAlgoStateError >::iterator error;
920       // call ::SMESH_Gen::GetAlgoState()
921       myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
922       error_array->length( error_list.size() );
923       int i = 0;
924       for ( error = error_list.begin(); error != error_list.end(); ++error )
925       {
926         // error name
927         SMESH::AlgoStateErrorName errName;
928         switch ( error->_name ) {
929         case ::SMESH_Gen::MISSING_ALGO:     errName = SMESH::MISSING_ALGO; break;
930         case ::SMESH_Gen::MISSING_HYPO:     errName = SMESH::MISSING_HYPO; break;
931         case ::SMESH_Gen::NOT_CONFORM_MESH: errName = SMESH::NOT_CONFORM_MESH; break;
932         default:
933           THROW_SALOME_CORBA_EXCEPTION( "bad error name",SALOME::BAD_PARAM );
934         }
935         // algo name
936         CORBA::String_var algoName;
937         if ( error->_algo ) {
938           if ( !myCurrentStudy->_is_nil() ) {
939             // find algo in the study
940             SALOMEDS::SComponent_var father = SALOMEDS::SComponent::_narrow
941               ( myCurrentStudy->FindComponent( ComponentDataType() ) );
942             if ( !father->_is_nil() ) {
943               SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( father );
944               for ( ; itBig->More(); itBig->Next() ) {
945                 SALOMEDS::SObject_var gotBranch = itBig->Value();
946                 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
947                   SALOMEDS::ChildIterator_var algoIt = myCurrentStudy->NewChildIterator( gotBranch );
948                   for ( ; algoIt->More(); algoIt->Next() ) {
949                     SALOMEDS::SObject_var algoSO = algoIt->Value();
950                     CORBA::Object_var    algoIOR = SObjectToObject( algoSO );
951                     if ( !CORBA::is_nil( algoIOR )) {
952                       SMESH_Hypothesis_i* myImpl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
953                       if ( myImpl && myImpl->GetImpl() == error->_algo ) {
954                         algoName = algoSO->GetName();
955                         break;
956                       }
957                     }
958                   } // loop on algo SO's
959                   break;
960                 } // if algo tag
961               } // SMESH component iterator
962             }
963           }
964           if ( algoName.in() == 0 )
965             // use algo type name
966             algoName = CORBA::string_dup( error->_algo->GetName() );
967         }
968         // fill AlgoStateError structure
969         SMESH::AlgoStateError & errStruct = error_array[ i++ ];
970         errStruct.name         = errName;
971         errStruct.algoName     = algoName;
972         errStruct.algoDim      = error->_algoDim;
973         errStruct.isGlobalAlgo = error->_isGlobalAlgo;
974       }
975     }
976   }
977   catch ( SALOME_Exception& S_ex ) {
978     INFOS( "catch exception "<< S_ex.what() );
979   }
980   return error_array._retn();
981 }
982
983 //=============================================================================
984 /*!
985  *  SMESH_Gen_i::GetSubShapesId
986  *
987  *  Get sub-shapes unique ID's list
988  */
989 //=============================================================================
990
991 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
992                                             const SMESH::object_array& theListOfSubShapeObject )
993      throw ( SALOME::SALOME_Exception )
994 {
995   Unexpect aCatch(SALOME_SalomeException);
996   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
997
998   SMESH::long_array_var shapesId = new SMESH::long_array;
999   set<int> setId;
1000
1001   if ( CORBA::is_nil( theMainShapeObject ) )
1002     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1003                                   SALOME::BAD_PARAM );
1004
1005   try
1006     {
1007       TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1008       TopTools_IndexedMapOfShape myIndexToShape;      
1009       TopExp::MapShapes(myMainShape,myIndexToShape);
1010
1011       for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
1012         {
1013           GEOM::GEOM_Object_var aShapeObject
1014             = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1015           if ( CORBA::is_nil( aShapeObject ) )
1016             THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1017                                         SALOME::BAD_PARAM );
1018
1019           TopoDS_Shape locShape  = GeomObjectToShape(aShapeObject);
1020           for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1021             {
1022               const TopoDS_Face& F = TopoDS::Face(exp.Current());
1023               setId.insert(myIndexToShape.FindIndex(F));
1024               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1025             }
1026           for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1027             {
1028               const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1029               setId.insert(myIndexToShape.FindIndex(E));
1030               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1031             }
1032           for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1033             {
1034               const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1035               setId.insert(myIndexToShape.FindIndex(V));
1036               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1037             }
1038         }
1039       shapesId->length(setId.size());
1040       set<int>::iterator iind;
1041       int i=0;
1042       for (iind = setId.begin(); iind != setId.end(); iind++)
1043         {
1044           if(MYDEBUG) SCRUTE((*iind));
1045           shapesId[i] = (*iind);
1046           if(MYDEBUG) SCRUTE(shapesId[i]);
1047           i++;
1048         }
1049     }
1050   catch (SALOME_Exception& S_ex)
1051     {
1052       THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1053     }
1054
1055   return shapesId._retn();
1056 }
1057
1058 //=============================================================================
1059 /*!
1060  *  SMESH_Gen_i::Compute
1061  *
1062  *  Compute mesh on a shape
1063  */
1064 //=============================================================================
1065
1066 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1067                                      GEOM::GEOM_Object_ptr theShapeObject )
1068      throw ( SALOME::SALOME_Exception )
1069 {
1070   Unexpect aCatch(SALOME_SalomeException);
1071   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1072
1073   if ( CORBA::is_nil( theShapeObject ) )
1074     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
1075                                   SALOME::BAD_PARAM );
1076
1077   if ( CORBA::is_nil( theMesh ) )
1078     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1079                                   SALOME::BAD_PARAM );
1080
1081   // Update Python script
1082   TPythonDump() << "isDone = " << this << ".Compute( "
1083                 << theMesh << ", " << theShapeObject << ")";
1084   TPythonDump() << "if not isDone: print 'Mesh " << theMesh << " : computation failed'";
1085
1086   try {
1087     // get mesh servant
1088     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1089     ASSERT( meshServant );
1090     if ( meshServant ) {
1091       // get local TopoDS_Shape
1092       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1093       // call implementation compute
1094       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1095       return myGen.Compute( myLocMesh, myLocShape);
1096     }
1097   }
1098   catch ( SALOME_Exception& S_ex ) {
1099     INFOS( "Compute(): catch exception "<< S_ex.what() );
1100   }
1101   catch ( ... ) {
1102     INFOS( "Compute(): unknown exception " );
1103   }
1104   return false;
1105 }
1106
1107 //================================================================================
1108 /*!
1109  * \brief Return geometrical object the given element is built on
1110  *  \param theMesh - the mesh the element is in
1111  *  \param theElementID - the element ID
1112  *  \param theGeomName - the name of the result geom object if it is not yet published
1113  *  \retval GEOM::GEOM_Object_ptr - the found or just published geom object
1114  */
1115 //================================================================================
1116
1117 GEOM::GEOM_Object_ptr
1118 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
1119                                        CORBA::Long            theElementID,
1120                                        const char*            theGeomName)
1121   throw ( SALOME::SALOME_Exception )
1122 {
1123   Unexpect aCatch(SALOME_SalomeException);
1124   if ( CORBA::is_nil( theMesh ) )
1125     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
1126
1127   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
1128   GEOM::GEOM_Gen_var    geomGen   = GetGeomEngine();
1129
1130   // get a core mesh DS
1131   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1132   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
1133   {
1134     ::SMESH_Mesh & mesh = meshServant->GetImpl();
1135     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
1136     // find the element in mesh
1137     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) )
1138       // find a shape id by the element
1139       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
1140         // get a geom object by the shape id
1141         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
1142         if ( geom->_is_nil() ) {
1143           GEOM::GEOM_IShapesOperations_var op =
1144             geomGen->GetIShapesOperations( GetCurrentStudyID() );
1145           if ( !op->_is_nil() )
1146             geom = op->GetSubShape( mainShape, shapeID );
1147         }
1148         if ( !geom->_is_nil() ) {
1149           // try to find the corresponding SObject
1150           GeomObjectToShape( geom ); // geom client remembers the found shape
1151           SALOMEDS::SObject_var SObj = ObjectToSObject( myCurrentStudy, geom.in() );
1152           if ( SObj->_is_nil() )
1153             // publish a new subshape
1154             SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
1155           // return only published geometry
1156           if ( !SObj->_is_nil() )
1157             return geom._retn();
1158         }
1159       }
1160   }
1161   return GEOM::GEOM_Object::_nil();
1162 }
1163
1164 //=============================================================================
1165 /*!
1166  *  SMESH_Gen_i::Save
1167  *
1168  *  Save SMESH module's data
1169  */
1170 //=============================================================================
1171 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
1172                                       const char*              theURL,
1173                                       bool                     isMultiFile )
1174 {
1175   INFOS( "SMESH_Gen_i::Save" );
1176
1177 //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
1178   // san -- in case <myCurrentStudy> differs from theComponent's study,
1179   // use that of the component
1180   if ( myCurrentStudy->_is_nil() || 
1181        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
1182     SetCurrentStudy( theComponent->GetStudy() );
1183
1184   // Store study contents as a set of python commands
1185   SavePython(myCurrentStudy);
1186
1187   StudyContext* myStudyContext = GetCurrentStudyContext();
1188   
1189   // Declare a byte stream
1190   SALOMEDS::TMPFile_var aStreamFile;
1191   
1192   // Obtain a temporary dir
1193   TCollection_AsciiString tmpDir =
1194     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
1195
1196   // Create a sequence of files processed
1197   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
1198   aFileSeq->length( NUM_TMP_FILES );
1199
1200   TCollection_AsciiString aStudyName( "" );
1201   if ( isMultiFile ) 
1202     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
1203
1204   // Set names of temporary files
1205   TCollection_AsciiString filename =
1206     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
1207   TCollection_AsciiString meshfile =
1208     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
1209   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
1210   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
1211   filename = tmpDir + filename;
1212   meshfile = tmpDir + meshfile;
1213
1214   HDFfile*    aFile;
1215   HDFdataset* aDataset;
1216   HDFgroup*   aTopGroup;
1217   HDFgroup*   aGroup;
1218   HDFgroup*   aSubGroup;
1219   HDFgroup*   aSubSubGroup;
1220   hdf_size    aSize[ 1 ];
1221
1222
1223   //Remove the files if they exist: BugID: 11225
1224   TCollection_AsciiString cmd("rm -f \"");
1225   cmd+=filename;
1226   cmd+="\" \"";
1227   cmd+=meshfile;
1228   cmd+="\"";
1229   system(cmd.ToCString());
1230
1231   // MED writer to be used by storage process
1232   DriverMED_W_SMESHDS_Mesh myWriter;
1233   myWriter.SetFile( meshfile.ToCString() );
1234
1235   // Write data
1236   // ---> create HDF file
1237   aFile = new HDFfile( filename.ToCString() );
1238   aFile->CreateOnDisk();
1239
1240   // --> iterator for top-level objects
1241   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
1242   for ( ; itBig->More(); itBig->Next() ) {
1243     SALOMEDS::SObject_var gotBranch = itBig->Value();
1244
1245     // --> hypotheses root branch (only one for the study)
1246     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
1247       // create hypotheses root HDF group
1248       aTopGroup = new HDFgroup( "Hypotheses", aFile );
1249       aTopGroup->CreateOnDisk();
1250
1251       // iterator for all hypotheses
1252       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
1253       for ( ; it->More(); it->Next() ) {
1254         SALOMEDS::SObject_var mySObject = it->Value();
1255         CORBA::Object_var anObject = SObjectToObject( mySObject );
1256         if ( !CORBA::is_nil( anObject ) ) {
1257           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
1258           if ( !myHyp->_is_nil() ) {
1259             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1260             if ( myImpl ) {
1261               string hypname = string( myHyp->GetName() );
1262               string libname = string( myHyp->GetLibName() );
1263               int    id      = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1264               string hypdata = string( myImpl->SaveTo() );
1265
1266               // for each hypothesis create HDF group basing on its id
1267               char hypGrpName[30];
1268               sprintf( hypGrpName, "Hypothesis %d", id );
1269               aGroup = new HDFgroup( hypGrpName, aTopGroup );
1270               aGroup->CreateOnDisk();
1271               // --> type name of hypothesis
1272               aSize[ 0 ] = hypname.length() + 1;
1273               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
1274               aDataset->CreateOnDisk();
1275               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
1276               aDataset->CloseOnDisk();
1277               // --> server plugin library name of hypothesis
1278               aSize[ 0 ] = libname.length() + 1;
1279               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
1280               aDataset->CreateOnDisk();
1281               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
1282               aDataset->CloseOnDisk();
1283               // --> persistent data of hypothesis
1284               aSize[ 0 ] = hypdata.length() + 1;
1285               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
1286               aDataset->CreateOnDisk();
1287               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
1288               aDataset->CloseOnDisk();
1289               // close hypothesis HDF group
1290               aGroup->CloseOnDisk();
1291             }
1292           }
1293         }
1294       }
1295       // close hypotheses root HDF group
1296       aTopGroup->CloseOnDisk();
1297     }
1298     // --> algorithms root branch (only one for the study)
1299     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1300       // create algorithms root HDF group
1301       aTopGroup = new HDFgroup( "Algorithms", aFile );
1302       aTopGroup->CreateOnDisk();
1303
1304       // iterator for all algorithms
1305       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
1306       for ( ; it->More(); it->Next() ) {
1307         SALOMEDS::SObject_var mySObject = it->Value();
1308         CORBA::Object_var anObject = SObjectToObject( mySObject );
1309         if ( !CORBA::is_nil( anObject ) ) {
1310           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
1311           if ( !myHyp->_is_nil() ) {
1312             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1313             if ( myImpl ) {
1314               string hypname = string( myHyp->GetName() );
1315               string libname = string( myHyp->GetLibName() );
1316               int    id      = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1317               string hypdata = string( myImpl->SaveTo() );
1318
1319               // for each algorithm create HDF group basing on its id
1320               char hypGrpName[30];
1321               sprintf( hypGrpName, "Algorithm %d", id );
1322               aGroup = new HDFgroup( hypGrpName, aTopGroup );
1323               aGroup->CreateOnDisk();
1324               // --> type name of algorithm
1325               aSize[0] = hypname.length() + 1;
1326               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
1327               aDataset->CreateOnDisk();
1328               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
1329               aDataset->CloseOnDisk();
1330               // --> server plugin library name of hypothesis
1331               aSize[0] = libname.length() + 1;
1332               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
1333               aDataset->CreateOnDisk();
1334               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
1335               aDataset->CloseOnDisk();
1336               // --> persistent data of algorithm
1337               aSize[0] = hypdata.length() + 1;
1338               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
1339               aDataset->CreateOnDisk();
1340               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
1341               aDataset->CloseOnDisk();
1342               // close algorithm HDF group
1343               aGroup->CloseOnDisk();
1344             }
1345           }
1346         }
1347       }
1348       // close algorithms root HDF group
1349       aTopGroup->CloseOnDisk();
1350     }
1351     // --> mesh objects roots branches
1352     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
1353       CORBA::Object_var anObject = SObjectToObject( gotBranch );
1354       if ( !CORBA::is_nil( anObject ) ) {
1355         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
1356         if ( !myMesh->_is_nil() ) {
1357           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
1358           if ( myImpl ) {
1359             int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1360             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
1361             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
1362
1363             // for each mesh open the HDF group basing on its id
1364             char meshGrpName[ 30 ];
1365             sprintf( meshGrpName, "Mesh %d", id );
1366             aTopGroup = new HDFgroup( meshGrpName, aFile );
1367             aTopGroup->CreateOnDisk();
1368
1369             // --> put dataset to hdf file which is a flag that mesh has data
1370             string strHasData = "0";
1371             // check if the mesh is not empty
1372             if ( mySMESHDSMesh->NbNodes() > 0 ) {
1373               // write mesh data to med file
1374               myWriter.SetMesh( mySMESHDSMesh );
1375               myWriter.SetMeshId( id );
1376               strHasData = "1";
1377             }
1378             aSize[ 0 ] = strHasData.length() + 1;
1379             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
1380             aDataset->CreateOnDisk();
1381             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
1382             aDataset->CloseOnDisk();
1383             
1384             // write reference on a shape if exists
1385             SALOMEDS::SObject_var myRef;
1386             bool shapeRefFound = false;
1387             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
1388             if ( found ) {
1389               SALOMEDS::SObject_var myShape;
1390               bool ok = myRef->ReferencedObject( myShape );
1391               if ( ok ) {
1392                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
1393                 string myRefOnObject = myShape->GetID();
1394                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
1395                   aSize[ 0 ] = myRefOnObject.length() + 1;
1396                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
1397                   aDataset->CreateOnDisk();
1398                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1399                   aDataset->CloseOnDisk();
1400                 }
1401               }
1402             }
1403
1404             // write applied hypotheses if exist
1405             SALOMEDS::SObject_var myHypBranch;
1406             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
1407             if ( found && !shapeRefFound ) { // remove applied hyps
1408               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
1409             }
1410             if ( found && shapeRefFound ) {
1411               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
1412               aGroup->CreateOnDisk();
1413
1414               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
1415               int hypNb = 0;
1416               for ( ; it->More(); it->Next() ) {
1417                 SALOMEDS::SObject_var mySObject = it->Value();
1418                 SALOMEDS::SObject_var myRefOnHyp;
1419                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
1420                 if ( ok ) {
1421                   // san - it is impossible to recover applied hypotheses
1422                   //       using their entries within Load() method,
1423                   // for there are no AttributeIORs in the study when Load() is working. 
1424                   // Hence, it is better to store persistent IDs of hypotheses as references to them
1425
1426                   //string myRefOnObject = myRefOnHyp->GetID();
1427                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
1428                   int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1429                   //if ( myRefOnObject.length() > 0 ) {
1430                   //aSize[ 0 ] = myRefOnObject.length() + 1;
1431                   char hypName[ 30 ], hypId[ 30 ];
1432                   sprintf( hypName, "Hyp %d", ++hypNb );
1433                   sprintf( hypId, "%d", id );
1434                   aSize[ 0 ] = strlen( hypId ) + 1;
1435                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
1436                   aDataset->CreateOnDisk();
1437                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1438                   aDataset->WriteOnDisk( hypId );
1439                   aDataset->CloseOnDisk();
1440                   //}
1441                 }
1442               }
1443               aGroup->CloseOnDisk();
1444             }
1445
1446             // write applied algorithms if exist
1447             SALOMEDS::SObject_var myAlgoBranch;
1448             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
1449             if ( found && !shapeRefFound ) { // remove applied algos
1450               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
1451             }
1452             if ( found && shapeRefFound ) {
1453               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
1454               aGroup->CreateOnDisk();
1455
1456               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
1457               int algoNb = 0;
1458               for ( ; it->More(); it->Next() ) {
1459                 SALOMEDS::SObject_var mySObject = it->Value();
1460                 SALOMEDS::SObject_var myRefOnAlgo;
1461                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
1462                 if ( ok ) {
1463                   // san - it is impossible to recover applied algorithms
1464                   //       using their entries within Load() method,
1465                   // for there are no AttributeIORs in the study when Load() is working. 
1466                   // Hence, it is better to store persistent IDs of algorithms as references to them
1467
1468                   //string myRefOnObject = myRefOnAlgo->GetID();
1469                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
1470                   int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1471                   //if ( myRefOnObject.length() > 0 ) {
1472                   //aSize[ 0 ] = myRefOnObject.length() + 1;
1473                   char algoName[ 30 ], algoId[ 30 ];
1474                   sprintf( algoName, "Algo %d", ++algoNb );
1475                   sprintf( algoId, "%d", id );
1476                   aSize[ 0 ] = strlen( algoId ) + 1;
1477                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
1478                   aDataset->CreateOnDisk();
1479                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1480                   aDataset->WriteOnDisk( algoId );
1481                   aDataset->CloseOnDisk();
1482                   //}
1483                 }
1484               }
1485               aGroup->CloseOnDisk();
1486             }
1487
1488             // --> submesh objects sub-branches
1489
1490             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
1491               SALOMEDS::SObject_var mySubmeshBranch;
1492               found = gotBranch->FindSubObject( i, mySubmeshBranch );
1493
1494               if ( found ) // check if there is shape reference in submeshes
1495               {
1496                 bool hasShapeRef = false;
1497                 SALOMEDS::ChildIterator_var itSM =
1498                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
1499                 for ( ; itSM->More(); itSM->Next() ) {
1500                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
1501                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
1502                     mySubRef->ReferencedObject( myShape );
1503                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
1504                     hasShapeRef = true;
1505                   else
1506                   { // remove one submesh
1507                     if ( shapeRefFound )
1508                     { // unassign hypothesis
1509                       SMESH::SMESH_subMesh_var mySubMesh =
1510                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
1511                       if ( !mySubMesh->_is_nil() ) {
1512                         int shapeID = mySubMesh->GetId();
1513                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
1514                         const list<const SMESHDS_Hypothesis*>& hypList =
1515                           mySMESHDSMesh->GetHypothesis( S );
1516                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
1517                         while ( hyp != hypList.end() ) {
1518                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
1519                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
1520                         }
1521                       }
1522                     }
1523                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
1524                   }
1525                 } // loop on submeshes of a type
1526                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
1527                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
1528                   found = false;
1529                 }
1530               }  // end check if there is shape reference in submeshes
1531               if ( found ) {
1532                 char name_meshgroup[ 30 ];
1533                 if ( i == GetSubMeshOnVertexTag() )
1534                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
1535                 else if ( i == GetSubMeshOnEdgeTag() )
1536                   strcpy( name_meshgroup, "SubMeshes On Edge" );
1537                 else if ( i == GetSubMeshOnWireTag() )
1538                   strcpy( name_meshgroup, "SubMeshes On Wire" );
1539                 else if ( i == GetSubMeshOnFaceTag() )
1540                   strcpy( name_meshgroup, "SubMeshes On Face" );
1541                 else if ( i == GetSubMeshOnShellTag() )
1542                   strcpy( name_meshgroup, "SubMeshes On Shell" );
1543                 else if ( i == GetSubMeshOnSolidTag() )
1544                   strcpy( name_meshgroup, "SubMeshes On Solid" );
1545                 else if ( i == GetSubMeshOnCompoundTag() )
1546                   strcpy( name_meshgroup, "SubMeshes On Compound" );
1547                 
1548                 // for each type of submeshes create container HDF group
1549                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
1550                 aGroup->CreateOnDisk();
1551             
1552                 // iterator for all submeshes of given type
1553                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
1554                 for ( ; itSM->More(); itSM->Next() ) {
1555                   SALOMEDS::SObject_var mySObject = itSM->Value();
1556                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
1557                   if ( !CORBA::is_nil( anSubObject ))
1558                   {
1559                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
1560                     int subid = myStudyContext->findId( string( GetORB()->object_to_string( anSubObject ) ) );
1561                       
1562                     // for each mesh open the HDF group basing on its id
1563                     char submeshGrpName[ 30 ];
1564                     sprintf( submeshGrpName, "SubMesh %d", subid );
1565                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
1566                     aSubGroup->CreateOnDisk();
1567
1568                     // write reference on a shape, already checked if it exists
1569                     SALOMEDS::SObject_var mySubRef, myShape;
1570                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
1571                       mySubRef->ReferencedObject( myShape );
1572                     string myRefOnObject = myShape->GetID();
1573                     if ( myRefOnObject.length() > 0 ) {
1574                       aSize[ 0 ] = myRefOnObject.length() + 1;
1575                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
1576                       aDataset->CreateOnDisk();
1577                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1578                       aDataset->CloseOnDisk();
1579                     }
1580
1581                     // write applied hypotheses if exist
1582                     SALOMEDS::SObject_var mySubHypBranch;
1583                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
1584                     if ( found ) {
1585                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
1586                       aSubSubGroup->CreateOnDisk();
1587
1588                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
1589                       int hypNb = 0;
1590                       for ( ; it->More(); it->Next() ) {
1591                         SALOMEDS::SObject_var mySubSObject = it->Value();
1592                         SALOMEDS::SObject_var myRefOnHyp;
1593                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
1594                         if ( ok ) {
1595                           //string myRefOnObject = myRefOnHyp->GetID();
1596                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
1597                           int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1598                           //if ( myRefOnObject.length() > 0 ) {
1599                           //aSize[ 0 ] = myRefOnObject.length() + 1;
1600                           char hypName[ 30 ], hypId[ 30 ];
1601                           sprintf( hypName, "Hyp %d", ++hypNb );
1602                           sprintf( hypId, "%d", id );
1603                           aSize[ 0 ] = strlen( hypId ) + 1;
1604                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
1605                           aDataset->CreateOnDisk();
1606                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1607                           aDataset->WriteOnDisk( hypId );
1608                           aDataset->CloseOnDisk();
1609                           //}
1610                         }
1611                       }
1612                       aSubSubGroup->CloseOnDisk();
1613                     }
1614                     
1615                     // write applied algorithms if exist
1616                     SALOMEDS::SObject_var mySubAlgoBranch;
1617                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
1618                     if ( found ) {
1619                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
1620                       aSubSubGroup->CreateOnDisk();
1621
1622                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
1623                       int algoNb = 0;
1624                       for ( ; it->More(); it->Next() ) {
1625                         SALOMEDS::SObject_var mySubSObject = it->Value();
1626                         SALOMEDS::SObject_var myRefOnAlgo;
1627                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
1628                         if ( ok ) {
1629                           //string myRefOnObject = myRefOnAlgo->GetID();
1630                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
1631                           int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1632                           //if ( myRefOnObject.length() > 0 ) {
1633                           //aSize[ 0 ] = myRefOnObject.length() + 1;
1634                           char algoName[ 30 ], algoId[ 30 ];
1635                           sprintf( algoName, "Algo %d", ++algoNb );
1636                           sprintf( algoId, "%d", id );
1637                           aSize[ 0 ] = strlen( algoId ) + 1;
1638                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
1639                           aDataset->CreateOnDisk();
1640                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1641                           aDataset->WriteOnDisk( algoId );
1642                           aDataset->CloseOnDisk();
1643                           //}
1644                         }
1645                       }
1646                       aSubSubGroup->CloseOnDisk();
1647                     }
1648                     // close submesh HDF group
1649                     aSubGroup->CloseOnDisk();
1650                   }
1651                 }
1652                 // close container of submeshes by type HDF group
1653                 aGroup->CloseOnDisk();
1654               }
1655             }
1656             // All sub-meshes will be stored in MED file
1657             // .. will NOT (PAL 12992)
1658             //if ( shapeRefFound )
1659             //myWriter.AddAllSubMeshes();
1660
1661             // groups root sub-branch
1662             SALOMEDS::SObject_var myGroupsBranch;
1663             for ( int i = GetNodeGroupsTag(); i <= GetVolumeGroupsTag(); i++ ) {
1664               found = gotBranch->FindSubObject( i, myGroupsBranch );
1665               if ( found ) {
1666                 char name_group[ 30 ];
1667                 if ( i == GetNodeGroupsTag() )
1668                   strcpy( name_group, "Groups of Nodes" );
1669                 else if ( i == GetEdgeGroupsTag() )
1670                   strcpy( name_group, "Groups of Edges" );
1671                 else if ( i == GetFaceGroupsTag() )
1672                   strcpy( name_group, "Groups of Faces" );
1673                 else if ( i == GetVolumeGroupsTag() )
1674                   strcpy( name_group, "Groups of Volumes" );
1675
1676                 aGroup = new HDFgroup( name_group, aTopGroup );
1677                 aGroup->CreateOnDisk();
1678
1679                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
1680                 for ( ; it->More(); it->Next() ) {
1681                   SALOMEDS::SObject_var mySObject = it->Value();
1682                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
1683                   if ( !CORBA::is_nil( aSubObject ) ) {
1684                     SMESH_GroupBase_i* myGroupImpl =
1685                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
1686                     if ( !myGroupImpl )
1687                       continue;
1688
1689                     int anId = myStudyContext->findId( string( GetORB()->object_to_string( aSubObject ) ) );
1690                     
1691                     // For each group, create a dataset named "Group <group_persistent_id>"
1692                     // and store the group's user name into it
1693                     char grpName[ 30 ];
1694                     sprintf( grpName, "Group %d", anId );
1695                     char* aUserName = myGroupImpl->GetName();
1696                     aSize[ 0 ] = strlen( aUserName ) + 1;
1697
1698                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
1699                     aDataset->CreateOnDisk();
1700                     aDataset->WriteOnDisk( aUserName );
1701                     aDataset->CloseOnDisk();
1702
1703                     // Store the group contents into MED file
1704                     if ( myLocMesh.GetGroup( myGroupImpl->GetLocalID() ) ) {
1705
1706                       if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen_i::Save(): saving group with StoreName = "
1707                               << grpName << " to MED file" );
1708                       SMESHDS_GroupBase* aGrpBaseDS =
1709                         myLocMesh.GetGroup( myGroupImpl->GetLocalID() )->GetGroupDS();
1710                       aGrpBaseDS->SetStoreName( grpName );
1711
1712                       // Pass SMESHDS_Group to MED writer 
1713                       SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
1714                       if ( aGrpDS )
1715                         myWriter.AddGroup( aGrpDS );
1716
1717                       // write reference on a shape if exists
1718                       SMESHDS_GroupOnGeom* aGeomGrp =
1719                         dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
1720                       if ( aGeomGrp ) {
1721                         SALOMEDS::SObject_var mySubRef, myShape;
1722                         if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
1723                             mySubRef->ReferencedObject( myShape ) &&
1724                             !CORBA::is_nil( myShape->GetObject() ))
1725                         {
1726                           string myRefOnObject = myShape->GetID();
1727                           if ( myRefOnObject.length() > 0 ) {
1728                             char aRefName[ 30 ];
1729                             sprintf( aRefName, "Ref on shape %d", anId);
1730                             aSize[ 0 ] = myRefOnObject.length() + 1;
1731                             aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
1732                             aDataset->CreateOnDisk();
1733                             aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1734                             aDataset->CloseOnDisk();
1735                           }
1736                         }
1737                         else // shape ref is invalid:
1738                         {
1739                           // save a group on geometry as ordinary group
1740                           myWriter.AddGroup( aGeomGrp );
1741                         }
1742                       }
1743                     }
1744                   }
1745                 }
1746                 aGroup->CloseOnDisk();
1747               }
1748             } // loop on groups 
1749
1750             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
1751             {
1752               // Flush current mesh information into MED file
1753               myWriter.Perform();
1754
1755               // maybe a shape was deleted in the study
1756               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() ) {
1757                 TopoDS_Shape nullShape;
1758                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
1759               }
1760
1761               if ( !mySMESHDSMesh->SubMeshes().empty() )
1762               {
1763                 // Store submeshes
1764                 // ----------------
1765                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
1766                 aGroup->CreateOnDisk();
1767
1768                 // each element belongs to one or none submesh,
1769                 // so for each node/element, we store a submesh ID
1770
1771                 // Make maps of submesh IDs of elements sorted by element IDs
1772                 typedef int TElemID;
1773                 typedef int TSubMID;
1774                 map< TElemID, TSubMID > eId2smId, nId2smId;
1775                 map< TElemID, TSubMID >::iterator hint; // insertion to map is done before hint
1776                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
1777                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
1778                 SMDS_NodeIteratorPtr itNode;
1779                 SMDS_ElemIteratorPtr itElem;
1780                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
1781                 {
1782                   TSubMID          aSubMeID = itSubM->first;
1783                   SMESHDS_SubMesh* aSubMesh = itSubM->second;
1784                   if ( aSubMesh->IsComplexSubmesh() )
1785                     continue; // submesh containing other submeshs
1786                   // nodes
1787                   hint = nId2smId.begin(); // optimize insertion basing on increasing order of elem Ids in submesh
1788                   for ( itNode = aSubMesh->GetNodes(); itNode->more(); ++hint)
1789                     hint = nId2smId.insert( hint, make_pair( itNode->next()->GetID(), aSubMeID ));
1790                   // elements
1791                   hint = eId2smId.begin();
1792                   for ( itElem = aSubMesh->GetElements(); itElem->more(); ++hint)
1793                     hint = eId2smId.insert( hint, make_pair( itElem->next()->GetID(), aSubMeID ));
1794                 }
1795
1796                 // Care of elements that are not on submeshes
1797                 if ( mySMESHDSMesh->NbNodes() != nId2smId.size() ) {
1798                   for ( itNode = mySMESHDSMesh->nodesIterator(); itNode->more(); )
1799                     /*  --- stl_map.h says : */
1800                     /*  A %map relies on unique keys and thus a %pair is only inserted if its */
1801                     /*  first element (the key) is not already present in the %map.           */
1802                     nId2smId.insert( make_pair( itNode->next()->GetID(), 0 ));
1803                 }
1804                 int nbElems = mySMESHDSMesh->NbEdges() + mySMESHDSMesh->NbFaces() + mySMESHDSMesh->NbVolumes();
1805                 if ( nbElems != eId2smId.size() ) {
1806                   for ( itElem = mySMESHDSMesh->elementsIterator(); itElem->more(); )
1807                     eId2smId.insert( make_pair( itElem->next()->GetID(), 0 ));
1808                 }
1809
1810                 // Store submesh IDs
1811                 for ( int isNode = 0; isNode < 2; ++isNode )
1812                 {
1813                   map< TElemID, TSubMID >& id2smId = isNode ? nId2smId : eId2smId;
1814                   if ( id2smId.empty() ) continue;
1815                   map< TElemID, TSubMID >::const_iterator id_smId = id2smId.begin();
1816                   // make and fill array of submesh IDs
1817                   int* smIDs = new int [ id2smId.size() ];
1818                   for ( int i = 0; id_smId != id2smId.end(); ++id_smId, ++i )
1819                     smIDs[ i ] = id_smId->second;
1820                   // write HDF group
1821                   aSize[ 0 ] = id2smId.size();
1822                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
1823                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
1824                   aDataset->CreateOnDisk();
1825                   aDataset->WriteOnDisk( smIDs );
1826                   aDataset->CloseOnDisk();
1827                   //
1828                   delete smIDs;
1829                 }
1830                 
1831                 // Store node positions on sub-shapes (SMDS_Position):
1832                 // ----------------------------------------------------
1833
1834                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
1835                 aGroup->CreateOnDisk();
1836
1837                 // in aGroup, create 5 datasets to contain:
1838                 // "Nodes on Edges" - ID of node on edge
1839                 // "Edge positions" - U parameter on node on edge
1840                 // "Nodes on Faces" - ID of node on face
1841                 // "Face U positions" - U parameter of node on face
1842                 // "Face V positions" - V parameter of node on face
1843
1844                 // Find out nb of nodes on edges and faces
1845                 // Collect corresponing sub-meshes
1846                 int nbEdgeNodes = 0, nbFaceNodes = 0;
1847                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
1848                 // loop on SMESHDS_SubMesh'es
1849                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
1850                 {
1851                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
1852                   if ( aSubMesh->IsComplexSubmesh() )
1853                     continue; // submesh containing other submeshs
1854                   int nbNodes = aSubMesh->NbNodes();
1855                   if ( nbNodes == 0 ) continue;
1856
1857                   int aShapeID = (*itSubM).first;
1858                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
1859                   // write only SMDS_FacePosition and SMDS_EdgePosition
1860                   switch ( aShapeType ) {
1861                   case TopAbs_FACE:
1862                     nbFaceNodes += nbNodes;
1863                     aFaceSM.push_back( aSubMesh );
1864                     break;
1865                   case TopAbs_EDGE:
1866                     nbEdgeNodes += nbNodes;
1867                     aEdgeSM.push_back( aSubMesh );
1868                     break;
1869                   default:
1870                     continue;
1871                   }
1872                 }
1873                 // Treat positions on edges or faces
1874                 for ( int onFace = 0; onFace < 2; onFace++ )
1875                 {
1876                   // Create arrays to store in datasets
1877                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
1878                   if (!nbNodes) continue;
1879                   int* aNodeIDs = new int [ nbNodes ];
1880                   double* aUPos = new double [ nbNodes ];
1881                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
1882
1883                   // Fill arrays
1884                   // loop on sub-meshes
1885                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
1886                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
1887                   for ( ; itSM != pListSM->end(); itSM++ )
1888                   {
1889                     SMESHDS_SubMesh* aSubMesh = (*itSM);
1890
1891                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
1892                     // loop on nodes in aSubMesh
1893                     while ( itNode->more() )
1894                     {
1895                       //node ID
1896                       const SMDS_MeshNode* node = itNode->next();
1897                       aNodeIDs [ iNode ] = node->GetID();
1898
1899                       // Position
1900                       const SMDS_PositionPtr pos = node->GetPosition();
1901                       if ( onFace ) { // on FACE
1902                         const SMDS_FacePosition* fPos =
1903                           dynamic_cast<const SMDS_FacePosition*>( pos.get() );
1904                         if ( fPos ) {
1905                           aUPos[ iNode ] = fPos->GetUParameter();
1906                           aVPos[ iNode ] = fPos->GetVParameter();
1907                           iNode++;
1908                         }
1909                         else
1910                           nbNodes--;
1911                       }
1912                       else { // on EDGE
1913                         const SMDS_EdgePosition* ePos =
1914                           dynamic_cast<const SMDS_EdgePosition*>( pos.get() );
1915                         if ( ePos ) {
1916                           aUPos[ iNode ] = ePos->GetUParameter();
1917                           iNode++;
1918                         }
1919                         else
1920                           nbNodes--;
1921                       }
1922                     } // loop on nodes in aSubMesh
1923                   } // loop on sub-meshes
1924
1925                   // Write datasets
1926                   if ( nbNodes )
1927                   {
1928                     aSize[ 0 ] = nbNodes;
1929                     // IDS
1930                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
1931                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
1932                     aDataset->CreateOnDisk();
1933                     aDataset->WriteOnDisk( aNodeIDs );
1934                     aDataset->CloseOnDisk();
1935
1936                     // U Positions
1937                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
1938                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
1939                     aDataset->CreateOnDisk();
1940                     aDataset->WriteOnDisk( aUPos );
1941                     aDataset->CloseOnDisk();
1942                     // V Positions
1943                     if ( onFace ) {
1944                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
1945                       aDataset->CreateOnDisk();
1946                       aDataset->WriteOnDisk( aVPos );
1947                       aDataset->CloseOnDisk();
1948                     }
1949                   }
1950                   delete [] aNodeIDs;
1951                   delete [] aUPos;
1952                   if ( aVPos ) delete [] aVPos;
1953
1954                 } // treat positions on edges or faces
1955
1956                 // close "Node Positions" group
1957                 aGroup->CloseOnDisk(); 
1958
1959               } // if ( there are submeshes in SMESHDS_Mesh )
1960             } // if ( hasData )
1961
1962             // close mesh HDF group
1963             aTopGroup->CloseOnDisk();
1964           }
1965         }
1966       }
1967     }
1968   }
1969
1970   // close HDF file
1971   aFile->CloseOnDisk();
1972   delete aFile;
1973
1974   // Convert temporary files to stream
1975   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
1976
1977   // Remove temporary files and directory
1978   if ( !isMultiFile ) 
1979     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
1980
1981   INFOS( "SMESH_Gen_i::Save() completed" );
1982   return aStreamFile._retn();
1983 }
1984
1985 //=============================================================================
1986 /*!
1987  *  SMESH_Gen_i::SaveASCII
1988  *
1989  *  Save SMESH module's data in ASCII format (not implemented yet)
1990  */
1991 //=============================================================================
1992
1993 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
1994                                            const char*              theURL,
1995                                            bool                     isMultiFile ) {
1996   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
1997   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
1998   return aStreamFile._retn();
1999 }
2000
2001 //=============================================================================
2002 /*!
2003  *  SMESH_Gen_i::loadGeomData
2004  *
2005  *  Load GEOM module data
2006  */
2007 //=============================================================================
2008
2009 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
2010 {
2011   if ( theCompRoot->_is_nil() )
2012     return;
2013
2014   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
2015   if ( aStudy->_is_nil() )
2016     return;
2017
2018   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder(); 
2019   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
2020 }
2021 //=============================================================================
2022 /*!
2023  * \brief Creates SMDS_Position according to shape type
2024  */
2025 //=============================================================================
2026
2027 class PositionCreator {
2028 public:
2029   SMDS_PositionPtr MakePosition(const TopAbs_ShapeEnum type) {
2030     return (this->*myFuncTable[ type ])();
2031   }
2032   PositionCreator() {
2033     myFuncTable.resize( (size_t) TopAbs_SHAPE, & PositionCreator::defaultPosition );
2034     myFuncTable[ TopAbs_FACE ] = & PositionCreator::facePosition;
2035     myFuncTable[ TopAbs_EDGE ] = & PositionCreator::edgePosition;
2036     myFuncTable[ TopAbs_VERTEX ] = & PositionCreator::vertexPosition;
2037   }
2038 private:
2039   SMDS_PositionPtr edgePosition()    const { return SMDS_PositionPtr( new SMDS_EdgePosition  ); }
2040   SMDS_PositionPtr facePosition()    const { return SMDS_PositionPtr( new SMDS_FacePosition  ); }
2041   SMDS_PositionPtr vertexPosition()  const { return SMDS_PositionPtr( new SMDS_VertexPosition); }
2042   SMDS_PositionPtr defaultPosition() const { return SMDS_SpacePosition::originSpacePosition();  }
2043   typedef SMDS_PositionPtr (PositionCreator:: * FmakePos)() const;
2044   vector<FmakePos> myFuncTable;
2045 };
2046
2047 //=============================================================================
2048 /*!
2049  *  SMESH_Gen_i::Load
2050  *
2051  *  Load SMESH module's data
2052  */
2053 //=============================================================================
2054
2055 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
2056                         const SALOMEDS::TMPFile& theStream,
2057                         const char*              theURL,
2058                         bool                     isMultiFile )
2059 {
2060   INFOS( "SMESH_Gen_i::Load" );
2061
2062   if ( myCurrentStudy->_is_nil() || 
2063        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
2064     SetCurrentStudy( theComponent->GetStudy() );
2065
2066 /*  if( !theComponent->_is_nil() )
2067   {
2068     //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
2069     if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
2070       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
2071   }*/
2072
2073   StudyContext* myStudyContext = GetCurrentStudyContext();
2074   
2075   // Get temporary files location
2076   TCollection_AsciiString tmpDir =
2077     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2078
2079   // Convert the stream into sequence of files to process
2080   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
2081                                                                             tmpDir.ToCString(),
2082                                                                             isMultiFile );
2083   TCollection_AsciiString aStudyName( "" );
2084   if ( isMultiFile ) 
2085     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2086
2087   // Set names of temporary files
2088   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
2089   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
2090
2091   int size;
2092   HDFfile*    aFile;
2093   HDFdataset* aDataset;
2094   HDFgroup*   aTopGroup;
2095   HDFgroup*   aGroup;
2096   HDFgroup*   aSubGroup;
2097   HDFgroup*   aSubSubGroup;
2098
2099   // Read data
2100   // ---> open HDF file
2101   aFile = new HDFfile( filename.ToCString() );
2102   try {
2103     aFile->OpenOnDisk( HDF_RDONLY );
2104   }
2105   catch ( HDFexception ) {
2106     INFOS( "Load(): " << filename << " not found!" );
2107     return false;
2108   }
2109
2110   DriverMED_R_SMESHDS_Mesh myReader;
2111   myReader.SetFile( meshfile.ToCString() );
2112
2113   // get total number of top-level groups
2114   int aNbGroups = aFile->nInternalObjects(); 
2115   if ( aNbGroups > 0 ) {
2116     // --> in first turn we should read&create hypotheses
2117     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
2118       // open hypotheses root HDF group
2119       aTopGroup = new HDFgroup( "Hypotheses", aFile ); 
2120       aTopGroup->OpenOnDisk();
2121
2122       // get number of hypotheses
2123       int aNbObjects = aTopGroup->nInternalObjects(); 
2124       for ( int j = 0; j < aNbObjects; j++ ) {
2125         // try to identify hypothesis
2126         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
2127         aTopGroup->InternalObjectIndentify( j, hypGrpName );
2128
2129         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
2130           // open hypothesis group
2131           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
2132           aGroup->OpenOnDisk();
2133
2134           // --> get hypothesis id
2135           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
2136           string hypname;
2137           string libname;
2138           string hypdata;
2139
2140           // get number of datasets
2141           int aNbSubObjects = aGroup->nInternalObjects();
2142           for ( int k = 0; k < aNbSubObjects; k++ ) {
2143             // identify dataset
2144             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
2145             aGroup->InternalObjectIndentify( k, name_of_subgroup );
2146             // --> get hypothesis name
2147             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
2148               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2149               aDataset->OpenOnDisk();
2150               size = aDataset->GetSize();
2151               char* hypname_str = new char[ size ];
2152               aDataset->ReadFromDisk( hypname_str );
2153               hypname = string( hypname_str );
2154               delete [] hypname_str;
2155               aDataset->CloseOnDisk();
2156             }
2157             // --> get hypothesis plugin library name
2158             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
2159               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2160               aDataset->OpenOnDisk();
2161               size = aDataset->GetSize();
2162               char* libname_str = new char[ size ];
2163               aDataset->ReadFromDisk( libname_str );
2164               if(MYDEBUG) SCRUTE( libname_str );
2165               libname = string( libname_str );
2166               delete [] libname_str;
2167               aDataset->CloseOnDisk();
2168             }
2169             // --> get hypothesis data
2170             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
2171               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2172               aDataset->OpenOnDisk();
2173               size = aDataset->GetSize();
2174               char* hypdata_str = new char[ size ];
2175               aDataset->ReadFromDisk( hypdata_str );
2176               hypdata = string( hypdata_str );
2177               delete [] hypdata_str;
2178               aDataset->CloseOnDisk();
2179             }
2180           }
2181           // close hypothesis HDF group
2182           aGroup->CloseOnDisk();
2183
2184           // --> restore hypothesis from data
2185           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
2186             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
2187                     ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
2188             SMESH::SMESH_Hypothesis_var myHyp;
2189             
2190             try { // protect persistence mechanism against exceptions
2191               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
2192             }
2193             catch (...) {
2194               INFOS( "Exception during hypothesis creation" );
2195             }
2196
2197             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2198             if ( myImpl ) {
2199               myImpl->LoadFrom( hypdata.c_str() );
2200               string iorString = GetORB()->object_to_string( myHyp );
2201               int newId = myStudyContext->findId( iorString );
2202               myStudyContext->mapOldToNew( id, newId );
2203             }
2204             else
2205               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
2206           }
2207         }
2208       }
2209       // close hypotheses root HDF group
2210       aTopGroup->CloseOnDisk();
2211     }
2212
2213     // --> then we should read&create algorithms
2214     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
2215       // open algorithms root HDF group
2216       aTopGroup = new HDFgroup( "Algorithms", aFile ); 
2217       aTopGroup->OpenOnDisk();
2218
2219       // get number of algorithms
2220       int aNbObjects = aTopGroup->nInternalObjects(); 
2221       for ( int j = 0; j < aNbObjects; j++ ) {
2222         // try to identify algorithm
2223         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
2224         aTopGroup->InternalObjectIndentify( j, hypGrpName );
2225
2226         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
2227           // open algorithm group
2228           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
2229           aGroup->OpenOnDisk();
2230
2231           // --> get algorithm id
2232           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
2233           string hypname;
2234           string libname;
2235           string hypdata;
2236
2237           // get number of datasets
2238           int aNbSubObjects = aGroup->nInternalObjects();
2239           for ( int k = 0; k < aNbSubObjects; k++ ) {
2240             // identify dataset
2241             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
2242             aGroup->InternalObjectIndentify( k, name_of_subgroup );
2243             // --> get algorithm name
2244             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
2245               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2246               aDataset->OpenOnDisk();
2247               size = aDataset->GetSize();
2248               char* hypname_str = new char[ size ];
2249               aDataset->ReadFromDisk( hypname_str );
2250               hypname = string( hypname_str );
2251               delete [] hypname_str;
2252               aDataset->CloseOnDisk();
2253             }
2254             // --> get algorithm plugin library name
2255             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
2256               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2257               aDataset->OpenOnDisk();
2258               size = aDataset->GetSize();
2259               char* libname_str = new char[ size ];
2260               aDataset->ReadFromDisk( libname_str );
2261               if(MYDEBUG) SCRUTE( libname_str );
2262               libname = string( libname_str );
2263               delete [] libname_str;
2264               aDataset->CloseOnDisk();
2265             }
2266             // --> get algorithm data
2267             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
2268               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2269               aDataset->OpenOnDisk();
2270               size = aDataset->GetSize();
2271               char* hypdata_str = new char[ size ];
2272               aDataset->ReadFromDisk( hypdata_str );
2273               if(MYDEBUG) SCRUTE( hypdata_str );
2274               hypdata = string( hypdata_str );
2275               delete [] hypdata_str;
2276               aDataset->CloseOnDisk();
2277             }
2278           }
2279           // close algorithm HDF group
2280           aGroup->CloseOnDisk();
2281           
2282           // --> restore algorithm from data
2283           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
2284             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
2285                     ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
2286             SMESH::SMESH_Hypothesis_var myHyp;
2287                     
2288             try { // protect persistence mechanism against exceptions
2289               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
2290             }
2291             catch (...) {
2292               INFOS( "Exception during hypothesis creation" );
2293             }
2294             
2295             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2296             if ( myImpl ) {
2297               myImpl->LoadFrom( hypdata.c_str() );
2298               string iorString = GetORB()->object_to_string( myHyp );
2299               int newId = myStudyContext->findId( iorString );
2300               myStudyContext->mapOldToNew( id, newId );
2301             }
2302             else
2303               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
2304           }
2305         }
2306       }
2307       // close algorithms root HDF group
2308       aTopGroup->CloseOnDisk();
2309     }
2310
2311     // --> the rest groups should be meshes
2312     for ( int i = 0; i < aNbGroups; i++ ) {
2313       // identify next group
2314       char meshName[ HDF_NAME_MAX_LEN+1 ];
2315       aFile->InternalObjectIndentify( i, meshName );
2316
2317       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
2318         // --> get mesh id
2319         int id = atoi( string( meshName ).substr( 4 ).c_str() );
2320         if ( id <= 0 )
2321           continue;
2322
2323         bool hasData = false;
2324
2325         // open mesh HDF group
2326         aTopGroup = new HDFgroup( meshName, aFile ); 
2327         aTopGroup->OpenOnDisk();
2328
2329         // get number of child HDF objects
2330         int aNbObjects = aTopGroup->nInternalObjects(); 
2331         if ( aNbObjects > 0 ) {
2332           // create mesh
2333           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
2334           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
2335           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
2336           if ( !myNewMeshImpl )
2337             continue;
2338           string iorString = GetORB()->object_to_string( myNewMesh );
2339           int newId = myStudyContext->findId( iorString );
2340           myStudyContext->mapOldToNew( id, newId );
2341           
2342           ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
2343           SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
2344
2345           // try to find mesh data dataset
2346           if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
2347             // load mesh "has data" flag
2348             aDataset = new HDFdataset( "Has data", aTopGroup );
2349             aDataset->OpenOnDisk();
2350             size = aDataset->GetSize();
2351             char* strHasData = new char[ size ];
2352             aDataset->ReadFromDisk( strHasData );
2353             aDataset->CloseOnDisk();
2354             if ( strcmp( strHasData, "1") == 0 ) {
2355               // read mesh data from MED file
2356               myReader.SetMesh( mySMESHDSMesh );
2357               myReader.SetMeshId( id );
2358               myReader.Perform();
2359               hasData = true;
2360             }
2361           }
2362
2363           // try to read and set reference to shape
2364           GEOM::GEOM_Object_var aShapeObject;
2365           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
2366             // load mesh "Ref on shape" - it's an entry to SObject
2367             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
2368             aDataset->OpenOnDisk();
2369             size = aDataset->GetSize();
2370             char* refFromFile = new char[ size ];
2371             aDataset->ReadFromDisk( refFromFile );
2372             aDataset->CloseOnDisk();
2373             if ( strlen( refFromFile ) > 0 ) {
2374               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
2375
2376               // Make sure GEOM data are loaded first
2377               //loadGeomData( shapeSO->GetFatherComponent() );
2378
2379               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
2380               if ( !CORBA::is_nil( shapeObject ) ) {
2381                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
2382                 if ( !aShapeObject->_is_nil() )
2383                   myNewMeshImpl->SetShape( aShapeObject );
2384               }
2385             }
2386           }
2387
2388           // try to get applied algorithms
2389           if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
2390             aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
2391             aGroup->OpenOnDisk();
2392             // get number of applied algorithms
2393             int aNbSubObjects = aGroup->nInternalObjects(); 
2394             if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
2395             for ( int j = 0; j < aNbSubObjects; j++ ) {
2396               char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2397               aGroup->InternalObjectIndentify( j, name_dataset );
2398               // check if it is an algorithm
2399               if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
2400                 aDataset = new HDFdataset( name_dataset, aGroup );
2401                 aDataset->OpenOnDisk();
2402                 size = aDataset->GetSize();
2403                 char* refFromFile = new char[ size ];
2404                 aDataset->ReadFromDisk( refFromFile );
2405                 aDataset->CloseOnDisk();
2406
2407                 // san - it is impossible to recover applied algorithms using their entries within Load() method
2408                 
2409                 //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2410                 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2411                 int id = atoi( refFromFile );
2412                 string anIOR = myStudyContext->getIORbyOldId( id );
2413                 if ( !anIOR.empty() ) {
2414                   CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2415                   if ( !CORBA::is_nil( hypObject ) ) {
2416                     SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2417                     if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2418                       myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
2419                   }
2420                 }
2421               }
2422             }
2423             aGroup->CloseOnDisk();
2424           }
2425
2426           // try to get applied hypotheses
2427           if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
2428             aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
2429             aGroup->OpenOnDisk();
2430             // get number of applied hypotheses
2431             int aNbSubObjects = aGroup->nInternalObjects(); 
2432             for ( int j = 0; j < aNbSubObjects; j++ ) {
2433               char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2434               aGroup->InternalObjectIndentify( j, name_dataset );
2435               // check if it is a hypothesis
2436               if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
2437                 aDataset = new HDFdataset( name_dataset, aGroup );
2438                 aDataset->OpenOnDisk();
2439                 size = aDataset->GetSize();
2440                 char* refFromFile = new char[ size ];
2441                 aDataset->ReadFromDisk( refFromFile );
2442                 aDataset->CloseOnDisk();
2443
2444                 // san - it is impossible to recover applied hypotheses using their entries within Load() method
2445                 
2446                 //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2447                 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2448                 int id = atoi( refFromFile );
2449                 string anIOR = myStudyContext->getIORbyOldId( id );
2450                 if ( !anIOR.empty() ) {
2451                   CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2452                   if ( !CORBA::is_nil( hypObject ) ) {
2453                     SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2454                     if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2455                       myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
2456                   }
2457                 }
2458               }
2459             }
2460             aGroup->CloseOnDisk();
2461           }
2462
2463           // --> try to find submeshes containers for each type of submesh
2464           for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
2465             char name_meshgroup[ 30 ];
2466             if ( j == GetSubMeshOnVertexTag() )
2467               strcpy( name_meshgroup, "SubMeshes On Vertex" );
2468             else if ( j == GetSubMeshOnEdgeTag() )
2469               strcpy( name_meshgroup, "SubMeshes On Edge" );
2470             else if ( j == GetSubMeshOnWireTag() )
2471               strcpy( name_meshgroup, "SubMeshes On Wire" );
2472             else if ( j == GetSubMeshOnFaceTag() )
2473               strcpy( name_meshgroup, "SubMeshes On Face" );
2474             else if ( j == GetSubMeshOnShellTag() )
2475               strcpy( name_meshgroup, "SubMeshes On Shell" );
2476             else if ( j == GetSubMeshOnSolidTag() )
2477               strcpy( name_meshgroup, "SubMeshes On Solid" );
2478             else if ( j == GetSubMeshOnCompoundTag() )
2479               strcpy( name_meshgroup, "SubMeshes On Compound" );
2480             
2481             // try to get submeshes container HDF group
2482             if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
2483               // open submeshes containers HDF group
2484               aGroup = new HDFgroup( name_meshgroup, aTopGroup );
2485               aGroup->OpenOnDisk();
2486               
2487               // get number of submeshes
2488               int aNbSubMeshes = aGroup->nInternalObjects(); 
2489               for ( int k = 0; k < aNbSubMeshes; k++ ) {
2490                 // identify submesh
2491                 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
2492                 aGroup->InternalObjectIndentify( k, name_submeshgroup );
2493                 if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
2494                   // --> get submesh id
2495                   int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
2496                   if ( subid <= 0 )
2497                     continue;
2498                   // open submesh HDF group
2499                   aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
2500                   aSubGroup->OpenOnDisk();
2501                   
2502                   // try to read and set reference to subshape
2503                   GEOM::GEOM_Object_var aSubShapeObject;
2504                   SMESH::SMESH_subMesh_var aSubMesh;
2505
2506                   if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
2507                     // load submesh "Ref on shape" - it's an entry to SObject
2508                     aDataset = new HDFdataset( "Ref on shape", aSubGroup );
2509                     aDataset->OpenOnDisk();
2510                     size = aDataset->GetSize();
2511                     char* refFromFile = new char[ size ];
2512                     aDataset->ReadFromDisk( refFromFile );
2513                     aDataset->CloseOnDisk();
2514                     if ( strlen( refFromFile ) > 0 ) {
2515                       SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
2516                       CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
2517                       if ( !CORBA::is_nil( subShapeObject ) ) {
2518                         aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
2519                         if ( !aSubShapeObject->_is_nil() )
2520                           aSubMesh = SMESH::SMESH_subMesh::_duplicate
2521                             ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
2522                         if ( aSubMesh->_is_nil() )
2523                           continue;
2524                         string iorSubString = GetORB()->object_to_string( aSubMesh );
2525                         int newSubId = myStudyContext->findId( iorSubString );
2526                         myStudyContext->mapOldToNew( subid, newSubId );
2527                       }
2528                     }
2529                   }
2530                   
2531                   if ( aSubMesh->_is_nil() )
2532                     continue;
2533
2534                   // VSR: Get submesh data from MED convertor
2535 //                int anInternalSubmeshId = aSubMesh->GetId(); // this is not a persistent ID, it's an internal one computed from sub-shape
2536 //                if (myNewMeshImpl->_mapSubMesh.find(anInternalSubmeshId) != myNewMeshImpl->_mapSubMesh.end()) {
2537 //                  if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): loading from MED file submesh with ID = " <<
2538 //                            subid << " for subshape # " << anInternalSubmeshId);
2539 //                  SMESHDS_SubMesh* aSubMeshDS =
2540 //                      myNewMeshImpl->_mapSubMesh[anInternalSubmeshId]->CreateSubMeshDS();
2541 //                  if ( !aSubMeshDS ) {
2542 //                    if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): FAILED to create a submesh for subshape # " <<
2543 //                              anInternalSubmeshId << " in current mesh!");
2544 //                  }
2545 //                  else
2546 //                    myReader.GetSubMesh( aSubMeshDS, subid );
2547 //                }
2548                     
2549                   // try to get applied algorithms
2550                   if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
2551                     // open "applied algorithms" HDF group
2552                     aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
2553                     aSubSubGroup->OpenOnDisk();
2554                     // get number of applied algorithms
2555                     int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
2556                     for ( int l = 0; l < aNbSubObjects; l++ ) {
2557                       char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2558                       aSubSubGroup->InternalObjectIndentify( l, name_dataset );
2559                       // check if it is an algorithm
2560                       if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
2561                         aDataset = new HDFdataset( name_dataset, aSubSubGroup );
2562                         aDataset->OpenOnDisk();
2563                         size = aDataset->GetSize();
2564                         char* refFromFile = new char[ size ];
2565                         aDataset->ReadFromDisk( refFromFile );
2566                         aDataset->CloseOnDisk();
2567
2568                         //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2569                         //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2570                         int id = atoi( refFromFile );
2571                         string anIOR = myStudyContext->getIORbyOldId( id );
2572                         if ( !anIOR.empty() ) {
2573                           CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2574                           if ( !CORBA::is_nil( hypObject ) ) {
2575                             SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2576                             if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2577                               myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
2578                           }
2579                         }
2580                       }
2581                     }
2582                     // close "applied algorithms" HDF group
2583                     aSubSubGroup->CloseOnDisk();
2584                   }
2585                   
2586                   // try to get applied hypotheses
2587                   if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
2588                     // open "applied hypotheses" HDF group
2589                     aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
2590                     aSubSubGroup->OpenOnDisk();
2591                     // get number of applied hypotheses
2592                     int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
2593                     for ( int l = 0; l < aNbSubObjects; l++ ) {
2594                       char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2595                       aSubSubGroup->InternalObjectIndentify( l, name_dataset );
2596                       // check if it is a hypothesis
2597                       if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
2598                         aDataset = new HDFdataset( name_dataset, aSubSubGroup );
2599                         aDataset->OpenOnDisk();
2600                         size = aDataset->GetSize();
2601                         char* refFromFile = new char[ size ];
2602                         aDataset->ReadFromDisk( refFromFile );
2603                         aDataset->CloseOnDisk();
2604                         
2605                         //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2606                         //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2607                         int id = atoi( refFromFile );
2608                         string anIOR = myStudyContext->getIORbyOldId( id );
2609                         if ( !anIOR.empty() ) {
2610                           CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2611                           if ( !CORBA::is_nil( hypObject ) ) {
2612                             SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2613                             if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2614                               myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
2615                           }
2616                         }
2617                       }
2618                     }
2619                     // close "applied hypotheses" HDF group
2620                     aSubSubGroup->CloseOnDisk();
2621                   }
2622
2623                   // close submesh HDF group
2624                   aSubGroup->CloseOnDisk();
2625                 }
2626               }
2627               // close submeshes containers HDF group
2628               aGroup->CloseOnDisk();
2629             }
2630           }
2631
2632           if(hasData) {
2633             
2634             // Read sub-meshes from MED
2635             // -------------------------
2636             if(MYDEBUG) MESSAGE("Create all sub-meshes");
2637             bool submeshesInFamilies = ( ! aTopGroup->ExistInternalObject( "Submeshes" ));
2638             if ( submeshesInFamilies )
2639             {
2640               // old way working before fix of PAL 12992
2641               myReader.CreateAllSubMeshes();
2642             }
2643             else
2644             {
2645               // open a group
2646               aGroup = new HDFgroup( "Submeshes", aTopGroup ); 
2647               aGroup->OpenOnDisk();
2648
2649               int maxID = mySMESHDSMesh->MaxShapeIndex();
2650               vector< SMESHDS_SubMesh * > subMeshes( maxID + 1, (SMESHDS_SubMesh*) 0 );
2651               vector< TopAbs_ShapeEnum  > smType   ( maxID + 1, TopAbs_SHAPE ); 
2652               
2653               PositionCreator aPositionCreator;
2654
2655               SMDS_NodeIteratorPtr nIt = mySMESHDSMesh->nodesIterator();
2656               SMDS_ElemIteratorPtr eIt = mySMESHDSMesh->elementsIterator();
2657               for ( int isNode = 0; isNode < 2; ++isNode )
2658               {
2659                 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
2660                 if ( aGroup->ExistInternalObject( (char*) aDSName.c_str() ))
2661                 {
2662                   aDataset = new HDFdataset( (char*) aDSName.c_str(), aGroup );
2663                   aDataset->OpenOnDisk();
2664                   // read submesh IDs for all elements sorted by ID
2665                   int nbElems = aDataset->GetSize();
2666                   int* smIDs = new int [ nbElems ];
2667                   aDataset->ReadFromDisk( smIDs );
2668                   aDataset->CloseOnDisk();
2669
2670                   // get elements sorted by ID
2671                   ::SMESH_MeshEditor::TIDSortedElemSet elemSet;
2672                   if ( isNode )
2673                     while ( nIt->more() ) elemSet.insert( nIt->next() );
2674                   else
2675                     while ( eIt->more() ) elemSet.insert( eIt->next() );
2676                   ASSERT( elemSet.size() == nbElems );
2677
2678                   // add elements to submeshes
2679                   ::SMESH_MeshEditor::TIDSortedElemSet::iterator iE = elemSet.begin();
2680                   for ( int i = 0; i < nbElems; ++i, ++iE )
2681                   {
2682                     int smID = smIDs[ i ];
2683                     if ( smID == 0 ) continue;
2684                     ASSERT( smID <= maxID );
2685                     const SMDS_MeshElement* elem = *iE;
2686                     // get or create submesh
2687                     SMESHDS_SubMesh* & sm = subMeshes[ smID ];
2688                     if ( ! sm ) {
2689                       sm = mySMESHDSMesh->NewSubMesh( smID );
2690                       smType[ smID ] = mySMESHDSMesh->IndexToShape( smID ).ShapeType();
2691                     }
2692                     // add
2693                     if ( isNode ) {
2694                       SMDS_PositionPtr pos = aPositionCreator.MakePosition( smType[ smID ]);
2695                       pos->SetShapeId( smID );
2696                       SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>( static_cast<const SMDS_MeshNode*>( elem ));
2697                       node->SetPosition( pos );
2698                       sm->AddNode( node );
2699                     } else {
2700                       sm->AddElement( elem );
2701                     }
2702                   }
2703                   delete smIDs;
2704                 }
2705               }
2706             } // end reading submeshes
2707
2708             // Read node positions on sub-shapes (SMDS_Position)
2709
2710             if ( aTopGroup->ExistInternalObject( "Node Positions" ))
2711             {
2712               // There are 5 datasets to read:
2713               // "Nodes on Edges" - ID of node on edge
2714               // "Edge positions" - U parameter on node on edge
2715               // "Nodes on Faces" - ID of node on face
2716               // "Face U positions" - U parameter of node on face
2717               // "Face V positions" - V parameter of node on face
2718               char* aEid_DSName = "Nodes on Edges";
2719               char* aEu_DSName  = "Edge positions";
2720               char* aFu_DSName  = "Face U positions";
2721               //char* aFid_DSName = "Nodes on Faces";
2722               //char* aFv_DSName  = "Face V positions";
2723
2724               // data to retrieve
2725               int nbEids = 0, nbFids = 0;
2726               int *aEids = 0, *aFids  = 0;
2727               double *aEpos = 0, *aFupos = 0, *aFvpos = 0;
2728
2729               // open a group
2730               aGroup = new HDFgroup( "Node Positions", aTopGroup ); 
2731               aGroup->OpenOnDisk();
2732
2733               // loop on 5 data sets
2734               int aNbObjects = aGroup->nInternalObjects();
2735               for ( int i = 0; i < aNbObjects; i++ )
2736               {
2737                 // identify dataset
2738                 char aDSName[ HDF_NAME_MAX_LEN+1 ];
2739                 aGroup->InternalObjectIndentify( i, aDSName );
2740                 // read data
2741                 aDataset = new HDFdataset( aDSName, aGroup );
2742                 aDataset->OpenOnDisk();
2743                 if ( aDataset->GetType() == HDF_FLOAT64 ) // Positions
2744                 {
2745                   double* pos = new double [ aDataset->GetSize() ];
2746                   aDataset->ReadFromDisk( pos );
2747                   // which one?
2748                   if ( strncmp( aDSName, aEu_DSName, strlen( aEu_DSName )) == 0 )
2749                     aEpos = pos;
2750                   else if ( strncmp( aDSName, aFu_DSName, strlen( aFu_DSName )) == 0 )
2751                     aFupos = pos;
2752                   else
2753                     aFvpos = pos;
2754                 }
2755                 else // NODE IDS
2756                 {
2757                   int aSize = aDataset->GetSize();
2758
2759                   // for reading files, created from 18.07.2005 till 10.10.2005
2760                   if (aDataset->GetType() == HDF_STRING)
2761                     aSize /= sizeof(int);
2762
2763                   int* ids = new int [aSize];
2764                   aDataset->ReadFromDisk( ids );
2765                   // on face or nodes?
2766                   if ( strncmp( aDSName, aEid_DSName, strlen( aEid_DSName )) == 0 ) {
2767                     aEids = ids;
2768                     nbEids = aSize;
2769                   }
2770                   else {
2771                     aFids = ids;
2772                     nbFids = aSize;
2773                   }
2774                 }
2775                 aDataset->CloseOnDisk();
2776               } // loop on 5 datasets
2777
2778               // Set node positions on edges or faces
2779               for ( int onFace = 0; onFace < 2; onFace++ )
2780               {
2781                 int nbNodes = ( onFace ? nbFids : nbEids );
2782                 if ( nbNodes == 0 ) continue;
2783                 int* aNodeIDs = ( onFace ? aFids : aEids );
2784                 double* aUPos = ( onFace ? aFupos : aEpos );
2785                 double* aVPos = ( onFace ? aFvpos : 0 );
2786                 // loop on node IDs
2787                 for ( int iNode = 0; iNode < nbNodes; iNode++ )
2788                 {
2789                   const SMDS_MeshNode* node = mySMESHDSMesh->FindNode( aNodeIDs[ iNode ]);
2790                   ASSERT( node );
2791                   SMDS_PositionPtr aPos = node->GetPosition();
2792                   ASSERT( aPos )
2793                   if ( onFace ) {
2794                     ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_FACE );
2795                     SMDS_FacePosition* fPos = const_cast<SMDS_FacePosition*>
2796                       ( static_cast<const SMDS_FacePosition*>( aPos.get() ));
2797                     fPos->SetUParameter( aUPos[ iNode ]);
2798                     fPos->SetVParameter( aVPos[ iNode ]);
2799                   }
2800                   else {
2801                     ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE );
2802                     SMDS_EdgePosition* fPos = const_cast<SMDS_EdgePosition*>
2803                       ( static_cast<const SMDS_EdgePosition*>( aPos.get() ));
2804                     fPos->SetUParameter( aUPos[ iNode ]);
2805                   }
2806                 }
2807               }
2808               if ( aEids ) delete [] aEids;
2809               if ( aFids ) delete [] aFids;
2810               if ( aEpos ) delete [] aEpos;
2811               if ( aFupos ) delete [] aFupos;
2812               if ( aFvpos ) delete [] aFvpos;
2813               
2814               aGroup->CloseOnDisk();
2815
2816             } // if ( aTopGroup->ExistInternalObject( "Node Positions" ) )
2817           } // if ( hasData )
2818
2819           // Recompute State (as computed sub-meshes are restored from MED)
2820           if ( !aShapeObject->_is_nil() ) {
2821             MESSAGE("Compute State Engine ...");
2822             TopoDS_Shape myLocShape = GeomObjectToShape( aShapeObject );
2823             myNewMeshImpl->GetImpl().GetSubMesh(myLocShape)->ComputeStateEngine
2824               (SMESH_subMesh::SUBMESH_RESTORED);
2825             MESSAGE("Compute State Engine finished");
2826           }
2827
2828           // try to get groups
2829           for ( int ii = GetNodeGroupsTag(); ii <= GetVolumeGroupsTag(); ii++ ) {
2830             char name_group[ 30 ];
2831             if ( ii == GetNodeGroupsTag() )
2832               strcpy( name_group, "Groups of Nodes" );
2833             else if ( ii == GetEdgeGroupsTag() )
2834               strcpy( name_group, "Groups of Edges" );
2835             else if ( ii == GetFaceGroupsTag() )
2836               strcpy( name_group, "Groups of Faces" );
2837             else if ( ii == GetVolumeGroupsTag() )
2838               strcpy( name_group, "Groups of Volumes" );
2839
2840             if ( aTopGroup->ExistInternalObject( name_group ) ) {
2841               aGroup = new HDFgroup( name_group, aTopGroup );
2842               aGroup->OpenOnDisk();
2843               // get number of groups
2844               int aNbSubObjects = aGroup->nInternalObjects(); 
2845               for ( int j = 0; j < aNbSubObjects; j++ ) {
2846                 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2847                 aGroup->InternalObjectIndentify( j, name_dataset );
2848                 // check if it is an group
2849                 if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
2850                   // --> get group id
2851                   int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
2852                   if ( subid <= 0 )
2853                     continue;
2854                   aDataset = new HDFdataset( name_dataset, aGroup );
2855                   aDataset->OpenOnDisk();
2856
2857                   // Retrieve actual group name
2858                   size = aDataset->GetSize();
2859                   char* nameFromFile = new char[ size ];
2860                   aDataset->ReadFromDisk( nameFromFile );
2861                   aDataset->CloseOnDisk();
2862
2863                   // Try to find a shape reference
2864                   TopoDS_Shape aShape;
2865                   char aRefName[ 30 ];
2866                   sprintf( aRefName, "Ref on shape %d", subid);
2867                   if ( aGroup->ExistInternalObject( aRefName ) ) {
2868                     // load mesh "Ref on shape" - it's an entry to SObject
2869                     aDataset = new HDFdataset( aRefName, aGroup );
2870                     aDataset->OpenOnDisk();
2871                     size = aDataset->GetSize();
2872                     char* refFromFile = new char[ size ];
2873                     aDataset->ReadFromDisk( refFromFile );
2874                     aDataset->CloseOnDisk();
2875                     if ( strlen( refFromFile ) > 0 ) {
2876                       SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
2877                       CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
2878                       if ( !CORBA::is_nil( shapeObject ) ) {
2879                         aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
2880                         if ( !aShapeObject->_is_nil() )
2881                           aShape = GeomObjectToShape( aShapeObject );
2882                       }
2883                     }
2884                   }
2885                   // Create group servant
2886                   SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
2887                   SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
2888                     ( myNewMeshImpl->createGroup( type, nameFromFile, aShape ) );
2889                   // Obtain a SMESHDS_Group object 
2890                   if ( aNewGroup->_is_nil() )
2891                     continue;
2892
2893                   string iorSubString = GetORB()->object_to_string( aNewGroup );
2894                   int newSubId = myStudyContext->findId( iorSubString );
2895                   myStudyContext->mapOldToNew( subid, newSubId );
2896
2897                   SMESH_GroupBase_i* aGroupImpl =
2898                     dynamic_cast<SMESH_GroupBase_i*>( GetServant( aNewGroup ).in() );
2899                   if ( !aGroupImpl )
2900                     continue;
2901
2902                   SMESH_Group* aLocalGroup  = myLocMesh.GetGroup( aGroupImpl->GetLocalID() );
2903                   if ( !aLocalGroup )
2904                     continue;
2905
2906                   SMESHDS_GroupBase* aGroupBaseDS = aLocalGroup->GetGroupDS();
2907                   aGroupBaseDS->SetStoreName( name_dataset );
2908
2909                   // Fill group with contents from MED file
2910                   SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
2911                   if ( aGrp )
2912                     myReader.GetGroup( aGrp );
2913                 }
2914               }
2915               aGroup->CloseOnDisk();
2916             }
2917           }
2918         }
2919         // close mesh group
2920         aTopGroup->CloseOnDisk();       
2921       }
2922     }
2923   }
2924   // close HDF file
2925   aFile->CloseOnDisk();
2926   delete aFile;
2927
2928   // Remove temporary files created from the stream
2929   if ( !isMultiFile ) 
2930     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
2931
2932   INFOS( "SMESH_Gen_i::Load completed" );
2933   return true;
2934 }
2935
2936 //=============================================================================
2937 /*!
2938  *  SMESH_Gen_i::LoadASCII
2939  *
2940  *  Load SMESH module's data in ASCII format (not implemented yet)
2941  */
2942 //=============================================================================
2943
2944 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
2945                              const SALOMEDS::TMPFile& theStream,
2946                              const char*              theURL,
2947                              bool                     isMultiFile ) {
2948   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
2949   return Load( theComponent, theStream, theURL, isMultiFile );
2950 }
2951
2952 //=============================================================================
2953 /*!
2954  *  SMESH_Gen_i::Close
2955  *
2956  *  Clears study-connected data when it is closed
2957  */
2958 //=============================================================================
2959
2960 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
2961 {
2962   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
2963
2964   // Clear study contexts data
2965   int studyId = GetCurrentStudyID();
2966   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
2967     delete myStudyContextMap[ studyId ];
2968     myStudyContextMap.erase( studyId );
2969   }
2970   return;
2971 }
2972
2973 //=============================================================================
2974 /*!
2975  *  SMESH_Gen_i::ComponentDataType
2976  * 
2977  *  Get component data type
2978  */
2979 //=============================================================================
2980
2981 char* SMESH_Gen_i::ComponentDataType()
2982 {
2983   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
2984   return CORBA::string_dup( "SMESH" );
2985 }
2986
2987     
2988 //=============================================================================
2989 /*!
2990  *  SMESH_Gen_i::IORToLocalPersistentID
2991  *  
2992  *  Transform data from transient form to persistent
2993  */
2994 //=============================================================================
2995
2996 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
2997                                            const char*           IORString,
2998                                            CORBA::Boolean        /*isMultiFile*/,
2999                                            CORBA::Boolean        /*isASCII*/ )
3000 {
3001   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
3002   StudyContext* myStudyContext = GetCurrentStudyContext();
3003   
3004   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
3005     int anId = myStudyContext->findId( IORString );
3006     if ( anId ) {
3007       if(MYDEBUG) MESSAGE( "VSR " << anId )
3008       char strId[ 20 ];
3009       sprintf( strId, "%d", anId );
3010       return  CORBA::string_dup( strId );
3011     }
3012   }
3013   return CORBA::string_dup( "" );
3014 }
3015
3016 //=============================================================================
3017 /*!
3018  *  SMESH_Gen_i::LocalPersistentIDToIOR
3019  *
3020  *  Transform data from persistent form to transient
3021  */
3022 //=============================================================================
3023
3024 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
3025                                            const char*           aLocalPersistentID,
3026                                            CORBA::Boolean        /*isMultiFile*/,
3027                                            CORBA::Boolean        /*isASCII*/ )
3028 {
3029   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
3030   StudyContext* myStudyContext = GetCurrentStudyContext();
3031
3032   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
3033     int anId = atoi( aLocalPersistentID );
3034     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
3035   }
3036   return CORBA::string_dup( "" );
3037 }
3038
3039 //=======================================================================
3040 //function : RegisterObject
3041 //purpose  : 
3042 //=======================================================================
3043
3044 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
3045 {
3046   StudyContext* myStudyContext = GetCurrentStudyContext();
3047   if ( myStudyContext && !CORBA::is_nil( theObject )) {
3048     string iorString = GetORB()->object_to_string( theObject );
3049     return myStudyContext->addObject( iorString );
3050   }
3051   return 0;
3052 }
3053       
3054 //=============================================================================
3055 /*! 
3056  *  SMESHEngine_factory
3057  *
3058  *  C factory, accessible with dlsym, after dlopen  
3059  */
3060 //=============================================================================
3061
3062 extern "C"
3063 {
3064   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
3065                                                  PortableServer::POA_ptr   poa, 
3066                                                  PortableServer::ObjectId* contId,
3067                                                  const char*               instanceName, 
3068                                                  const char*               interfaceName )
3069   {
3070     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
3071     if(MYDEBUG) SCRUTE(interfaceName);
3072     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
3073     return aSMESHGen->getId() ;
3074   }
3075 }