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