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