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