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