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