Salome HOME
Corrected for PAL13400.
[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   if ( CORBA::is_nil( theMesh ) )
1134     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
1135
1136   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
1137   GEOM::GEOM_Gen_var    geomGen   = GetGeomEngine();
1138
1139   // get a core mesh DS
1140   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1141   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
1142   {
1143     ::SMESH_Mesh & mesh = meshServant->GetImpl();
1144     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
1145     // find the element in mesh
1146     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) )
1147       // find a shape id by the element
1148       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
1149         // get a geom object by the shape id
1150         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
1151         if ( geom->_is_nil() ) {
1152           GEOM::GEOM_IShapesOperations_var op =
1153             geomGen->GetIShapesOperations( GetCurrentStudyID() );
1154           if ( !op->_is_nil() )
1155             geom = op->GetSubShape( mainShape, shapeID );
1156         }
1157         if ( !geom->_is_nil() ) {
1158           // try to find the corresponding SObject
1159           GeomObjectToShape( geom ); // geom client remembers the found shape
1160           SALOMEDS::SObject_var SObj = ObjectToSObject( myCurrentStudy, geom.in() );
1161           if ( SObj->_is_nil() )
1162             // publish a new subshape
1163             SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
1164           // return only published geometry
1165           if ( !SObj->_is_nil() )
1166             return geom._retn();
1167         }
1168       }
1169   }
1170   return GEOM::GEOM_Object::_nil();
1171 }
1172
1173 //=============================================================================
1174 /*!
1175  *  SMESH_Gen_i::Save
1176  *
1177  *  Save SMESH module's data
1178  */
1179 //=============================================================================
1180 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
1181                                       const char*              theURL,
1182                                       bool                     isMultiFile )
1183 {
1184   INFOS( "SMESH_Gen_i::Save" );
1185
1186 //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
1187   // san -- in case <myCurrentStudy> differs from theComponent's study,
1188   // use that of the component
1189   if ( myCurrentStudy->_is_nil() || 
1190        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
1191     SetCurrentStudy( theComponent->GetStudy() );
1192
1193   // Store study contents as a set of python commands
1194   SavePython(myCurrentStudy);
1195
1196   StudyContext* myStudyContext = GetCurrentStudyContext();
1197   
1198   // Declare a byte stream
1199   SALOMEDS::TMPFile_var aStreamFile;
1200   
1201   // Obtain a temporary dir
1202   TCollection_AsciiString tmpDir =
1203     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
1204
1205   // Create a sequence of files processed
1206   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
1207   aFileSeq->length( NUM_TMP_FILES );
1208
1209   TCollection_AsciiString aStudyName( "" );
1210   if ( isMultiFile ) 
1211     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
1212
1213   // Set names of temporary files
1214   TCollection_AsciiString filename =
1215     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
1216   TCollection_AsciiString meshfile =
1217     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
1218   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
1219   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
1220   filename = tmpDir + filename;
1221   meshfile = tmpDir + meshfile;
1222
1223   HDFfile*    aFile;
1224   HDFdataset* aDataset;
1225   HDFgroup*   aTopGroup;
1226   HDFgroup*   aGroup;
1227   HDFgroup*   aSubGroup;
1228   HDFgroup*   aSubSubGroup;
1229   hdf_size    aSize[ 1 ];
1230
1231
1232   //Remove the files if they exist: BugID: 11225
1233   TCollection_AsciiString cmd("rm -f \"");
1234   cmd+=filename;
1235   cmd+="\" \"";
1236   cmd+=meshfile;
1237   cmd+="\"";
1238   system(cmd.ToCString());
1239
1240   // MED writer to be used by storage process
1241   DriverMED_W_SMESHDS_Mesh myWriter;
1242   myWriter.SetFile( meshfile.ToCString() );
1243
1244   // Write data
1245   // ---> create HDF file
1246   aFile = new HDFfile( filename.ToCString() );
1247   aFile->CreateOnDisk();
1248
1249   // --> iterator for top-level objects
1250   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
1251   for ( ; itBig->More(); itBig->Next() ) {
1252     SALOMEDS::SObject_var gotBranch = itBig->Value();
1253
1254     // --> hypotheses root branch (only one for the study)
1255     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
1256       // create hypotheses root HDF group
1257       aTopGroup = new HDFgroup( "Hypotheses", aFile );
1258       aTopGroup->CreateOnDisk();
1259
1260       // iterator for all hypotheses
1261       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
1262       for ( ; it->More(); it->Next() ) {
1263         SALOMEDS::SObject_var mySObject = it->Value();
1264         CORBA::Object_var anObject = SObjectToObject( mySObject );
1265         if ( !CORBA::is_nil( anObject ) ) {
1266           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
1267           if ( !myHyp->_is_nil() ) {
1268             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1269             if ( myImpl ) {
1270               string hypname = string( myHyp->GetName() );
1271               string libname = string( myHyp->GetLibName() );
1272               int    id      = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1273               string hypdata = string( myImpl->SaveTo() );
1274
1275               // for each hypothesis create HDF group basing on its id
1276               char hypGrpName[30];
1277               sprintf( hypGrpName, "Hypothesis %d", id );
1278               aGroup = new HDFgroup( hypGrpName, aTopGroup );
1279               aGroup->CreateOnDisk();
1280               // --> type name of hypothesis
1281               aSize[ 0 ] = hypname.length() + 1;
1282               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
1283               aDataset->CreateOnDisk();
1284               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
1285               aDataset->CloseOnDisk();
1286               // --> server plugin library name of hypothesis
1287               aSize[ 0 ] = libname.length() + 1;
1288               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
1289               aDataset->CreateOnDisk();
1290               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
1291               aDataset->CloseOnDisk();
1292               // --> persistent data of hypothesis
1293               aSize[ 0 ] = hypdata.length() + 1;
1294               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
1295               aDataset->CreateOnDisk();
1296               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
1297               aDataset->CloseOnDisk();
1298               // close hypothesis HDF group
1299               aGroup->CloseOnDisk();
1300             }
1301           }
1302         }
1303       }
1304       // close hypotheses root HDF group
1305       aTopGroup->CloseOnDisk();
1306     }
1307     // --> algorithms root branch (only one for the study)
1308     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1309       // create algorithms root HDF group
1310       aTopGroup = new HDFgroup( "Algorithms", aFile );
1311       aTopGroup->CreateOnDisk();
1312
1313       // iterator for all algorithms
1314       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
1315       for ( ; it->More(); it->Next() ) {
1316         SALOMEDS::SObject_var mySObject = it->Value();
1317         CORBA::Object_var anObject = SObjectToObject( mySObject );
1318         if ( !CORBA::is_nil( anObject ) ) {
1319           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
1320           if ( !myHyp->_is_nil() ) {
1321             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1322             if ( myImpl ) {
1323               string hypname = string( myHyp->GetName() );
1324               string libname = string( myHyp->GetLibName() );
1325               int    id      = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1326               string hypdata = string( myImpl->SaveTo() );
1327
1328               // for each algorithm create HDF group basing on its id
1329               char hypGrpName[30];
1330               sprintf( hypGrpName, "Algorithm %d", id );
1331               aGroup = new HDFgroup( hypGrpName, aTopGroup );
1332               aGroup->CreateOnDisk();
1333               // --> type name of algorithm
1334               aSize[0] = hypname.length() + 1;
1335               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
1336               aDataset->CreateOnDisk();
1337               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
1338               aDataset->CloseOnDisk();
1339               // --> server plugin library name of hypothesis
1340               aSize[0] = libname.length() + 1;
1341               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
1342               aDataset->CreateOnDisk();
1343               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
1344               aDataset->CloseOnDisk();
1345               // --> persistent data of algorithm
1346               aSize[0] = hypdata.length() + 1;
1347               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
1348               aDataset->CreateOnDisk();
1349               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
1350               aDataset->CloseOnDisk();
1351               // close algorithm HDF group
1352               aGroup->CloseOnDisk();
1353             }
1354           }
1355         }
1356       }
1357       // close algorithms root HDF group
1358       aTopGroup->CloseOnDisk();
1359     }
1360     // --> mesh objects roots branches
1361     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
1362       CORBA::Object_var anObject = SObjectToObject( gotBranch );
1363       if ( !CORBA::is_nil( anObject ) ) {
1364         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
1365         if ( !myMesh->_is_nil() ) {
1366           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
1367           if ( myImpl ) {
1368             int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1369             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
1370             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
1371
1372             // for each mesh open the HDF group basing on its id
1373             char meshGrpName[ 30 ];
1374             sprintf( meshGrpName, "Mesh %d", id );
1375             aTopGroup = new HDFgroup( meshGrpName, aFile );
1376             aTopGroup->CreateOnDisk();
1377
1378             // --> put dataset to hdf file which is a flag that mesh has data
1379             string strHasData = "0";
1380             // check if the mesh is not empty
1381             if ( mySMESHDSMesh->NbNodes() > 0 ) {
1382               // write mesh data to med file
1383               myWriter.SetMesh( mySMESHDSMesh );
1384               myWriter.SetMeshId( id );
1385               strHasData = "1";
1386             }
1387             aSize[ 0 ] = strHasData.length() + 1;
1388             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
1389             aDataset->CreateOnDisk();
1390             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
1391             aDataset->CloseOnDisk();
1392             
1393             // write reference on a shape if exists
1394             SALOMEDS::SObject_var myRef;
1395             bool shapeRefFound = false;
1396             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
1397             if ( found ) {
1398               SALOMEDS::SObject_var myShape;
1399               bool ok = myRef->ReferencedObject( myShape );
1400               if ( ok ) {
1401                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
1402                 string myRefOnObject = myShape->GetID();
1403                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
1404                   aSize[ 0 ] = myRefOnObject.length() + 1;
1405                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
1406                   aDataset->CreateOnDisk();
1407                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1408                   aDataset->CloseOnDisk();
1409                 }
1410               }
1411             }
1412
1413             // write applied hypotheses if exist
1414             SALOMEDS::SObject_var myHypBranch;
1415             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
1416             if ( found && !shapeRefFound ) { // remove applied hyps
1417               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
1418             }
1419             if ( found && shapeRefFound ) {
1420               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
1421               aGroup->CreateOnDisk();
1422
1423               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
1424               int hypNb = 0;
1425               for ( ; it->More(); it->Next() ) {
1426                 SALOMEDS::SObject_var mySObject = it->Value();
1427                 SALOMEDS::SObject_var myRefOnHyp;
1428                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
1429                 if ( ok ) {
1430                   // san - it is impossible to recover applied hypotheses
1431                   //       using their entries within Load() method,
1432                   // for there are no AttributeIORs in the study when Load() is working. 
1433                   // Hence, it is better to store persistent IDs of hypotheses as references to them
1434
1435                   //string myRefOnObject = myRefOnHyp->GetID();
1436                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
1437                   int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1438                   //if ( myRefOnObject.length() > 0 ) {
1439                   //aSize[ 0 ] = myRefOnObject.length() + 1;
1440                   char hypName[ 30 ], hypId[ 30 ];
1441                   sprintf( hypName, "Hyp %d", ++hypNb );
1442                   sprintf( hypId, "%d", id );
1443                   aSize[ 0 ] = strlen( hypId ) + 1;
1444                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
1445                   aDataset->CreateOnDisk();
1446                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1447                   aDataset->WriteOnDisk( hypId );
1448                   aDataset->CloseOnDisk();
1449                   //}
1450                 }
1451               }
1452               aGroup->CloseOnDisk();
1453             }
1454
1455             // write applied algorithms if exist
1456             SALOMEDS::SObject_var myAlgoBranch;
1457             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
1458             if ( found && !shapeRefFound ) { // remove applied algos
1459               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
1460             }
1461             if ( found && shapeRefFound ) {
1462               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
1463               aGroup->CreateOnDisk();
1464
1465               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
1466               int algoNb = 0;
1467               for ( ; it->More(); it->Next() ) {
1468                 SALOMEDS::SObject_var mySObject = it->Value();
1469                 SALOMEDS::SObject_var myRefOnAlgo;
1470                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
1471                 if ( ok ) {
1472                   // san - it is impossible to recover applied algorithms
1473                   //       using their entries within Load() method,
1474                   // for there are no AttributeIORs in the study when Load() is working. 
1475                   // Hence, it is better to store persistent IDs of algorithms as references to them
1476
1477                   //string myRefOnObject = myRefOnAlgo->GetID();
1478                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
1479                   int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1480                   //if ( myRefOnObject.length() > 0 ) {
1481                   //aSize[ 0 ] = myRefOnObject.length() + 1;
1482                   char algoName[ 30 ], algoId[ 30 ];
1483                   sprintf( algoName, "Algo %d", ++algoNb );
1484                   sprintf( algoId, "%d", id );
1485                   aSize[ 0 ] = strlen( algoId ) + 1;
1486                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
1487                   aDataset->CreateOnDisk();
1488                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1489                   aDataset->WriteOnDisk( algoId );
1490                   aDataset->CloseOnDisk();
1491                   //}
1492                 }
1493               }
1494               aGroup->CloseOnDisk();
1495             }
1496
1497             // --> submesh objects sub-branches
1498
1499             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
1500               SALOMEDS::SObject_var mySubmeshBranch;
1501               found = gotBranch->FindSubObject( i, mySubmeshBranch );
1502
1503               if ( found ) // check if there is shape reference in submeshes
1504               {
1505                 bool hasShapeRef = false;
1506                 SALOMEDS::ChildIterator_var itSM =
1507                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
1508                 for ( ; itSM->More(); itSM->Next() ) {
1509                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
1510                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
1511                     mySubRef->ReferencedObject( myShape );
1512                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
1513                     hasShapeRef = true;
1514                   else
1515                   { // remove one submesh
1516                     if ( shapeRefFound )
1517                     { // unassign hypothesis
1518                       SMESH::SMESH_subMesh_var mySubMesh =
1519                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
1520                       if ( !mySubMesh->_is_nil() ) {
1521                         int shapeID = mySubMesh->GetId();
1522                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
1523                         const list<const SMESHDS_Hypothesis*>& hypList =
1524                           mySMESHDSMesh->GetHypothesis( S );
1525                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
1526                         while ( hyp != hypList.end() ) {
1527                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
1528                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
1529                         }
1530                       }
1531                     }
1532                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
1533                   }
1534                 } // loop on submeshes of a type
1535                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
1536                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
1537                   found = false;
1538                 }
1539               }  // end check if there is shape reference in submeshes
1540               if ( found ) {
1541                 char name_meshgroup[ 30 ];
1542                 if ( i == GetSubMeshOnVertexTag() )
1543                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
1544                 else if ( i == GetSubMeshOnEdgeTag() )
1545                   strcpy( name_meshgroup, "SubMeshes On Edge" );
1546                 else if ( i == GetSubMeshOnWireTag() )
1547                   strcpy( name_meshgroup, "SubMeshes On Wire" );
1548                 else if ( i == GetSubMeshOnFaceTag() )
1549                   strcpy( name_meshgroup, "SubMeshes On Face" );
1550                 else if ( i == GetSubMeshOnShellTag() )
1551                   strcpy( name_meshgroup, "SubMeshes On Shell" );
1552                 else if ( i == GetSubMeshOnSolidTag() )
1553                   strcpy( name_meshgroup, "SubMeshes On Solid" );
1554                 else if ( i == GetSubMeshOnCompoundTag() )
1555                   strcpy( name_meshgroup, "SubMeshes On Compound" );
1556                 
1557                 // for each type of submeshes create container HDF group
1558                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
1559                 aGroup->CreateOnDisk();
1560             
1561                 // iterator for all submeshes of given type
1562                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
1563                 for ( ; itSM->More(); itSM->Next() ) {
1564                   SALOMEDS::SObject_var mySObject = itSM->Value();
1565                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
1566                   if ( !CORBA::is_nil( anSubObject ))
1567                   {
1568                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
1569                     int subid = myStudyContext->findId( string( GetORB()->object_to_string( anSubObject ) ) );
1570                       
1571                     // for each mesh open the HDF group basing on its id
1572                     char submeshGrpName[ 30 ];
1573                     sprintf( submeshGrpName, "SubMesh %d", subid );
1574                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
1575                     aSubGroup->CreateOnDisk();
1576
1577                     // write reference on a shape, already checked if it exists
1578                     SALOMEDS::SObject_var mySubRef, myShape;
1579                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
1580                       mySubRef->ReferencedObject( myShape );
1581                     string myRefOnObject = myShape->GetID();
1582                     if ( myRefOnObject.length() > 0 ) {
1583                       aSize[ 0 ] = myRefOnObject.length() + 1;
1584                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
1585                       aDataset->CreateOnDisk();
1586                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1587                       aDataset->CloseOnDisk();
1588                     }
1589
1590                     // write applied hypotheses if exist
1591                     SALOMEDS::SObject_var mySubHypBranch;
1592                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
1593                     if ( found ) {
1594                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
1595                       aSubSubGroup->CreateOnDisk();
1596
1597                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
1598                       int hypNb = 0;
1599                       for ( ; it->More(); it->Next() ) {
1600                         SALOMEDS::SObject_var mySubSObject = it->Value();
1601                         SALOMEDS::SObject_var myRefOnHyp;
1602                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
1603                         if ( ok ) {
1604                           //string myRefOnObject = myRefOnHyp->GetID();
1605                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
1606                           int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1607                           //if ( myRefOnObject.length() > 0 ) {
1608                           //aSize[ 0 ] = myRefOnObject.length() + 1;
1609                           char hypName[ 30 ], hypId[ 30 ];
1610                           sprintf( hypName, "Hyp %d", ++hypNb );
1611                           sprintf( hypId, "%d", id );
1612                           aSize[ 0 ] = strlen( hypId ) + 1;
1613                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
1614                           aDataset->CreateOnDisk();
1615                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1616                           aDataset->WriteOnDisk( hypId );
1617                           aDataset->CloseOnDisk();
1618                           //}
1619                         }
1620                       }
1621                       aSubSubGroup->CloseOnDisk();
1622                     }
1623                     
1624                     // write applied algorithms if exist
1625                     SALOMEDS::SObject_var mySubAlgoBranch;
1626                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
1627                     if ( found ) {
1628                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
1629                       aSubSubGroup->CreateOnDisk();
1630
1631                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
1632                       int algoNb = 0;
1633                       for ( ; it->More(); it->Next() ) {
1634                         SALOMEDS::SObject_var mySubSObject = it->Value();
1635                         SALOMEDS::SObject_var myRefOnAlgo;
1636                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
1637                         if ( ok ) {
1638                           //string myRefOnObject = myRefOnAlgo->GetID();
1639                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
1640                           int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1641                           //if ( myRefOnObject.length() > 0 ) {
1642                           //aSize[ 0 ] = myRefOnObject.length() + 1;
1643                           char algoName[ 30 ], algoId[ 30 ];
1644                           sprintf( algoName, "Algo %d", ++algoNb );
1645                           sprintf( algoId, "%d", id );
1646                           aSize[ 0 ] = strlen( algoId ) + 1;
1647                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
1648                           aDataset->CreateOnDisk();
1649                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1650                           aDataset->WriteOnDisk( algoId );
1651                           aDataset->CloseOnDisk();
1652                           //}
1653                         }
1654                       }
1655                       aSubSubGroup->CloseOnDisk();
1656                     }
1657                     // close submesh HDF group
1658                     aSubGroup->CloseOnDisk();
1659                   }
1660                 }
1661                 // close container of submeshes by type HDF group
1662                 aGroup->CloseOnDisk();
1663               }
1664             }
1665             // All sub-meshes will be stored in MED file
1666             // .. will NOT (PAL 12992)
1667             //if ( shapeRefFound )
1668             //myWriter.AddAllSubMeshes();
1669
1670             // groups root sub-branch
1671             SALOMEDS::SObject_var myGroupsBranch;
1672             for ( int i = GetNodeGroupsTag(); i <= GetVolumeGroupsTag(); i++ ) {
1673               found = gotBranch->FindSubObject( i, myGroupsBranch );
1674               if ( found ) {
1675                 char name_group[ 30 ];
1676                 if ( i == GetNodeGroupsTag() )
1677                   strcpy( name_group, "Groups of Nodes" );
1678                 else if ( i == GetEdgeGroupsTag() )
1679                   strcpy( name_group, "Groups of Edges" );
1680                 else if ( i == GetFaceGroupsTag() )
1681                   strcpy( name_group, "Groups of Faces" );
1682                 else if ( i == GetVolumeGroupsTag() )
1683                   strcpy( name_group, "Groups of Volumes" );
1684
1685                 aGroup = new HDFgroup( name_group, aTopGroup );
1686                 aGroup->CreateOnDisk();
1687
1688                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
1689                 for ( ; it->More(); it->Next() ) {
1690                   SALOMEDS::SObject_var mySObject = it->Value();
1691                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
1692                   if ( !CORBA::is_nil( aSubObject ) ) {
1693                     SMESH_GroupBase_i* myGroupImpl =
1694                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
1695                     if ( !myGroupImpl )
1696                       continue;
1697
1698                     int anId = myStudyContext->findId( string( GetORB()->object_to_string( aSubObject ) ) );
1699                     
1700                     // For each group, create a dataset named "Group <group_persistent_id>"
1701                     // and store the group's user name into it
1702                     char grpName[ 30 ];
1703                     sprintf( grpName, "Group %d", anId );
1704                     char* aUserName = myGroupImpl->GetName();
1705                     aSize[ 0 ] = strlen( aUserName ) + 1;
1706
1707                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
1708                     aDataset->CreateOnDisk();
1709                     aDataset->WriteOnDisk( aUserName );
1710                     aDataset->CloseOnDisk();
1711
1712                     // Store the group contents into MED file
1713                     if ( myLocMesh.GetGroup( myGroupImpl->GetLocalID() ) ) {
1714
1715                       if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen_i::Save(): saving group with StoreName = "
1716                               << grpName << " to MED file" );
1717                       SMESHDS_GroupBase* aGrpBaseDS =
1718                         myLocMesh.GetGroup( myGroupImpl->GetLocalID() )->GetGroupDS();
1719                       aGrpBaseDS->SetStoreName( grpName );
1720
1721                       // Pass SMESHDS_Group to MED writer 
1722                       SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
1723                       if ( aGrpDS )
1724                         myWriter.AddGroup( aGrpDS );
1725
1726                       // write reference on a shape if exists
1727                       SMESHDS_GroupOnGeom* aGeomGrp =
1728                         dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
1729                       if ( aGeomGrp ) {
1730                         SALOMEDS::SObject_var mySubRef, myShape;
1731                         if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
1732                             mySubRef->ReferencedObject( myShape ) &&
1733                             !CORBA::is_nil( myShape->GetObject() ))
1734                         {
1735                           string myRefOnObject = myShape->GetID();
1736                           if ( myRefOnObject.length() > 0 ) {
1737                             char aRefName[ 30 ];
1738                             sprintf( aRefName, "Ref on shape %d", anId);
1739                             aSize[ 0 ] = myRefOnObject.length() + 1;
1740                             aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
1741                             aDataset->CreateOnDisk();
1742                             aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1743                             aDataset->CloseOnDisk();
1744                           }
1745                         }
1746                         else // shape ref is invalid:
1747                         {
1748                           // save a group on geometry as ordinary group
1749                           myWriter.AddGroup( aGeomGrp );
1750                         }
1751                       }
1752                     }
1753                   }
1754                 }
1755                 aGroup->CloseOnDisk();
1756               }
1757             } // loop on groups 
1758
1759             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
1760             {
1761               // Flush current mesh information into MED file
1762               myWriter.Perform();
1763
1764               // maybe a shape was deleted in the study
1765               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() ) {
1766                 TopoDS_Shape nullShape;
1767                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
1768               }
1769
1770               if ( !mySMESHDSMesh->SubMeshes().empty() )
1771               {
1772                 // Store submeshes
1773                 // ----------------
1774                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
1775                 aGroup->CreateOnDisk();
1776
1777                 // each element belongs to one or none submesh,
1778                 // so for each node/element, we store a submesh ID
1779
1780                 // Make maps of submesh IDs of elements sorted by element IDs
1781                 typedef int TElemID;
1782                 typedef int TSubMID;
1783                 map< TElemID, TSubMID > eId2smId, nId2smId;
1784                 map< TElemID, TSubMID >::iterator hint; // insertion to map is done before hint
1785                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
1786                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
1787                 SMDS_NodeIteratorPtr itNode;
1788                 SMDS_ElemIteratorPtr itElem;
1789                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
1790                 {
1791                   TSubMID          aSubMeID = itSubM->first;
1792                   SMESHDS_SubMesh* aSubMesh = itSubM->second;
1793                   if ( aSubMesh->IsComplexSubmesh() )
1794                     continue; // submesh containing other submeshs
1795                   // nodes
1796                   hint = nId2smId.begin(); // optimize insertion basing on increasing order of elem Ids in submesh
1797                   for ( itNode = aSubMesh->GetNodes(); itNode->more(); ++hint)
1798                     hint = nId2smId.insert( hint, make_pair( itNode->next()->GetID(), aSubMeID ));
1799                   // elements
1800                   hint = eId2smId.begin();
1801                   for ( itElem = aSubMesh->GetElements(); itElem->more(); ++hint)
1802                     hint = eId2smId.insert( hint, make_pair( itElem->next()->GetID(), aSubMeID ));
1803                 }
1804
1805                 // Care of elements that are not on submeshes
1806                 if ( mySMESHDSMesh->NbNodes() != nId2smId.size() ) {
1807                   for ( itNode = mySMESHDSMesh->nodesIterator(); itNode->more(); )
1808                     /*  --- stl_map.h says : */
1809                     /*  A %map relies on unique keys and thus a %pair is only inserted if its */
1810                     /*  first element (the key) is not already present in the %map.           */
1811                     nId2smId.insert( make_pair( itNode->next()->GetID(), 0 ));
1812                 }
1813                 int nbElems = mySMESHDSMesh->NbEdges() + mySMESHDSMesh->NbFaces() + mySMESHDSMesh->NbVolumes();
1814                 if ( nbElems != eId2smId.size() ) {
1815                   for ( itElem = mySMESHDSMesh->elementsIterator(); itElem->more(); )
1816                     eId2smId.insert( make_pair( itElem->next()->GetID(), 0 ));
1817                 }
1818
1819                 // Store submesh IDs
1820                 for ( int isNode = 0; isNode < 2; ++isNode )
1821                 {
1822                   map< TElemID, TSubMID >& id2smId = isNode ? nId2smId : eId2smId;
1823                   if ( id2smId.empty() ) continue;
1824                   map< TElemID, TSubMID >::const_iterator id_smId = id2smId.begin();
1825                   // make and fill array of submesh IDs
1826                   int* smIDs = new int [ id2smId.size() ];
1827                   for ( int i = 0; id_smId != id2smId.end(); ++id_smId, ++i )
1828                     smIDs[ i ] = id_smId->second;
1829                   // write HDF group
1830                   aSize[ 0 ] = id2smId.size();
1831                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
1832                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
1833                   aDataset->CreateOnDisk();
1834                   aDataset->WriteOnDisk( smIDs );
1835                   aDataset->CloseOnDisk();
1836                   //
1837                   delete smIDs;
1838                 }
1839                 
1840                 // Store node positions on sub-shapes (SMDS_Position):
1841                 // ----------------------------------------------------
1842
1843                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
1844                 aGroup->CreateOnDisk();
1845
1846                 // in aGroup, create 5 datasets to contain:
1847                 // "Nodes on Edges" - ID of node on edge
1848                 // "Edge positions" - U parameter on node on edge
1849                 // "Nodes on Faces" - ID of node on face
1850                 // "Face U positions" - U parameter of node on face
1851                 // "Face V positions" - V parameter of node on face
1852
1853                 // Find out nb of nodes on edges and faces
1854                 // Collect corresponing sub-meshes
1855                 int nbEdgeNodes = 0, nbFaceNodes = 0;
1856                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
1857                 // loop on SMESHDS_SubMesh'es
1858                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
1859                 {
1860                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
1861                   if ( aSubMesh->IsComplexSubmesh() )
1862                     continue; // submesh containing other submeshs
1863                   int nbNodes = aSubMesh->NbNodes();
1864                   if ( nbNodes == 0 ) continue;
1865
1866                   int aShapeID = (*itSubM).first;
1867                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
1868                   // write only SMDS_FacePosition and SMDS_EdgePosition
1869                   switch ( aShapeType ) {
1870                   case TopAbs_FACE:
1871                     nbFaceNodes += nbNodes;
1872                     aFaceSM.push_back( aSubMesh );
1873                     break;
1874                   case TopAbs_EDGE:
1875                     nbEdgeNodes += nbNodes;
1876                     aEdgeSM.push_back( aSubMesh );
1877                     break;
1878                   default:
1879                     continue;
1880                   }
1881                 }
1882                 // Treat positions on edges or faces
1883                 for ( int onFace = 0; onFace < 2; onFace++ )
1884                 {
1885                   // Create arrays to store in datasets
1886                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
1887                   if (!nbNodes) continue;
1888                   int* aNodeIDs = new int [ nbNodes ];
1889                   double* aUPos = new double [ nbNodes ];
1890                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
1891
1892                   // Fill arrays
1893                   // loop on sub-meshes
1894                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
1895                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
1896                   for ( ; itSM != pListSM->end(); itSM++ )
1897                   {
1898                     SMESHDS_SubMesh* aSubMesh = (*itSM);
1899
1900                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
1901                     // loop on nodes in aSubMesh
1902                     while ( itNode->more() )
1903                     {
1904                       //node ID
1905                       const SMDS_MeshNode* node = itNode->next();
1906                       aNodeIDs [ iNode ] = node->GetID();
1907
1908                       // Position
1909                       const SMDS_PositionPtr pos = node->GetPosition();
1910                       if ( onFace ) { // on FACE
1911                         const SMDS_FacePosition* fPos =
1912                           dynamic_cast<const SMDS_FacePosition*>( pos.get() );
1913                         if ( fPos ) {
1914                           aUPos[ iNode ] = fPos->GetUParameter();
1915                           aVPos[ iNode ] = fPos->GetVParameter();
1916                           iNode++;
1917                         }
1918                         else
1919                           nbNodes--;
1920                       }
1921                       else { // on EDGE
1922                         const SMDS_EdgePosition* ePos =
1923                           dynamic_cast<const SMDS_EdgePosition*>( pos.get() );
1924                         if ( ePos ) {
1925                           aUPos[ iNode ] = ePos->GetUParameter();
1926                           iNode++;
1927                         }
1928                         else
1929                           nbNodes--;
1930                       }
1931                     } // loop on nodes in aSubMesh
1932                   } // loop on sub-meshes
1933
1934                   // Write datasets
1935                   if ( nbNodes )
1936                   {
1937                     aSize[ 0 ] = nbNodes;
1938                     // IDS
1939                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
1940                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
1941                     aDataset->CreateOnDisk();
1942                     aDataset->WriteOnDisk( aNodeIDs );
1943                     aDataset->CloseOnDisk();
1944
1945                     // U Positions
1946                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
1947                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
1948                     aDataset->CreateOnDisk();
1949                     aDataset->WriteOnDisk( aUPos );
1950                     aDataset->CloseOnDisk();
1951                     // V Positions
1952                     if ( onFace ) {
1953                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
1954                       aDataset->CreateOnDisk();
1955                       aDataset->WriteOnDisk( aVPos );
1956                       aDataset->CloseOnDisk();
1957                     }
1958                   }
1959                   delete [] aNodeIDs;
1960                   delete [] aUPos;
1961                   if ( aVPos ) delete [] aVPos;
1962
1963                 } // treat positions on edges or faces
1964
1965                 // close "Node Positions" group
1966                 aGroup->CloseOnDisk(); 
1967
1968               } // if ( there are submeshes in SMESHDS_Mesh )
1969             } // if ( hasData )
1970
1971             // close mesh HDF group
1972             aTopGroup->CloseOnDisk();
1973           }
1974         }
1975       }
1976     }
1977   }
1978
1979   // close HDF file
1980   aFile->CloseOnDisk();
1981   delete aFile;
1982
1983   // Convert temporary files to stream
1984   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
1985
1986   // Remove temporary files and directory
1987   if ( !isMultiFile ) 
1988     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
1989
1990   INFOS( "SMESH_Gen_i::Save() completed" );
1991   return aStreamFile._retn();
1992 }
1993
1994 //=============================================================================
1995 /*!
1996  *  SMESH_Gen_i::SaveASCII
1997  *
1998  *  Save SMESH module's data in ASCII format (not implemented yet)
1999  */
2000 //=============================================================================
2001
2002 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
2003                                            const char*              theURL,
2004                                            bool                     isMultiFile ) {
2005   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
2006   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
2007   return aStreamFile._retn();
2008 }
2009
2010 //=============================================================================
2011 /*!
2012  *  SMESH_Gen_i::loadGeomData
2013  *
2014  *  Load GEOM module data
2015  */
2016 //=============================================================================
2017
2018 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
2019 {
2020   if ( theCompRoot->_is_nil() )
2021     return;
2022
2023   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
2024   if ( aStudy->_is_nil() )
2025     return;
2026
2027   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder(); 
2028   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
2029 }
2030 //=============================================================================
2031 /*!
2032  * \brief Creates SMDS_Position according to shape type
2033  */
2034 //=============================================================================
2035
2036 class PositionCreator {
2037 public:
2038   SMDS_PositionPtr MakePosition(const TopAbs_ShapeEnum type) {
2039     return (this->*myFuncTable[ type ])();
2040   }
2041   PositionCreator() {
2042     myFuncTable.resize( (size_t) TopAbs_SHAPE, & PositionCreator::defaultPosition );
2043     myFuncTable[ TopAbs_FACE ] = & PositionCreator::facePosition;
2044     myFuncTable[ TopAbs_EDGE ] = & PositionCreator::edgePosition;
2045     myFuncTable[ TopAbs_VERTEX ] = & PositionCreator::vertexPosition;
2046   }
2047 private:
2048   SMDS_PositionPtr edgePosition()    const { return SMDS_PositionPtr( new SMDS_EdgePosition  ); }
2049   SMDS_PositionPtr facePosition()    const { return SMDS_PositionPtr( new SMDS_FacePosition  ); }
2050   SMDS_PositionPtr vertexPosition()  const { return SMDS_PositionPtr( new SMDS_VertexPosition); }
2051   SMDS_PositionPtr defaultPosition() const { return SMDS_SpacePosition::originSpacePosition();  }
2052   typedef SMDS_PositionPtr (PositionCreator:: * FmakePos)() const;
2053   vector<FmakePos> myFuncTable;
2054 };
2055
2056 //=============================================================================
2057 /*!
2058  *  SMESH_Gen_i::Load
2059  *
2060  *  Load SMESH module's data
2061  */
2062 //=============================================================================
2063
2064 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
2065                         const SALOMEDS::TMPFile& theStream,
2066                         const char*              theURL,
2067                         bool                     isMultiFile )
2068 {
2069   INFOS( "SMESH_Gen_i::Load" );
2070
2071   if ( myCurrentStudy->_is_nil() || 
2072        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
2073     SetCurrentStudy( theComponent->GetStudy() );
2074
2075 /*  if( !theComponent->_is_nil() )
2076   {
2077     //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
2078     if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
2079       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
2080   }*/
2081
2082   StudyContext* myStudyContext = GetCurrentStudyContext();
2083   
2084   // Get temporary files location
2085   TCollection_AsciiString tmpDir =
2086     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2087
2088   // Convert the stream into sequence of files to process
2089   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
2090                                                                             tmpDir.ToCString(),
2091                                                                             isMultiFile );
2092   TCollection_AsciiString aStudyName( "" );
2093   if ( isMultiFile ) 
2094     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2095
2096   // Set names of temporary files
2097   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
2098   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
2099
2100   int size;
2101   HDFfile*    aFile;
2102   HDFdataset* aDataset;
2103   HDFgroup*   aTopGroup;
2104   HDFgroup*   aGroup;
2105   HDFgroup*   aSubGroup;
2106   HDFgroup*   aSubSubGroup;
2107
2108   // Read data
2109   // ---> open HDF file
2110   aFile = new HDFfile( filename.ToCString() );
2111   try {
2112     aFile->OpenOnDisk( HDF_RDONLY );
2113   }
2114   catch ( HDFexception ) {
2115     INFOS( "Load(): " << filename << " not found!" );
2116     return false;
2117   }
2118
2119   DriverMED_R_SMESHDS_Mesh myReader;
2120   myReader.SetFile( meshfile.ToCString() );
2121
2122   // get total number of top-level groups
2123   int aNbGroups = aFile->nInternalObjects(); 
2124   if ( aNbGroups > 0 ) {
2125     // --> in first turn we should read&create hypotheses
2126     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
2127       // open hypotheses root HDF group
2128       aTopGroup = new HDFgroup( "Hypotheses", aFile ); 
2129       aTopGroup->OpenOnDisk();
2130
2131       // get number of hypotheses
2132       int aNbObjects = aTopGroup->nInternalObjects(); 
2133       for ( int j = 0; j < aNbObjects; j++ ) {
2134         // try to identify hypothesis
2135         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
2136         aTopGroup->InternalObjectIndentify( j, hypGrpName );
2137
2138         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
2139           // open hypothesis group
2140           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
2141           aGroup->OpenOnDisk();
2142
2143           // --> get hypothesis id
2144           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
2145           string hypname;
2146           string libname;
2147           string hypdata;
2148
2149           // get number of datasets
2150           int aNbSubObjects = aGroup->nInternalObjects();
2151           for ( int k = 0; k < aNbSubObjects; k++ ) {
2152             // identify dataset
2153             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
2154             aGroup->InternalObjectIndentify( k, name_of_subgroup );
2155             // --> get hypothesis name
2156             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
2157               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2158               aDataset->OpenOnDisk();
2159               size = aDataset->GetSize();
2160               char* hypname_str = new char[ size ];
2161               aDataset->ReadFromDisk( hypname_str );
2162               hypname = string( hypname_str );
2163               delete [] hypname_str;
2164               aDataset->CloseOnDisk();
2165             }
2166             // --> get hypothesis plugin library name
2167             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
2168               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2169               aDataset->OpenOnDisk();
2170               size = aDataset->GetSize();
2171               char* libname_str = new char[ size ];
2172               aDataset->ReadFromDisk( libname_str );
2173               if(MYDEBUG) SCRUTE( libname_str );
2174               libname = string( libname_str );
2175               delete [] libname_str;
2176               aDataset->CloseOnDisk();
2177             }
2178             // --> get hypothesis data
2179             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
2180               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2181               aDataset->OpenOnDisk();
2182               size = aDataset->GetSize();
2183               char* hypdata_str = new char[ size ];
2184               aDataset->ReadFromDisk( hypdata_str );
2185               hypdata = string( hypdata_str );
2186               delete [] hypdata_str;
2187               aDataset->CloseOnDisk();
2188             }
2189           }
2190           // close hypothesis HDF group
2191           aGroup->CloseOnDisk();
2192
2193           // --> restore hypothesis from data
2194           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
2195             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
2196                     ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
2197             SMESH::SMESH_Hypothesis_var myHyp;
2198             
2199             try { // protect persistence mechanism against exceptions
2200               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
2201             }
2202             catch (...) {
2203               INFOS( "Exception during hypothesis creation" );
2204             }
2205
2206             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2207             if ( myImpl ) {
2208               myImpl->LoadFrom( hypdata.c_str() );
2209               string iorString = GetORB()->object_to_string( myHyp );
2210               int newId = myStudyContext->findId( iorString );
2211               myStudyContext->mapOldToNew( id, newId );
2212             }
2213             else
2214               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
2215           }
2216         }
2217       }
2218       // close hypotheses root HDF group
2219       aTopGroup->CloseOnDisk();
2220     }
2221
2222     // --> then we should read&create algorithms
2223     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
2224       // open algorithms root HDF group
2225       aTopGroup = new HDFgroup( "Algorithms", aFile ); 
2226       aTopGroup->OpenOnDisk();
2227
2228       // get number of algorithms
2229       int aNbObjects = aTopGroup->nInternalObjects(); 
2230       for ( int j = 0; j < aNbObjects; j++ ) {
2231         // try to identify algorithm
2232         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
2233         aTopGroup->InternalObjectIndentify( j, hypGrpName );
2234
2235         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
2236           // open algorithm group
2237           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
2238           aGroup->OpenOnDisk();
2239
2240           // --> get algorithm id
2241           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
2242           string hypname;
2243           string libname;
2244           string hypdata;
2245
2246           // get number of datasets
2247           int aNbSubObjects = aGroup->nInternalObjects();
2248           for ( int k = 0; k < aNbSubObjects; k++ ) {
2249             // identify dataset
2250             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
2251             aGroup->InternalObjectIndentify( k, name_of_subgroup );
2252             // --> get algorithm name
2253             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
2254               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2255               aDataset->OpenOnDisk();
2256               size = aDataset->GetSize();
2257               char* hypname_str = new char[ size ];
2258               aDataset->ReadFromDisk( hypname_str );
2259               hypname = string( hypname_str );
2260               delete [] hypname_str;
2261               aDataset->CloseOnDisk();
2262             }
2263             // --> get algorithm plugin library name
2264             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
2265               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2266               aDataset->OpenOnDisk();
2267               size = aDataset->GetSize();
2268               char* libname_str = new char[ size ];
2269               aDataset->ReadFromDisk( libname_str );
2270               if(MYDEBUG) SCRUTE( libname_str );
2271               libname = string( libname_str );
2272               delete [] libname_str;
2273               aDataset->CloseOnDisk();
2274             }
2275             // --> get algorithm data
2276             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
2277               aDataset = new HDFdataset( name_of_subgroup, aGroup );
2278               aDataset->OpenOnDisk();
2279               size = aDataset->GetSize();
2280               char* hypdata_str = new char[ size ];
2281               aDataset->ReadFromDisk( hypdata_str );
2282               if(MYDEBUG) SCRUTE( hypdata_str );
2283               hypdata = string( hypdata_str );
2284               delete [] hypdata_str;
2285               aDataset->CloseOnDisk();
2286             }
2287           }
2288           // close algorithm HDF group
2289           aGroup->CloseOnDisk();
2290           
2291           // --> restore algorithm from data
2292           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
2293             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
2294                     ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
2295             SMESH::SMESH_Hypothesis_var myHyp;
2296                     
2297             try { // protect persistence mechanism against exceptions
2298               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
2299             }
2300             catch (...) {
2301               INFOS( "Exception during hypothesis creation" );
2302             }
2303             
2304             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2305             if ( myImpl ) {
2306               myImpl->LoadFrom( hypdata.c_str() );
2307               string iorString = GetORB()->object_to_string( myHyp );
2308               int newId = myStudyContext->findId( iorString );
2309               myStudyContext->mapOldToNew( id, newId );
2310             }
2311             else
2312               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
2313           }
2314         }
2315       }
2316       // close algorithms root HDF group
2317       aTopGroup->CloseOnDisk();
2318     }
2319
2320     // --> the rest groups should be meshes
2321     for ( int i = 0; i < aNbGroups; i++ ) {
2322       // identify next group
2323       char meshName[ HDF_NAME_MAX_LEN+1 ];
2324       aFile->InternalObjectIndentify( i, meshName );
2325
2326       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
2327         // --> get mesh id
2328         int id = atoi( string( meshName ).substr( 4 ).c_str() );
2329         if ( id <= 0 )
2330           continue;
2331
2332         bool hasData = false;
2333
2334         // open mesh HDF group
2335         aTopGroup = new HDFgroup( meshName, aFile ); 
2336         aTopGroup->OpenOnDisk();
2337
2338         // get number of child HDF objects
2339         int aNbObjects = aTopGroup->nInternalObjects(); 
2340         if ( aNbObjects > 0 ) {
2341           // create mesh
2342           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
2343           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
2344           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
2345           if ( !myNewMeshImpl )
2346             continue;
2347           string iorString = GetORB()->object_to_string( myNewMesh );
2348           int newId = myStudyContext->findId( iorString );
2349           myStudyContext->mapOldToNew( id, newId );
2350           
2351           ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
2352           SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
2353
2354           // try to find mesh data dataset
2355           if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
2356             // load mesh "has data" flag
2357             aDataset = new HDFdataset( "Has data", aTopGroup );
2358             aDataset->OpenOnDisk();
2359             size = aDataset->GetSize();
2360             char* strHasData = new char[ size ];
2361             aDataset->ReadFromDisk( strHasData );
2362             aDataset->CloseOnDisk();
2363             if ( strcmp( strHasData, "1") == 0 ) {
2364               // read mesh data from MED file
2365               myReader.SetMesh( mySMESHDSMesh );
2366               myReader.SetMeshId( id );
2367               myReader.Perform();
2368               hasData = true;
2369             }
2370           }
2371
2372           // try to read and set reference to shape
2373           GEOM::GEOM_Object_var aShapeObject;
2374           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
2375             // load mesh "Ref on shape" - it's an entry to SObject
2376             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
2377             aDataset->OpenOnDisk();
2378             size = aDataset->GetSize();
2379             char* refFromFile = new char[ size ];
2380             aDataset->ReadFromDisk( refFromFile );
2381             aDataset->CloseOnDisk();
2382             if ( strlen( refFromFile ) > 0 ) {
2383               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
2384
2385               // Make sure GEOM data are loaded first
2386               //loadGeomData( shapeSO->GetFatherComponent() );
2387
2388               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
2389               if ( !CORBA::is_nil( shapeObject ) ) {
2390                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
2391                 if ( !aShapeObject->_is_nil() )
2392                   myNewMeshImpl->SetShape( aShapeObject );
2393               }
2394             }
2395           }
2396
2397           // try to get applied algorithms
2398           if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
2399             aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
2400             aGroup->OpenOnDisk();
2401             // get number of applied algorithms
2402             int aNbSubObjects = aGroup->nInternalObjects(); 
2403             if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
2404             for ( int j = 0; j < aNbSubObjects; j++ ) {
2405               char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2406               aGroup->InternalObjectIndentify( j, name_dataset );
2407               // check if it is an algorithm
2408               if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
2409                 aDataset = new HDFdataset( name_dataset, aGroup );
2410                 aDataset->OpenOnDisk();
2411                 size = aDataset->GetSize();
2412                 char* refFromFile = new char[ size ];
2413                 aDataset->ReadFromDisk( refFromFile );
2414                 aDataset->CloseOnDisk();
2415
2416                 // san - it is impossible to recover applied algorithms using their entries within Load() method
2417                 
2418                 //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2419                 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2420                 int id = atoi( refFromFile );
2421                 string anIOR = myStudyContext->getIORbyOldId( id );
2422                 if ( !anIOR.empty() ) {
2423                   CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2424                   if ( !CORBA::is_nil( hypObject ) ) {
2425                     SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2426                     if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2427                       myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
2428                   }
2429                 }
2430               }
2431             }
2432             aGroup->CloseOnDisk();
2433           }
2434
2435           // try to get applied hypotheses
2436           if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
2437             aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
2438             aGroup->OpenOnDisk();
2439             // get number of applied hypotheses
2440             int aNbSubObjects = aGroup->nInternalObjects(); 
2441             for ( int j = 0; j < aNbSubObjects; j++ ) {
2442               char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2443               aGroup->InternalObjectIndentify( j, name_dataset );
2444               // check if it is a hypothesis
2445               if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
2446                 aDataset = new HDFdataset( name_dataset, aGroup );
2447                 aDataset->OpenOnDisk();
2448                 size = aDataset->GetSize();
2449                 char* refFromFile = new char[ size ];
2450                 aDataset->ReadFromDisk( refFromFile );
2451                 aDataset->CloseOnDisk();
2452
2453                 // san - it is impossible to recover applied hypotheses using their entries within Load() method
2454                 
2455                 //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2456                 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2457                 int id = atoi( refFromFile );
2458                 string anIOR = myStudyContext->getIORbyOldId( id );
2459                 if ( !anIOR.empty() ) {
2460                   CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2461                   if ( !CORBA::is_nil( hypObject ) ) {
2462                     SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2463                     if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2464                       myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
2465                   }
2466                 }
2467               }
2468             }
2469             aGroup->CloseOnDisk();
2470           }
2471
2472           // --> try to find submeshes containers for each type of submesh
2473           for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
2474             char name_meshgroup[ 30 ];
2475             if ( j == GetSubMeshOnVertexTag() )
2476               strcpy( name_meshgroup, "SubMeshes On Vertex" );
2477             else if ( j == GetSubMeshOnEdgeTag() )
2478               strcpy( name_meshgroup, "SubMeshes On Edge" );
2479             else if ( j == GetSubMeshOnWireTag() )
2480               strcpy( name_meshgroup, "SubMeshes On Wire" );
2481             else if ( j == GetSubMeshOnFaceTag() )
2482               strcpy( name_meshgroup, "SubMeshes On Face" );
2483             else if ( j == GetSubMeshOnShellTag() )
2484               strcpy( name_meshgroup, "SubMeshes On Shell" );
2485             else if ( j == GetSubMeshOnSolidTag() )
2486               strcpy( name_meshgroup, "SubMeshes On Solid" );
2487             else if ( j == GetSubMeshOnCompoundTag() )
2488               strcpy( name_meshgroup, "SubMeshes On Compound" );
2489             
2490             // try to get submeshes container HDF group
2491             if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
2492               // open submeshes containers HDF group
2493               aGroup = new HDFgroup( name_meshgroup, aTopGroup );
2494               aGroup->OpenOnDisk();
2495               
2496               // get number of submeshes
2497               int aNbSubMeshes = aGroup->nInternalObjects(); 
2498               for ( int k = 0; k < aNbSubMeshes; k++ ) {
2499                 // identify submesh
2500                 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
2501                 aGroup->InternalObjectIndentify( k, name_submeshgroup );
2502                 if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
2503                   // --> get submesh id
2504                   int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
2505                   if ( subid <= 0 )
2506                     continue;
2507                   // open submesh HDF group
2508                   aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
2509                   aSubGroup->OpenOnDisk();
2510                   
2511                   // try to read and set reference to subshape
2512                   GEOM::GEOM_Object_var aSubShapeObject;
2513                   SMESH::SMESH_subMesh_var aSubMesh;
2514
2515                   if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
2516                     // load submesh "Ref on shape" - it's an entry to SObject
2517                     aDataset = new HDFdataset( "Ref on shape", aSubGroup );
2518                     aDataset->OpenOnDisk();
2519                     size = aDataset->GetSize();
2520                     char* refFromFile = new char[ size ];
2521                     aDataset->ReadFromDisk( refFromFile );
2522                     aDataset->CloseOnDisk();
2523                     if ( strlen( refFromFile ) > 0 ) {
2524                       SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
2525                       CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
2526                       if ( !CORBA::is_nil( subShapeObject ) ) {
2527                         aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
2528                         if ( !aSubShapeObject->_is_nil() )
2529                           aSubMesh = SMESH::SMESH_subMesh::_duplicate
2530                             ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
2531                         if ( aSubMesh->_is_nil() )
2532                           continue;
2533                         string iorSubString = GetORB()->object_to_string( aSubMesh );
2534                         int newSubId = myStudyContext->findId( iorSubString );
2535                         myStudyContext->mapOldToNew( subid, newSubId );
2536                       }
2537                     }
2538                   }
2539                   
2540                   if ( aSubMesh->_is_nil() )
2541                     continue;
2542
2543                   // VSR: Get submesh data from MED convertor
2544 //                int anInternalSubmeshId = aSubMesh->GetId(); // this is not a persistent ID, it's an internal one computed from sub-shape
2545 //                if (myNewMeshImpl->_mapSubMesh.find(anInternalSubmeshId) != myNewMeshImpl->_mapSubMesh.end()) {
2546 //                  if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): loading from MED file submesh with ID = " <<
2547 //                            subid << " for subshape # " << anInternalSubmeshId);
2548 //                  SMESHDS_SubMesh* aSubMeshDS =
2549 //                      myNewMeshImpl->_mapSubMesh[anInternalSubmeshId]->CreateSubMeshDS();
2550 //                  if ( !aSubMeshDS ) {
2551 //                    if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): FAILED to create a submesh for subshape # " <<
2552 //                              anInternalSubmeshId << " in current mesh!");
2553 //                  }
2554 //                  else
2555 //                    myReader.GetSubMesh( aSubMeshDS, subid );
2556 //                }
2557                     
2558                   // try to get applied algorithms
2559                   if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
2560                     // open "applied algorithms" HDF group
2561                     aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
2562                     aSubSubGroup->OpenOnDisk();
2563                     // get number of applied algorithms
2564                     int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
2565                     for ( int l = 0; l < aNbSubObjects; l++ ) {
2566                       char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2567                       aSubSubGroup->InternalObjectIndentify( l, name_dataset );
2568                       // check if it is an algorithm
2569                       if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
2570                         aDataset = new HDFdataset( name_dataset, aSubSubGroup );
2571                         aDataset->OpenOnDisk();
2572                         size = aDataset->GetSize();
2573                         char* refFromFile = new char[ size ];
2574                         aDataset->ReadFromDisk( refFromFile );
2575                         aDataset->CloseOnDisk();
2576
2577                         //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2578                         //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2579                         int id = atoi( refFromFile );
2580                         string anIOR = myStudyContext->getIORbyOldId( id );
2581                         if ( !anIOR.empty() ) {
2582                           CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2583                           if ( !CORBA::is_nil( hypObject ) ) {
2584                             SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2585                             if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2586                               myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
2587                           }
2588                         }
2589                       }
2590                     }
2591                     // close "applied algorithms" HDF group
2592                     aSubSubGroup->CloseOnDisk();
2593                   }
2594                   
2595                   // try to get applied hypotheses
2596                   if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
2597                     // open "applied hypotheses" HDF group
2598                     aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
2599                     aSubSubGroup->OpenOnDisk();
2600                     // get number of applied hypotheses
2601                     int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
2602                     for ( int l = 0; l < aNbSubObjects; l++ ) {
2603                       char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2604                       aSubSubGroup->InternalObjectIndentify( l, name_dataset );
2605                       // check if it is a hypothesis
2606                       if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
2607                         aDataset = new HDFdataset( name_dataset, aSubSubGroup );
2608                         aDataset->OpenOnDisk();
2609                         size = aDataset->GetSize();
2610                         char* refFromFile = new char[ size ];
2611                         aDataset->ReadFromDisk( refFromFile );
2612                         aDataset->CloseOnDisk();
2613                         
2614                         //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2615                         //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2616                         int id = atoi( refFromFile );
2617                         string anIOR = myStudyContext->getIORbyOldId( id );
2618                         if ( !anIOR.empty() ) {
2619                           CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2620                           if ( !CORBA::is_nil( hypObject ) ) {
2621                             SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2622                             if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2623                               myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
2624                           }
2625                         }
2626                       }
2627                     }
2628                     // close "applied hypotheses" HDF group
2629                     aSubSubGroup->CloseOnDisk();
2630                   }
2631
2632                   // close submesh HDF group
2633                   aSubGroup->CloseOnDisk();
2634                 }
2635               }
2636               // close submeshes containers HDF group
2637               aGroup->CloseOnDisk();
2638             }
2639           }
2640
2641           if(hasData) {
2642             
2643             // Read sub-meshes from MED
2644             // -------------------------
2645             if(MYDEBUG) MESSAGE("Create all sub-meshes");
2646             bool submeshesInFamilies = ( ! aTopGroup->ExistInternalObject( "Submeshes" ));
2647             if ( submeshesInFamilies )
2648             {
2649               // old way working before fix of PAL 12992
2650               myReader.CreateAllSubMeshes();
2651             }
2652             else
2653             {
2654               // open a group
2655               aGroup = new HDFgroup( "Submeshes", aTopGroup ); 
2656               aGroup->OpenOnDisk();
2657
2658               int maxID = mySMESHDSMesh->MaxShapeIndex();
2659               vector< SMESHDS_SubMesh * > subMeshes( maxID + 1, (SMESHDS_SubMesh*) 0 );
2660               vector< TopAbs_ShapeEnum  > smType   ( maxID + 1, TopAbs_SHAPE ); 
2661               
2662               PositionCreator aPositionCreator;
2663
2664               SMDS_NodeIteratorPtr nIt = mySMESHDSMesh->nodesIterator();
2665               SMDS_ElemIteratorPtr eIt = mySMESHDSMesh->elementsIterator();
2666               for ( int isNode = 0; isNode < 2; ++isNode )
2667               {
2668                 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
2669                 if ( aGroup->ExistInternalObject( (char*) aDSName.c_str() ))
2670                 {
2671                   aDataset = new HDFdataset( (char*) aDSName.c_str(), aGroup );
2672                   aDataset->OpenOnDisk();
2673                   // read submesh IDs for all elements sorted by ID
2674                   int nbElems = aDataset->GetSize();
2675                   int* smIDs = new int [ nbElems ];
2676                   aDataset->ReadFromDisk( smIDs );
2677                   aDataset->CloseOnDisk();
2678
2679                   // get elements sorted by ID
2680                   ::SMESH_MeshEditor::TIDSortedElemSet elemSet;
2681                   if ( isNode )
2682                     while ( nIt->more() ) elemSet.insert( nIt->next() );
2683                   else
2684                     while ( eIt->more() ) elemSet.insert( eIt->next() );
2685                   ASSERT( elemSet.size() == nbElems );
2686
2687                   // add elements to submeshes
2688                   ::SMESH_MeshEditor::TIDSortedElemSet::iterator iE = elemSet.begin();
2689                   for ( int i = 0; i < nbElems; ++i, ++iE )
2690                   {
2691                     int smID = smIDs[ i ];
2692                     if ( smID == 0 ) continue;
2693                     ASSERT( smID <= maxID );
2694                     const SMDS_MeshElement* elem = *iE;
2695                     // get or create submesh
2696                     SMESHDS_SubMesh* & sm = subMeshes[ smID ];
2697                     if ( ! sm ) {
2698                       sm = mySMESHDSMesh->NewSubMesh( smID );
2699                       smType[ smID ] = mySMESHDSMesh->IndexToShape( smID ).ShapeType();
2700                     }
2701                     // add
2702                     if ( isNode ) {
2703                       SMDS_PositionPtr pos = aPositionCreator.MakePosition( smType[ smID ]);
2704                       pos->SetShapeId( smID );
2705                       SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>( static_cast<const SMDS_MeshNode*>( elem ));
2706                       node->SetPosition( pos );
2707                       sm->AddNode( node );
2708                     } else {
2709                       sm->AddElement( elem );
2710                     }
2711                   }
2712                   delete smIDs;
2713                 }
2714               }
2715             } // end reading submeshes
2716
2717             // Read node positions on sub-shapes (SMDS_Position)
2718
2719             if ( aTopGroup->ExistInternalObject( "Node Positions" ))
2720             {
2721               // There are 5 datasets to read:
2722               // "Nodes on Edges" - ID of node on edge
2723               // "Edge positions" - U parameter on node on edge
2724               // "Nodes on Faces" - ID of node on face
2725               // "Face U positions" - U parameter of node on face
2726               // "Face V positions" - V parameter of node on face
2727               char* aEid_DSName = "Nodes on Edges";
2728               char* aEu_DSName  = "Edge positions";
2729               char* aFu_DSName  = "Face U positions";
2730               //char* aFid_DSName = "Nodes on Faces";
2731               //char* aFv_DSName  = "Face V positions";
2732
2733               // data to retrieve
2734               int nbEids = 0, nbFids = 0;
2735               int *aEids = 0, *aFids  = 0;
2736               double *aEpos = 0, *aFupos = 0, *aFvpos = 0;
2737
2738               // open a group
2739               aGroup = new HDFgroup( "Node Positions", aTopGroup ); 
2740               aGroup->OpenOnDisk();
2741
2742               // loop on 5 data sets
2743               int aNbObjects = aGroup->nInternalObjects();
2744               for ( int i = 0; i < aNbObjects; i++ )
2745               {
2746                 // identify dataset
2747                 char aDSName[ HDF_NAME_MAX_LEN+1 ];
2748                 aGroup->InternalObjectIndentify( i, aDSName );
2749                 // read data
2750                 aDataset = new HDFdataset( aDSName, aGroup );
2751                 aDataset->OpenOnDisk();
2752                 if ( aDataset->GetType() == HDF_FLOAT64 ) // Positions
2753                 {
2754                   double* pos = new double [ aDataset->GetSize() ];
2755                   aDataset->ReadFromDisk( pos );
2756                   // which one?
2757                   if ( strncmp( aDSName, aEu_DSName, strlen( aEu_DSName )) == 0 )
2758                     aEpos = pos;
2759                   else if ( strncmp( aDSName, aFu_DSName, strlen( aFu_DSName )) == 0 )
2760                     aFupos = pos;
2761                   else
2762                     aFvpos = pos;
2763                 }
2764                 else // NODE IDS
2765                 {
2766                   int aSize = aDataset->GetSize();
2767
2768                   // for reading files, created from 18.07.2005 till 10.10.2005
2769                   if (aDataset->GetType() == HDF_STRING)
2770                     aSize /= sizeof(int);
2771
2772                   int* ids = new int [aSize];
2773                   aDataset->ReadFromDisk( ids );
2774                   // on face or nodes?
2775                   if ( strncmp( aDSName, aEid_DSName, strlen( aEid_DSName )) == 0 ) {
2776                     aEids = ids;
2777                     nbEids = aSize;
2778                   }
2779                   else {
2780                     aFids = ids;
2781                     nbFids = aSize;
2782                   }
2783                 }
2784                 aDataset->CloseOnDisk();
2785               } // loop on 5 datasets
2786
2787               // Set node positions on edges or faces
2788               for ( int onFace = 0; onFace < 2; onFace++ )
2789               {
2790                 int nbNodes = ( onFace ? nbFids : nbEids );
2791                 if ( nbNodes == 0 ) continue;
2792                 int* aNodeIDs = ( onFace ? aFids : aEids );
2793                 double* aUPos = ( onFace ? aFupos : aEpos );
2794                 double* aVPos = ( onFace ? aFvpos : 0 );
2795                 // loop on node IDs
2796                 for ( int iNode = 0; iNode < nbNodes; iNode++ )
2797                 {
2798                   const SMDS_MeshNode* node = mySMESHDSMesh->FindNode( aNodeIDs[ iNode ]);
2799                   ASSERT( node );
2800                   SMDS_PositionPtr aPos = node->GetPosition();
2801                   ASSERT( aPos )
2802                   if ( onFace ) {
2803                     ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_FACE );
2804                     SMDS_FacePosition* fPos = const_cast<SMDS_FacePosition*>
2805                       ( static_cast<const SMDS_FacePosition*>( aPos.get() ));
2806                     fPos->SetUParameter( aUPos[ iNode ]);
2807                     fPos->SetVParameter( aVPos[ iNode ]);
2808                   }
2809                   else {
2810                     ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE );
2811                     SMDS_EdgePosition* fPos = const_cast<SMDS_EdgePosition*>
2812                       ( static_cast<const SMDS_EdgePosition*>( aPos.get() ));
2813                     fPos->SetUParameter( aUPos[ iNode ]);
2814                   }
2815                 }
2816               }
2817               if ( aEids ) delete [] aEids;
2818               if ( aFids ) delete [] aFids;
2819               if ( aEpos ) delete [] aEpos;
2820               if ( aFupos ) delete [] aFupos;
2821               if ( aFvpos ) delete [] aFvpos;
2822               
2823               aGroup->CloseOnDisk();
2824
2825             } // if ( aTopGroup->ExistInternalObject( "Node Positions" ) )
2826           } // if ( hasData )
2827
2828           // Recompute State (as computed sub-meshes are restored from MED)
2829           if ( !aShapeObject->_is_nil() ) {
2830             MESSAGE("Compute State Engine ...");
2831             TopoDS_Shape myLocShape = GeomObjectToShape( aShapeObject );
2832             myNewMeshImpl->GetImpl().GetSubMesh(myLocShape)->ComputeStateEngine
2833               (SMESH_subMesh::SUBMESH_RESTORED);
2834             MESSAGE("Compute State Engine finished");
2835           }
2836
2837           // try to get groups
2838           for ( int ii = GetNodeGroupsTag(); ii <= GetVolumeGroupsTag(); ii++ ) {
2839             char name_group[ 30 ];
2840             if ( ii == GetNodeGroupsTag() )
2841               strcpy( name_group, "Groups of Nodes" );
2842             else if ( ii == GetEdgeGroupsTag() )
2843               strcpy( name_group, "Groups of Edges" );
2844             else if ( ii == GetFaceGroupsTag() )
2845               strcpy( name_group, "Groups of Faces" );
2846             else if ( ii == GetVolumeGroupsTag() )
2847               strcpy( name_group, "Groups of Volumes" );
2848
2849             if ( aTopGroup->ExistInternalObject( name_group ) ) {
2850               aGroup = new HDFgroup( name_group, aTopGroup );
2851               aGroup->OpenOnDisk();
2852               // get number of groups
2853               int aNbSubObjects = aGroup->nInternalObjects(); 
2854               for ( int j = 0; j < aNbSubObjects; j++ ) {
2855                 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2856                 aGroup->InternalObjectIndentify( j, name_dataset );
2857                 // check if it is an group
2858                 if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
2859                   // --> get group id
2860                   int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
2861                   if ( subid <= 0 )
2862                     continue;
2863                   aDataset = new HDFdataset( name_dataset, aGroup );
2864                   aDataset->OpenOnDisk();
2865
2866                   // Retrieve actual group name
2867                   size = aDataset->GetSize();
2868                   char* nameFromFile = new char[ size ];
2869                   aDataset->ReadFromDisk( nameFromFile );
2870                   aDataset->CloseOnDisk();
2871
2872                   // Try to find a shape reference
2873                   TopoDS_Shape aShape;
2874                   char aRefName[ 30 ];
2875                   sprintf( aRefName, "Ref on shape %d", subid);
2876                   if ( aGroup->ExistInternalObject( aRefName ) ) {
2877                     // load mesh "Ref on shape" - it's an entry to SObject
2878                     aDataset = new HDFdataset( aRefName, aGroup );
2879                     aDataset->OpenOnDisk();
2880                     size = aDataset->GetSize();
2881                     char* refFromFile = new char[ size ];
2882                     aDataset->ReadFromDisk( refFromFile );
2883                     aDataset->CloseOnDisk();
2884                     if ( strlen( refFromFile ) > 0 ) {
2885                       SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
2886                       CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
2887                       if ( !CORBA::is_nil( shapeObject ) ) {
2888                         aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
2889                         if ( !aShapeObject->_is_nil() )
2890                           aShape = GeomObjectToShape( aShapeObject );
2891                       }
2892                     }
2893                   }
2894                   // Create group servant
2895                   SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
2896                   SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
2897                     ( myNewMeshImpl->createGroup( type, nameFromFile, aShape ) );
2898                   // Obtain a SMESHDS_Group object 
2899                   if ( aNewGroup->_is_nil() )
2900                     continue;
2901
2902                   string iorSubString = GetORB()->object_to_string( aNewGroup );
2903                   int newSubId = myStudyContext->findId( iorSubString );
2904                   myStudyContext->mapOldToNew( subid, newSubId );
2905
2906                   SMESH_GroupBase_i* aGroupImpl =
2907                     dynamic_cast<SMESH_GroupBase_i*>( GetServant( aNewGroup ).in() );
2908                   if ( !aGroupImpl )
2909                     continue;
2910
2911                   SMESH_Group* aLocalGroup  = myLocMesh.GetGroup( aGroupImpl->GetLocalID() );
2912                   if ( !aLocalGroup )
2913                     continue;
2914
2915                   SMESHDS_GroupBase* aGroupBaseDS = aLocalGroup->GetGroupDS();
2916                   aGroupBaseDS->SetStoreName( name_dataset );
2917
2918                   // Fill group with contents from MED file
2919                   SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
2920                   if ( aGrp )
2921                     myReader.GetGroup( aGrp );
2922                 }
2923               }
2924               aGroup->CloseOnDisk();
2925             }
2926           }
2927         }
2928         // close mesh group
2929         aTopGroup->CloseOnDisk();       
2930       }
2931     }
2932   }
2933   // close HDF file
2934   aFile->CloseOnDisk();
2935   delete aFile;
2936
2937   // Remove temporary files created from the stream
2938   if ( !isMultiFile ) 
2939     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
2940
2941   INFOS( "SMESH_Gen_i::Load completed" );
2942   return true;
2943 }
2944
2945 //=============================================================================
2946 /*!
2947  *  SMESH_Gen_i::LoadASCII
2948  *
2949  *  Load SMESH module's data in ASCII format (not implemented yet)
2950  */
2951 //=============================================================================
2952
2953 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
2954                              const SALOMEDS::TMPFile& theStream,
2955                              const char*              theURL,
2956                              bool                     isMultiFile ) {
2957   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
2958   return Load( theComponent, theStream, theURL, isMultiFile );
2959 }
2960
2961 //=============================================================================
2962 /*!
2963  *  SMESH_Gen_i::Close
2964  *
2965  *  Clears study-connected data when it is closed
2966  */
2967 //=============================================================================
2968
2969 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
2970 {
2971   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
2972
2973   // Clear study contexts data
2974   int studyId = GetCurrentStudyID();
2975   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
2976     delete myStudyContextMap[ studyId ];
2977     myStudyContextMap.erase( studyId );
2978   }
2979   return;
2980 }
2981
2982 //=============================================================================
2983 /*!
2984  *  SMESH_Gen_i::ComponentDataType
2985  * 
2986  *  Get component data type
2987  */
2988 //=============================================================================
2989
2990 char* SMESH_Gen_i::ComponentDataType()
2991 {
2992   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
2993   return CORBA::string_dup( "SMESH" );
2994 }
2995
2996     
2997 //=============================================================================
2998 /*!
2999  *  SMESH_Gen_i::IORToLocalPersistentID
3000  *  
3001  *  Transform data from transient form to persistent
3002  */
3003 //=============================================================================
3004
3005 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
3006                                            const char*           IORString,
3007                                            CORBA::Boolean        /*isMultiFile*/,
3008                                            CORBA::Boolean        /*isASCII*/ )
3009 {
3010   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
3011   StudyContext* myStudyContext = GetCurrentStudyContext();
3012   
3013   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
3014     int anId = myStudyContext->findId( IORString );
3015     if ( anId ) {
3016       if(MYDEBUG) MESSAGE( "VSR " << anId )
3017       char strId[ 20 ];
3018       sprintf( strId, "%d", anId );
3019       return  CORBA::string_dup( strId );
3020     }
3021   }
3022   return CORBA::string_dup( "" );
3023 }
3024
3025 //=============================================================================
3026 /*!
3027  *  SMESH_Gen_i::LocalPersistentIDToIOR
3028  *
3029  *  Transform data from persistent form to transient
3030  */
3031 //=============================================================================
3032
3033 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
3034                                            const char*           aLocalPersistentID,
3035                                            CORBA::Boolean        /*isMultiFile*/,
3036                                            CORBA::Boolean        /*isASCII*/ )
3037 {
3038   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
3039   StudyContext* myStudyContext = GetCurrentStudyContext();
3040
3041   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
3042     int anId = atoi( aLocalPersistentID );
3043     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
3044   }
3045   return CORBA::string_dup( "" );
3046 }
3047
3048 //=======================================================================
3049 //function : RegisterObject
3050 //purpose  : 
3051 //=======================================================================
3052
3053 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
3054 {
3055   StudyContext* myStudyContext = GetCurrentStudyContext();
3056   if ( myStudyContext && !CORBA::is_nil( theObject )) {
3057     string iorString = GetORB()->object_to_string( theObject );
3058     return myStudyContext->addObject( iorString );
3059   }
3060   return 0;
3061 }
3062       
3063 //=============================================================================
3064 /*! 
3065  *  SMESHEngine_factory
3066  *
3067  *  C factory, accessible with dlsym, after dlopen  
3068  */
3069 //=============================================================================
3070
3071 extern "C"
3072 {
3073   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
3074                                                  PortableServer::POA_ptr   poa, 
3075                                                  PortableServer::ObjectId* contId,
3076                                                  const char*               instanceName, 
3077                                                  const char*               interfaceName )
3078   {
3079     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
3080     if(MYDEBUG) SCRUTE(interfaceName);
3081     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
3082     return aSMESHGen->getId() ;
3083   }
3084 }