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