Salome HOME
PAL8581. Really check smoothing
[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.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org 
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 <gp_Pnt.hxx>
45 #include <BRep_Tool.hxx>
46 #include <TCollection_AsciiString.hxx>
47
48 #include "Utils_CorbaException.hxx"
49
50 #include "utilities.h"
51 #include <fstream>
52 #include <stdio.h>
53 #include <dlfcn.h>
54
55 #include <HDFOI.hxx>
56
57 #include "SMESH_Gen_i.hxx"
58 #include "SMESH_Mesh_i.hxx"
59 #include "SMESH_Hypothesis_i.hxx"
60 #include "SMESH_Algo_i.hxx"
61 #include "SMESH_Group_i.hxx"
62
63 #include "SMESHDS_Document.hxx"
64 #include "SMESHDS_Group.hxx"
65 #include "SMESHDS_GroupOnGeom.hxx"
66 #include "SMESH_Group.hxx"
67
68 #include "SMDS_EdgePosition.hxx"
69 #include "SMDS_FacePosition.hxx"
70
71 #include CORBA_SERVER_HEADER(SMESH_Group)
72 #include CORBA_SERVER_HEADER(SMESH_Filter)
73
74 #include "DriverMED_W_SMESHDS_Mesh.h"
75 #include "DriverMED_R_SMESHDS_Mesh.h"
76
77 #include "SALOMEDS_Tool.hxx"
78 #include "SALOME_NamingService.hxx"
79 #include "SALOME_LifeCycleCORBA.hxx"
80 #include "Utils_SINGLETON.hxx"
81 #include "OpUtil.hxx"
82
83 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
84
85 #include "GEOM_Client.hxx"
86 #include "Utils_ExceptHandlers.hxx"
87
88 #include <map>
89 #include <boost/filesystem/path.hpp>
90
91 using namespace std;
92
93 #define NUM_TMP_FILES 2
94
95 #ifdef _DEBUG_
96 static int MYDEBUG = 0;
97 #else
98 static int MYDEBUG = 0;
99 #endif
100
101 // Static variables definition
102 CORBA::ORB_var          SMESH_Gen_i::myOrb;
103 PortableServer::POA_var SMESH_Gen_i::myPoa;
104 SALOME_NamingService*   SMESH_Gen_i::myNS  = NULL;
105 SALOME_LifeCycleCORBA*  SMESH_Gen_i::myLCC = NULL;
106 SMESH_Gen_i*            SMESH_Gen_i::mySMESHGen = NULL;
107
108 //=============================================================================
109 /*!
110  *  GetServant [ static ]
111  *
112  *  Get servant of the CORBA object
113  */
114 //=============================================================================
115
116 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
117 {
118   if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
119     return NULL;
120   try {
121     PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
122     return aServant;
123   } 
124   catch (...) {
125     INFOS( "GetServant - Unknown exception was caught!!!" ); 
126     return NULL;
127   }
128 }
129
130 //=============================================================================
131 /*!
132  *  SObjectToObject [ static ]
133  *
134  *  Get CORBA object corresponding to the SALOMEDS::SObject
135  */
136 //=============================================================================
137
138 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
139 {
140   SALOMEDS::GenericAttribute_var anAttr;
141   CORBA::Object_var anObj;
142   if ( !theSObject->_is_nil() ) {
143     try {
144       if( theSObject->FindAttribute( anAttr, "AttributeIOR" ) ) {
145         SALOMEDS::AttributeIOR_var anIOR  = SALOMEDS::AttributeIOR::_narrow( anAttr );
146         CORBA::String_var aValue = anIOR->Value();
147         if( strcmp( aValue, "" ) != 0 )
148           anObj = GetORB()->string_to_object( aValue );
149         }
150     }
151     catch( ... ) {
152       INFOS( "SObjectToObject - Unknown exception was caught!!!" );
153     }
154   }
155   return anObj;
156 }
157
158 //=============================================================================
159 /*!
160  *  GetNS [ static ]
161  *
162  *  Get SALOME_NamingService object 
163  */
164 //=============================================================================
165
166 SALOME_NamingService* SMESH_Gen_i::GetNS()
167 {
168   if ( myNS == NULL ) {
169     myNS = SINGLETON_<SALOME_NamingService>::Instance();
170     ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
171     myNS->init_orb( GetORB() );
172   }
173   return myNS;
174 }
175
176 //=============================================================================
177 /*!
178  *  GetLCC [ static ]
179  *
180  *  Get SALOME_LifeCycleCORBA object
181  */
182 //=============================================================================     
183 SALOME_LifeCycleCORBA*  SMESH_Gen_i::GetLCC() {
184   if ( myLCC == NULL ) {
185     myLCC = new SALOME_LifeCycleCORBA( GetNS() );
186   }
187   return myLCC;
188 }
189
190
191 //=============================================================================
192 /*!
193  *  GetGeomEngine [ static ]
194  *
195  *  Get GEOM::GEOM_Gen reference
196  */
197 //=============================================================================     
198 GEOM::GEOM_Gen_ptr SMESH_Gen_i::GetGeomEngine() {
199   GEOM::GEOM_Gen_var aGeomEngine =
200     GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
201   return aGeomEngine._retn();
202 }
203
204 //=============================================================================
205 /*!
206  *  SMESH_Gen_i::SMESH_Gen_i
207  *
208  *  Default constructor: not for use
209  */
210 //=============================================================================
211
212 SMESH_Gen_i::SMESH_Gen_i()
213 {
214   INFOS( "SMESH_Gen_i::SMESH_Gen_i : default constructor" );
215 }
216
217 //=============================================================================
218 /*!
219  *  SMESH_Gen_i::SMESH_Gen_i 
220  *
221  *  Standard constructor, used with Container
222  */
223 //=============================================================================
224
225 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr            orb,
226                           PortableServer::POA_ptr   poa,
227                           PortableServer::ObjectId* contId, 
228                           const char*               instanceName, 
229                           const char*               interfaceName )
230      : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
231 {
232   INFOS( "SMESH_Gen_i::SMESH_Gen_i : standard constructor" );
233
234   myOrb = CORBA::ORB::_duplicate(orb);
235   myPoa = PortableServer::POA::_duplicate(poa);
236   
237   _thisObj = this ;
238   _id = myPoa->activate_object( _thisObj );
239   
240   myShapeReader = NULL;  // shape reader
241   mySMESHGen = this;
242 }
243
244 //=============================================================================
245 /*!
246  *  SMESH_Gen_i::~SMESH_Gen_i
247  *
248  *  Destructor
249  */
250 //=============================================================================
251
252 SMESH_Gen_i::~SMESH_Gen_i()
253 {
254   INFOS( "SMESH_Gen_i::~SMESH_Gen_i" );
255
256   // delete hypothesis creators
257   map<string, GenericHypothesisCreator_i*>::iterator itHyp;
258   for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
259   {
260     delete (*itHyp).second;
261   }
262   myHypCreatorMap.clear();
263
264   // Clear study contexts data
265   map<int, StudyContext*>::iterator it;
266   for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
267     delete it->second;
268   }
269   myStudyContextMap.clear();
270   // delete shape reader
271   if ( !myShapeReader ) 
272     delete myShapeReader;
273 }
274   
275 //=============================================================================
276 /*!
277  *  SMESH_Gen_i::createHypothesis
278  *
279  *  Create hypothesis of given type
280  */
281 //=============================================================================
282 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
283                                                           const char* theLibName)
284      throw (SALOME::SALOME_Exception)
285 {
286   Unexpect aCatch(SALOME_SalomeException);
287   if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << theLibName);
288
289   // create a new hypothesis object servant
290   SMESH_Hypothesis_i* myHypothesis_i = 0;
291   SMESH::SMESH_Hypothesis_var hypothesis_i;
292
293   try
294   {
295     // check, if creator for this hypothesis type already exists
296     if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
297     {
298       // load plugin library
299       if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
300       void* libHandle = dlopen (theLibName, RTLD_LAZY);
301       if (!libHandle)
302       {
303         // report any error, if occured
304         const char* anError = dlerror();
305         throw(SALOME_Exception(anError));
306       }
307
308       // get method, returning hypothesis creator
309       if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
310       typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* theHypName);
311       GetHypothesisCreator procHandle =
312         (GetHypothesisCreator)dlsym( libHandle, "GetHypothesisCreator" );
313       if (!procHandle)
314       {
315         throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
316         dlclose(libHandle);
317       }
318
319       // get hypothesis creator
320       if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
321       GenericHypothesisCreator_i* aCreator = procHandle(theHypName);
322       if (!aCreator)
323       {
324         throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
325       }
326
327       // map hypothesis creator to a hypothesis name
328       myHypCreatorMap[string(theHypName)] = aCreator;
329     }
330
331     // create a new hypothesis object, store its ref. in studyContext
332     if(MYDEBUG) MESSAGE("Create Hypothesis " << theHypName);
333     myHypothesis_i =
334       myHypCreatorMap[string(theHypName)]->Create (myPoa, GetCurrentStudyID(), &myGen);
335     // _CS_gbo Explicit activation (no longer made in the constructor).
336     myHypothesis_i->Activate();
337     myHypothesis_i->SetLibName(theLibName); // for persistency assurance
338   }
339   catch (SALOME_Exception& S_ex)
340   {
341     THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
342   }
343
344   if (!myHypothesis_i)
345     return hypothesis_i._retn();
346
347   // activate the CORBA servant of hypothesis
348   hypothesis_i = SMESH::SMESH_Hypothesis::_narrow( myHypothesis_i->_this() );
349   int nextId = RegisterObject( hypothesis_i );
350   if(MYDEBUG) MESSAGE( "Add hypo to map with id = "<< nextId );
351
352   return hypothesis_i._retn();
353 }
354   
355 //=============================================================================
356 /*!
357  *  SMESH_Gen_i::createMesh
358  *
359  *  Create empty mesh on shape
360  */
361 //=============================================================================
362 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
363      throw ( SALOME::SALOME_Exception )
364 {
365   Unexpect aCatch(SALOME_SalomeException);
366   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
367
368   // Get or create the GEOM_Client instance
369   try {
370     // create a new mesh object servant, store it in a map in study context
371     SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
372     // create a new mesh object
373     meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID() ));
374
375     // activate the CORBA servant of Mesh
376     SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
377     int nextId = RegisterObject( mesh );
378     if(MYDEBUG) MESSAGE( "Add mesh to map with id = "<< nextId);
379     return mesh._retn();
380   }
381   catch (SALOME_Exception& S_ex) {
382     THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
383   }
384   return SMESH::SMESH_Mesh::_nil();
385 }
386
387 //=============================================================================
388 /*!
389  *  SMESH_Gen_i::GetShapeReader
390  *
391  *  Get shape reader
392  */
393 //=============================================================================
394 GEOM_Client* SMESH_Gen_i::GetShapeReader()
395 {
396   // create shape reader if necessary
397   if ( !myShapeReader ) 
398     myShapeReader = new GEOM_Client(GetContainerRef());
399   ASSERT( myShapeReader );
400   return myShapeReader;
401 }
402
403 //=============================================================================
404 /*!
405  *  SMESH_Gen_i::SetCurrentStudy
406  *
407  *  Set current study
408  */
409 //=============================================================================
410
411 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
412 {
413   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SetCurrentStudy" );
414   myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
415   // create study context, if it doesn't exist and set current study
416   int studyId = GetCurrentStudyID();
417   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SetCurrentStudy: study Id = " << studyId );
418   if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() ) {
419     myStudyContextMap[ studyId ] = new StudyContext;      
420   }
421   // set current study for geom engine
422   /*
423   if ( !CORBA::is_nil( GetGeomEngine() ) )
424     GetGeomEngine()->GetCurrentStudy( myCurrentStudy->StudyId() );
425   */
426 }
427
428 //=============================================================================
429 /*!
430  *  SMESH_Gen_i::GetCurrentStudy
431  *
432  *  Get current study
433  */
434 //=============================================================================
435
436 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
437 {
438   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
439   return SALOMEDS::Study::_duplicate( myCurrentStudy );
440 }
441
442 //=============================================================================
443 /*!
444  *  SMESH_Gen_i::GetCurrentStudyContext 
445  *
446  *  Get current study context
447  */
448 //=============================================================================
449 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
450 {
451   if ( !CORBA::is_nil( myCurrentStudy ) &&
452       myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
453     return myStudyContextMap[ myCurrentStudy->StudyId() ];
454   else
455     return 0;
456 }
457
458 //=============================================================================
459 /*!
460  *  SMESH_Gen_i::CreateHypothesis 
461  *
462  *  Create hypothesis/algorothm of given type and publish it in the study
463  */
464 //=============================================================================
465
466 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
467                                                            const char* theLibName )
468      throw ( SALOME::SALOME_Exception )
469 {
470   Unexpect aCatch(SALOME_SalomeException);
471   // Create hypothesis/algorithm
472   SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
473
474   // Publish hypothesis/algorithm in the study
475   if ( CanPublishInStudy( hyp ) ) {
476     SALOMEDS::SObject_var aSO = PublishHypothesis( myCurrentStudy, hyp );
477     if ( !aSO->_is_nil() ) {
478       // Update Python script
479       TCollection_AsciiString aStr (aSO->GetID());
480       aStr += " = smesh.CreateHypothesis(\"";
481       aStr += Standard_CString(theHypName);
482       aStr += "\", \"";
483       aStr += Standard_CString(theLibName);
484       aStr += "\")";
485
486       AddToCurrentPyScript(aStr);
487     }
488   }
489
490   return hyp._retn();
491 }
492
493 //=============================================================================
494 /*!
495  *  SMESH_Gen_i::CreateMesh
496  *
497  *  Create empty mesh on a shape and publish it in the study
498  */
499 //=============================================================================
500
501 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
502      throw ( SALOME::SALOME_Exception )
503 {
504   Unexpect aCatch(SALOME_SalomeException);
505   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
506   // create mesh
507   SMESH::SMESH_Mesh_var mesh = this->createMesh();
508   // set shape
509   SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
510   ASSERT( meshServant );
511   meshServant->SetShape( theShapeObject );
512
513   // publish mesh in the study
514   if ( CanPublishInStudy( mesh ) ) {
515     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, mesh.in() );
516     if ( !aSO->_is_nil() ) {
517       // Update Python script
518       TCollection_AsciiString aStr (aSO->GetID());
519       aStr += " = smesh.CreateMesh(";
520       SMESH_Gen_i::AddObject(aStr, theShapeObject) += ")";
521       
522       AddToCurrentPyScript(aStr);
523     }
524   }
525
526   return mesh._retn();
527 }
528
529 //=============================================================================
530 /*!
531  *  SMESH_Gen_i::CreateMeshFromUNV
532  *
533  *  Create mesh and import data from UNV file
534  */
535 //=============================================================================
536
537 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
538   throw ( SALOME::SALOME_Exception )
539 {
540   Unexpect aCatch(SALOME_SalomeException);
541   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromUNV" );
542
543   SMESH::SMESH_Mesh_var aMesh = createMesh();
544   string aFileName; // = boost::filesystem::path(theFileName).leaf();
545   // publish mesh in the study
546   if ( CanPublishInStudy( aMesh ) ) {
547     SALOMEDS::SObject_var aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
548     if ( !aSO->_is_nil() ) {
549       // Update Python script
550       TCollection_AsciiString aStr (aSO->GetID());
551       aStr += " = smesh.CreateMeshesFromUNV(\"";
552       aStr += Standard_CString(theFileName);
553       aStr += "\")";
554
555       AddToCurrentPyScript(aStr);
556     }
557   }
558
559   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
560   ASSERT( aServant );
561   aServant->ImportUNVFile( theFileName );
562   return aMesh._retn();
563 }
564
565 //=============================================================================
566 /*!
567  *  SMESH_Gen_i::CreateMeshFromMED
568  *
569  *  Create mesh and import data from MED file
570  */
571 //=============================================================================
572
573 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
574                                                      SMESH::DriverMED_ReadStatus& theStatus)
575      throw ( SALOME::SALOME_Exception )
576 {
577   Unexpect aCatch(SALOME_SalomeException);
578   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshFromMED" );
579
580   // Python Dump
581   TCollection_AsciiString aStr ("([");
582
583   // Retrieve mesh names from the file
584   DriverMED_R_SMESHDS_Mesh myReader;
585   myReader.SetFile( theFileName );
586   myReader.SetMeshId( -1 );
587   Driver_Mesh::Status aStatus;
588   list<string> aNames = myReader.GetMeshNames(aStatus);
589   SMESH::mesh_array_var aResult = new SMESH::mesh_array();
590   theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
591   if (theStatus == SMESH::DRS_OK) {
592     aResult->length( aNames.size() );
593     int i = 0;
594     
595     // Iterate through all meshes and create mesh objects
596     for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ ) {
597       // Python Dump
598       if (i > 0) aStr += ", ";
599
600       // create mesh
601       SMESH::SMESH_Mesh_var mesh = createMesh();
602       
603       // publish mesh in the study
604       SALOMEDS::SObject_var aSO;
605       if ( CanPublishInStudy( mesh ) )
606         aSO = PublishMesh( myCurrentStudy, mesh.in(), (*it).c_str() );
607       if ( !aSO->_is_nil() ) {
608         // Python Dump
609         aStr += aSO->GetID();
610       } else {
611         // Python Dump
612         aStr += "mesh_";
613         aStr += TCollection_AsciiString(i);
614       }
615
616       // Read mesh data (groups are published automatically by ImportMEDFile())
617       SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
618       ASSERT( meshServant );
619       SMESH::DriverMED_ReadStatus status1 =
620         meshServant->ImportMEDFile( theFileName, (*it).c_str() );
621       if (status1 > theStatus)
622         theStatus = status1;
623
624       aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
625     }
626   }
627
628   // Update Python script
629   aStr += "], status) = smesh.CreateMeshesFromMED(\"";
630   aStr += Standard_CString(theFileName);
631   aStr += "\")";
632
633   AddToCurrentPyScript(aStr);
634
635   return aResult._retn();
636 }
637
638 //=============================================================================
639 /*!
640  *  SMESH_Gen_i::CreateMeshFromSTL
641  *
642  *  Create mesh and import data from STL file
643  */
644 //=============================================================================
645
646 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
647   throw ( SALOME::SALOME_Exception )
648 {
649   Unexpect aCatch(SALOME_SalomeException);
650   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMeshesFromSTL" );
651
652   SMESH::SMESH_Mesh_var aMesh = createMesh();
653   string aFileName; // = boost::filesystem::path(theFileName).leaf();
654   // publish mesh in the study
655   if ( CanPublishInStudy( aMesh ) ) {
656     SALOMEDS::SObject_var aSO = PublishInStudy
657       ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
658     if ( !aSO->_is_nil() ) {
659     // Update Python script
660       TCollection_AsciiString aStr (aSO->GetID());
661       aStr += " = smesh.CreateMeshesFromSTL(\"";
662       aStr += Standard_CString(theFileName);
663       aStr += "\")";
664
665       AddToCurrentPyScript(aStr);
666     }
667   }
668
669   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
670   ASSERT( aServant );
671   aServant->ImportSTLFile( theFileName );
672   return aMesh._retn();
673 }
674
675 //=============================================================================
676 /*!
677  *  SMESH_Gen_i::IsReadyToCompute
678  *
679  *  Returns true if mesh contains enough data to be computed
680  */
681 //=============================================================================
682
683 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
684                                               GEOM::GEOM_Object_ptr theShapeObject )
685   throw ( SALOME::SALOME_Exception )
686 {
687   Unexpect aCatch(SALOME_SalomeException);
688   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
689
690   if ( CORBA::is_nil( theShapeObject ) )
691     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
692                                   SALOME::BAD_PARAM );
693
694   if ( CORBA::is_nil( theMesh ) )
695     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
696                                   SALOME::BAD_PARAM );
697
698   try {
699     // get mesh servant
700     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
701     ASSERT( meshServant );
702     if ( meshServant ) {
703       // get local TopoDS_Shape
704       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
705       // call implementation
706       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
707       return myGen.CheckAlgoState( myLocMesh, myLocShape );
708     }
709   }
710   catch ( SALOME_Exception& S_ex ) {
711     INFOS( "catch exception "<< S_ex.what() );
712   }
713   return false;
714 }
715
716 //=============================================================================
717 /*!
718  *  SMESH_Gen_i::GetSubShapesId
719  *
720  *  Get sub-shapes unique ID's list
721  */
722 //=============================================================================
723
724 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
725                                             const SMESH::object_array& theListOfSubShapeObject )
726      throw ( SALOME::SALOME_Exception )
727 {
728   Unexpect aCatch(SALOME_SalomeException);
729   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
730
731   SMESH::long_array_var shapesId = new SMESH::long_array;
732   set<int> setId;
733
734   if ( CORBA::is_nil( theMainShapeObject ) )
735     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
736                                   SALOME::BAD_PARAM );
737
738   try
739     {
740       TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
741       TopTools_IndexedMapOfShape myIndexToShape;      
742       TopExp::MapShapes(myMainShape,myIndexToShape);
743
744       for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
745         {
746           GEOM::GEOM_Object_var aShapeObject
747             = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
748           if ( CORBA::is_nil( aShapeObject ) )
749             THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
750                                         SALOME::BAD_PARAM );
751
752           TopoDS_Shape locShape  = GeomObjectToShape(aShapeObject);
753           for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
754             {
755               const TopoDS_Face& F = TopoDS::Face(exp.Current());
756               setId.insert(myIndexToShape.FindIndex(F));
757               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
758             }
759           for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
760             {
761               const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
762               setId.insert(myIndexToShape.FindIndex(E));
763               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
764             }
765           for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
766             {
767               const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
768               setId.insert(myIndexToShape.FindIndex(V));
769               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
770             }
771         }
772       shapesId->length(setId.size());
773       set<int>::iterator iind;
774       int i=0;
775       for (iind = setId.begin(); iind != setId.end(); iind++)
776         {
777           if(MYDEBUG) SCRUTE((*iind));
778           shapesId[i] = (*iind);
779           if(MYDEBUG) SCRUTE(shapesId[i]);
780           i++;
781         }
782     }
783   catch (SALOME_Exception& S_ex)
784     {
785       THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
786     }
787
788   return shapesId._retn();
789 }
790
791 //=============================================================================
792 /*!
793  *  SMESH_Gen_i::Compute
794  *
795  *  Compute mesh on a shape
796  */
797 //=============================================================================
798
799 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
800                                      GEOM::GEOM_Object_ptr theShapeObject )
801      throw ( SALOME::SALOME_Exception )
802 {
803   Unexpect aCatch(SALOME_SalomeException);
804   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
805
806   if ( CORBA::is_nil( theShapeObject ) )
807     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", 
808                                   SALOME::BAD_PARAM );
809
810   if ( CORBA::is_nil( theMesh ) )
811     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
812                                   SALOME::BAD_PARAM );
813
814   // Update Python script
815   TCollection_AsciiString aStr ("isDone = smesh.Compute(");
816   SMESH_Gen_i::AddObject(aStr, theMesh) += ", ";
817   SMESH_Gen_i::AddObject(aStr, theShapeObject) += ")";
818
819   AddToCurrentPyScript(aStr);
820
821   aStr = "if isDone == 0: print \"Mesh ";
822   SMESH_Gen_i::AddObject(aStr, theMesh) += " computation failed\"";
823   AddToCurrentPyScript(aStr);
824
825   try {
826     // get mesh servant
827     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
828     ASSERT( meshServant );
829     if ( meshServant ) {
830       // get local TopoDS_Shape
831       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
832       // call implementation compute
833       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
834       return myGen.Compute( myLocMesh, myLocShape);
835     }
836   }
837   catch ( SALOME_Exception& S_ex ) {
838     INFOS( "Compute(): catch exception "<< S_ex.what() );
839   }
840   catch ( ... ) {
841     INFOS( "Compute(): unknown exception " );
842   }
843   return false;
844 }
845
846 //=============================================================================
847 /*!
848  *  SMESH_Gen_i::Save
849  *
850  *  Save SMESH module's data
851  */
852 //=============================================================================
853 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
854                                       const char*              theURL,
855                                       bool                     isMultiFile )
856 {
857   INFOS( "SMESH_Gen_i::Save" );
858
859 //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
860   // san -- in case <myCurrentStudy> differs from theComponent's study,
861   // use that of the component
862   if ( myCurrentStudy->_is_nil() || 
863        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
864     SetCurrentStudy( theComponent->GetStudy() );
865
866   // Store study contents as a set of python commands
867   SavePython(myCurrentStudy);
868
869   StudyContext* myStudyContext = GetCurrentStudyContext();
870   
871   // Declare a byte stream
872   SALOMEDS::TMPFile_var aStreamFile;
873   
874   // Obtain a temporary dir
875   TCollection_AsciiString tmpDir =
876     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
877
878   // Create a sequence of files processed
879   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
880   aFileSeq->length( NUM_TMP_FILES );
881
882   TCollection_AsciiString aStudyName( "" );
883   if ( isMultiFile ) 
884     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
885
886   // Set names of temporary files
887   TCollection_AsciiString filename =
888     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
889   TCollection_AsciiString meshfile =
890     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
891   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
892   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
893   filename = tmpDir + filename;
894   meshfile = tmpDir + meshfile;
895
896   HDFfile*    aFile;
897   HDFdataset* aDataset;
898   HDFgroup*   aTopGroup;
899   HDFgroup*   aGroup;
900   HDFgroup*   aSubGroup;
901   HDFgroup*   aSubSubGroup;
902   hdf_size    aSize[ 1 ];
903
904   // MED writer to be used by storage process
905   DriverMED_W_SMESHDS_Mesh myWriter;
906   myWriter.SetFile( meshfile.ToCString() );
907
908   // Write data
909   // ---> create HDF file
910   aFile = new HDFfile( filename.ToCString() );
911   aFile->CreateOnDisk();
912   
913   // --> iterator for top-level objects
914   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
915   for ( ; itBig->More(); itBig->Next() ) {
916     SALOMEDS::SObject_var gotBranch = itBig->Value();
917
918     // --> hypotheses root branch (only one for the study)
919     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
920       // create hypotheses root HDF group
921       aTopGroup = new HDFgroup( "Hypotheses", aFile );
922       aTopGroup->CreateOnDisk();
923
924       // iterator for all hypotheses
925       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
926       for ( ; it->More(); it->Next() ) {
927         SALOMEDS::SObject_var mySObject = it->Value();
928         CORBA::Object_var anObject = SObjectToObject( mySObject );
929         if ( !CORBA::is_nil( anObject ) ) {
930           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
931           if ( !myHyp->_is_nil() ) {
932             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
933             if ( myImpl ) {
934               string hypname = string( myHyp->GetName() );
935               string libname = string( myHyp->GetLibName() );
936               int    id      = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
937               string hypdata = string( myImpl->SaveTo() );
938
939               // for each hypothesis create HDF group basing on its id
940               char hypGrpName[30];
941               sprintf( hypGrpName, "Hypothesis %d", id );
942               aGroup = new HDFgroup( hypGrpName, aTopGroup );
943               aGroup->CreateOnDisk();
944               // --> type name of hypothesis
945               aSize[ 0 ] = hypname.length() + 1;
946               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
947               aDataset->CreateOnDisk();
948               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
949               aDataset->CloseOnDisk();
950               // --> server plugin library name of hypothesis
951               aSize[ 0 ] = libname.length() + 1;
952               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
953               aDataset->CreateOnDisk();
954               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
955               aDataset->CloseOnDisk();
956               // --> persistent data of hypothesis
957               aSize[ 0 ] = hypdata.length() + 1;
958               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
959               aDataset->CreateOnDisk();
960               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
961               aDataset->CloseOnDisk();
962               // close hypothesis HDF group
963               aGroup->CloseOnDisk();
964             }
965           }
966         }
967       }
968       // close hypotheses root HDF group
969       aTopGroup->CloseOnDisk();
970     }
971     // --> algorithms root branch (only one for the study)
972     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
973       // create algorithms root HDF group
974       aTopGroup = new HDFgroup( "Algorithms", aFile );
975       aTopGroup->CreateOnDisk();
976
977       // iterator for all algorithms
978       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
979       for ( ; it->More(); it->Next() ) {
980         SALOMEDS::SObject_var mySObject = it->Value();
981         CORBA::Object_var anObject = SObjectToObject( mySObject );
982         if ( !CORBA::is_nil( anObject ) ) {
983           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
984           if ( !myHyp->_is_nil() ) {
985             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
986             if ( myImpl ) {
987               string hypname = string( myHyp->GetName() );
988               string libname = string( myHyp->GetLibName() );
989               int    id      = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
990               string hypdata = string( myImpl->SaveTo() );
991
992               // for each algorithm create HDF group basing on its id
993               char hypGrpName[30];
994               sprintf( hypGrpName, "Algorithm %d", id );
995               aGroup = new HDFgroup( hypGrpName, aTopGroup );
996               aGroup->CreateOnDisk();
997               // --> type name of algorithm
998               aSize[0] = hypname.length() + 1;
999               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
1000               aDataset->CreateOnDisk();
1001               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
1002               aDataset->CloseOnDisk();
1003               // --> server plugin library name of hypothesis
1004               aSize[0] = libname.length() + 1;
1005               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
1006               aDataset->CreateOnDisk();
1007               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
1008               aDataset->CloseOnDisk();
1009               // --> persistent data of algorithm
1010               aSize[0] = hypdata.length() + 1;
1011               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
1012               aDataset->CreateOnDisk();
1013               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
1014               aDataset->CloseOnDisk();
1015               // close algorithm HDF group
1016               aGroup->CloseOnDisk();
1017             }
1018           }
1019         }
1020       }
1021       // close algorithms root HDF group
1022       aTopGroup->CloseOnDisk();
1023     }
1024     // --> mesh objects roots branches
1025     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
1026       CORBA::Object_var anObject = SObjectToObject( gotBranch );
1027       if ( !CORBA::is_nil( anObject ) ) {
1028         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
1029         if ( !myMesh->_is_nil() ) {
1030           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
1031           if ( myImpl ) {
1032             int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1033             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
1034             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
1035
1036             // for each mesh open the HDF group basing on its id
1037             char meshGrpName[ 30 ];
1038             sprintf( meshGrpName, "Mesh %d", id );
1039             aTopGroup = new HDFgroup( meshGrpName, aFile );
1040             aTopGroup->CreateOnDisk();
1041
1042             // --> put dataset to hdf file which is a flag that mesh has data
1043             string strHasData = "0";
1044             // check if the mesh is not empty
1045             if ( mySMESHDSMesh->NbNodes() > 0 ) {
1046               // write mesh data to med file
1047               myWriter.SetMesh( mySMESHDSMesh );
1048               myWriter.SetMeshId( id );
1049               strHasData = "1";
1050             }
1051             aSize[ 0 ] = strHasData.length() + 1;
1052             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
1053             aDataset->CreateOnDisk();
1054             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
1055             aDataset->CloseOnDisk();
1056             
1057             // write reference on a shape if exists
1058             SALOMEDS::SObject_var myRef;
1059             bool shapeRefFound = false;
1060             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
1061             if ( found ) {
1062               SALOMEDS::SObject_var myShape;
1063               bool ok = myRef->ReferencedObject( myShape );
1064               if ( ok ) {
1065                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
1066                 string myRefOnObject = myShape->GetID();
1067                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
1068                   aSize[ 0 ] = myRefOnObject.length() + 1;
1069                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
1070                   aDataset->CreateOnDisk();
1071                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1072                   aDataset->CloseOnDisk();
1073                 }
1074               }
1075             }
1076
1077             // write applied hypotheses if exist
1078             SALOMEDS::SObject_var myHypBranch;
1079             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
1080             if ( found && !shapeRefFound ) { // remove applied hyps
1081               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
1082             }
1083             if ( found && shapeRefFound ) {
1084               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
1085               aGroup->CreateOnDisk();
1086
1087               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
1088               int hypNb = 0;
1089               for ( ; it->More(); it->Next() ) {
1090                 SALOMEDS::SObject_var mySObject = it->Value();
1091                 SALOMEDS::SObject_var myRefOnHyp;
1092                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
1093                 if ( ok ) {
1094                   // san - it is impossible to recover applied hypotheses
1095                   //       using their entries within Load() method,
1096                   // for there are no AttributeIORs in the study when Load() is working. 
1097                   // Hence, it is better to store persistent IDs of hypotheses as references to them
1098
1099                   //string myRefOnObject = myRefOnHyp->GetID();
1100                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
1101                   int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1102                   //if ( myRefOnObject.length() > 0 ) {
1103                   //aSize[ 0 ] = myRefOnObject.length() + 1;
1104                   char hypName[ 30 ], hypId[ 30 ];
1105                   sprintf( hypName, "Hyp %d", ++hypNb );
1106                   sprintf( hypId, "%d", id );
1107                   aSize[ 0 ] = strlen( hypId ) + 1;
1108                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
1109                   aDataset->CreateOnDisk();
1110                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1111                   aDataset->WriteOnDisk( hypId );
1112                   aDataset->CloseOnDisk();
1113                   //}
1114                 }
1115               }
1116               aGroup->CloseOnDisk();
1117             }
1118
1119             // write applied algorithms if exist
1120             SALOMEDS::SObject_var myAlgoBranch;
1121             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
1122             if ( found && !shapeRefFound ) { // remove applied algos
1123               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
1124             }
1125             if ( found && shapeRefFound ) {
1126               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
1127               aGroup->CreateOnDisk();
1128
1129               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
1130               int algoNb = 0;
1131               for ( ; it->More(); it->Next() ) {
1132                 SALOMEDS::SObject_var mySObject = it->Value();
1133                 SALOMEDS::SObject_var myRefOnAlgo;
1134                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
1135                 if ( ok ) {
1136                   // san - it is impossible to recover applied algorithms
1137                   //       using their entries within Load() method,
1138                   // for there are no AttributeIORs in the study when Load() is working. 
1139                   // Hence, it is better to store persistent IDs of algorithms as references to them
1140
1141                   //string myRefOnObject = myRefOnAlgo->GetID();
1142                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
1143                   int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1144                   //if ( myRefOnObject.length() > 0 ) {
1145                   //aSize[ 0 ] = myRefOnObject.length() + 1;
1146                   char algoName[ 30 ], algoId[ 30 ];
1147                   sprintf( algoName, "Algo %d", ++algoNb );
1148                   sprintf( algoId, "%d", id );
1149                   aSize[ 0 ] = strlen( algoId ) + 1;
1150                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
1151                   aDataset->CreateOnDisk();
1152                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1153                   aDataset->WriteOnDisk( algoId );
1154                   aDataset->CloseOnDisk();
1155                   //}
1156                 }
1157               }
1158               aGroup->CloseOnDisk();
1159             }
1160
1161             // --> submesh objects sub-branches
1162
1163             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
1164               SALOMEDS::SObject_var mySubmeshBranch;
1165               found = gotBranch->FindSubObject( i, mySubmeshBranch );
1166
1167               if ( found ) // check if there is shape reference in submeshes
1168               {
1169                 bool hasShapeRef = false;
1170                 SALOMEDS::ChildIterator_var itSM =
1171                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
1172                 for ( ; itSM->More(); itSM->Next() ) {
1173                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
1174                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
1175                     mySubRef->ReferencedObject( myShape );
1176                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
1177                     hasShapeRef = true;
1178                   else
1179                   { // remove one submesh
1180                     if ( shapeRefFound )
1181                     { // unassign hypothesis
1182                       SMESH::SMESH_subMesh_var mySubMesh =
1183                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
1184                       if ( !mySubMesh->_is_nil() ) {
1185                         int shapeID = mySubMesh->GetId();
1186                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
1187                         const list<const SMESHDS_Hypothesis*>& hypList =
1188                           mySMESHDSMesh->GetHypothesis( S );
1189                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
1190                         while ( hyp != hypList.end() ) {
1191                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
1192                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
1193                         }
1194                       }
1195                     }
1196                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
1197                   }
1198                 } // loop on submeshes of a type
1199                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
1200                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
1201                   found = false;
1202                 }
1203               }  // end check if there is shape reference in submeshes
1204               if ( found ) {
1205                 char name_meshgroup[ 30 ];
1206                 if ( i == GetSubMeshOnVertexTag() )
1207                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
1208                 else if ( i == GetSubMeshOnEdgeTag() )
1209                   strcpy( name_meshgroup, "SubMeshes On Edge" );
1210                 else if ( i == GetSubMeshOnWireTag() )
1211                   strcpy( name_meshgroup, "SubMeshes On Wire" );
1212                 else if ( i == GetSubMeshOnFaceTag() )
1213                   strcpy( name_meshgroup, "SubMeshes On Face" );
1214                 else if ( i == GetSubMeshOnShellTag() )
1215                   strcpy( name_meshgroup, "SubMeshes On Shell" );
1216                 else if ( i == GetSubMeshOnSolidTag() )
1217                   strcpy( name_meshgroup, "SubMeshes On Solid" );
1218                 else if ( i == GetSubMeshOnCompoundTag() )
1219                   strcpy( name_meshgroup, "SubMeshes On Compound" );
1220                 
1221                 // for each type of submeshes create container HDF group
1222                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
1223                 aGroup->CreateOnDisk();
1224             
1225                 // iterator for all submeshes of given type
1226                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
1227                 for ( ; itSM->More(); itSM->Next() ) {
1228                   SALOMEDS::SObject_var mySObject = itSM->Value();
1229                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
1230                   if ( !CORBA::is_nil( anSubObject ))
1231                   {
1232                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
1233                     int subid = myStudyContext->findId( string( GetORB()->object_to_string( anSubObject ) ) );
1234                       
1235                     // for each mesh open the HDF group basing on its id
1236                     char submeshGrpName[ 30 ];
1237                     sprintf( submeshGrpName, "SubMesh %d", subid );
1238                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
1239                     aSubGroup->CreateOnDisk();
1240
1241                     // write reference on a shape, already checked if it exists
1242                     SALOMEDS::SObject_var mySubRef, myShape;
1243                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
1244                       mySubRef->ReferencedObject( myShape );
1245                     string myRefOnObject = myShape->GetID();
1246                     if ( myRefOnObject.length() > 0 ) {
1247                       aSize[ 0 ] = myRefOnObject.length() + 1;
1248                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
1249                       aDataset->CreateOnDisk();
1250                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1251                       aDataset->CloseOnDisk();
1252                     }
1253
1254                     // write applied hypotheses if exist
1255                     SALOMEDS::SObject_var mySubHypBranch;
1256                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
1257                     if ( found ) {
1258                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
1259                       aSubSubGroup->CreateOnDisk();
1260
1261                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
1262                       int hypNb = 0;
1263                       for ( ; it->More(); it->Next() ) {
1264                         SALOMEDS::SObject_var mySubSObject = it->Value();
1265                         SALOMEDS::SObject_var myRefOnHyp;
1266                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
1267                         if ( ok ) {
1268                           //string myRefOnObject = myRefOnHyp->GetID();
1269                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
1270                           int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1271                           //if ( myRefOnObject.length() > 0 ) {
1272                           //aSize[ 0 ] = myRefOnObject.length() + 1;
1273                           char hypName[ 30 ], hypId[ 30 ];
1274                           sprintf( hypName, "Hyp %d", ++hypNb );
1275                           sprintf( hypId, "%d", id );
1276                           aSize[ 0 ] = strlen( hypId ) + 1;
1277                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
1278                           aDataset->CreateOnDisk();
1279                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1280                           aDataset->WriteOnDisk( hypId );
1281                           aDataset->CloseOnDisk();
1282                           //}
1283                         }
1284                       }
1285                       aSubSubGroup->CloseOnDisk();
1286                     }
1287                     
1288                     // write applied algorithms if exist
1289                     SALOMEDS::SObject_var mySubAlgoBranch;
1290                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
1291                     if ( found ) {
1292                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
1293                       aSubSubGroup->CreateOnDisk();
1294
1295                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
1296                       int algoNb = 0;
1297                       for ( ; it->More(); it->Next() ) {
1298                         SALOMEDS::SObject_var mySubSObject = it->Value();
1299                         SALOMEDS::SObject_var myRefOnAlgo;
1300                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
1301                         if ( ok ) {
1302                           //string myRefOnObject = myRefOnAlgo->GetID();
1303                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
1304                           int id = myStudyContext->findId( string( GetORB()->object_to_string( anObject ) ) );
1305                           //if ( myRefOnObject.length() > 0 ) {
1306                           //aSize[ 0 ] = myRefOnObject.length() + 1;
1307                           char algoName[ 30 ], algoId[ 30 ];
1308                           sprintf( algoName, "Algo %d", ++algoNb );
1309                           sprintf( algoId, "%d", id );
1310                           aSize[ 0 ] = strlen( algoId ) + 1;
1311                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
1312                           aDataset->CreateOnDisk();
1313                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1314                           aDataset->WriteOnDisk( algoId );
1315                           aDataset->CloseOnDisk();
1316                           //}
1317                         }
1318                       }
1319                       aSubSubGroup->CloseOnDisk();
1320                     }
1321                     // close submesh HDF group
1322                     aSubGroup->CloseOnDisk();
1323                   }
1324                 }
1325                 // close container of submeshes by type HDF group
1326                 aGroup->CloseOnDisk();
1327               }
1328             }
1329             // All sub-meshes will be stored in MED file
1330             if ( shapeRefFound )
1331               myWriter.AddAllSubMeshes();
1332
1333             // groups root sub-branch
1334             SALOMEDS::SObject_var myGroupsBranch;
1335             for ( int i = GetNodeGroupsTag(); i <= GetVolumeGroupsTag(); i++ ) {
1336               found = gotBranch->FindSubObject( i, myGroupsBranch );
1337               if ( found ) {
1338                 char name_group[ 30 ];
1339                 if ( i == GetNodeGroupsTag() )
1340                   strcpy( name_group, "Groups of Nodes" );
1341                 else if ( i == GetEdgeGroupsTag() )
1342                   strcpy( name_group, "Groups of Edges" );
1343                 else if ( i == GetFaceGroupsTag() )
1344                   strcpy( name_group, "Groups of Faces" );
1345                 else if ( i == GetVolumeGroupsTag() )
1346                   strcpy( name_group, "Groups of Volumes" );
1347
1348                 aGroup = new HDFgroup( name_group, aTopGroup );
1349                 aGroup->CreateOnDisk();
1350
1351                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
1352                 for ( ; it->More(); it->Next() ) {
1353                   SALOMEDS::SObject_var mySObject = it->Value();
1354                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
1355                   if ( !CORBA::is_nil( aSubObject ) ) {
1356                     SMESH_GroupBase_i* myGroupImpl =
1357                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
1358                     if ( !myGroupImpl )
1359                       continue;
1360
1361                     int anId = myStudyContext->findId( string( GetORB()->object_to_string( aSubObject ) ) );
1362                     
1363                     // For each group, create a dataset named "Group <group_persistent_id>"
1364                     // and store the group's user name into it
1365                     char grpName[ 30 ];
1366                     sprintf( grpName, "Group %d", anId );
1367                     char* aUserName = myGroupImpl->GetName();
1368                     aSize[ 0 ] = strlen( aUserName ) + 1;
1369
1370                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
1371                     aDataset->CreateOnDisk();
1372                     aDataset->WriteOnDisk( aUserName );
1373                     aDataset->CloseOnDisk();
1374
1375                     // Store the group contents into MED file
1376                     if ( myLocMesh.GetGroup( myGroupImpl->GetLocalID() ) ) {
1377
1378                       if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen_i::Save(): saving group with StoreName = "
1379                               << grpName << " to MED file" );
1380                       SMESHDS_GroupBase* aGrpBaseDS =
1381                         myLocMesh.GetGroup( myGroupImpl->GetLocalID() )->GetGroupDS();
1382                       aGrpBaseDS->SetStoreName( grpName );
1383
1384                       // Pass SMESHDS_Group to MED writer 
1385                       SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
1386                       if ( aGrpDS )
1387                         myWriter.AddGroup( aGrpDS );
1388
1389                       // write reference on a shape if exists
1390                       SMESHDS_GroupOnGeom* aGeomGrp =
1391                         dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
1392                       if ( aGeomGrp ) {
1393                         SALOMEDS::SObject_var mySubRef, myShape;
1394                         if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
1395                             mySubRef->ReferencedObject( myShape ) &&
1396                             !CORBA::is_nil( myShape->GetObject() ))
1397                         {
1398                           string myRefOnObject = myShape->GetID();
1399                           if ( myRefOnObject.length() > 0 ) {
1400                             char aRefName[ 30 ];
1401                             sprintf( aRefName, "Ref on shape %d", anId);
1402                             aSize[ 0 ] = myRefOnObject.length() + 1;
1403                             aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
1404                             aDataset->CreateOnDisk();
1405                             aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
1406                             aDataset->CloseOnDisk();
1407                           }
1408                         }
1409                         else // shape ref is invalid:
1410                         {
1411                           // save a group on geometry as ordinary group
1412                           myWriter.AddGroup( aGeomGrp );
1413                         }
1414                       }
1415                     }
1416                   }
1417                 }
1418                 aGroup->CloseOnDisk();
1419               }
1420             } // loop on groups 
1421
1422             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
1423             {
1424               // Flush current mesh information into MED file
1425               myWriter.Perform();
1426
1427               // maybe a shape was deleted in the study
1428               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() ) {
1429                 TopoDS_Shape nullShape;
1430                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
1431               }
1432
1433               // Store node positions on sub-shapes (SMDS_Position):
1434
1435               if ( !mySMESHDSMesh->SubMeshes().empty() )
1436               {
1437                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
1438                 aGroup->CreateOnDisk();
1439
1440                 // in aGroup, create 5 datasets to contain:
1441                 // "Nodes on Edges" - ID of node on edge
1442                 // "Edge positions" - U parameter on node on edge
1443                 // "Nodes on Faces" - ID of node on face
1444                 // "Face U positions" - U parameter of node on face
1445                 // "Face V positions" - V parameter of node on face
1446
1447                 // Find out nb of nodes on edges and faces
1448                 // Collect corresponing sub-meshes
1449                 int nbEdgeNodes = 0, nbFaceNodes = 0;
1450                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
1451                 // loop on SMESHDS_SubMesh'es
1452                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
1453                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
1454                 for ( ; itSubM != aSubMeshes.end() ; itSubM++ )
1455                 {
1456                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
1457                   if ( aSubMesh->IsComplexSubmesh() )
1458                     continue; // submesh containing other submeshs
1459                   int nbNodes = aSubMesh->NbNodes();
1460                   if ( nbNodes == 0 ) continue;
1461
1462                   int aShapeID = (*itSubM).first;
1463                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
1464                   // write only SMDS_FacePosition and SMDS_EdgePosition
1465                   switch ( aShapeType ) {
1466                   case TopAbs_FACE:
1467                     nbFaceNodes += nbNodes;
1468                     aFaceSM.push_back( aSubMesh );
1469                     break;
1470                   case TopAbs_EDGE:
1471                     nbEdgeNodes += nbNodes;
1472                     aEdgeSM.push_back( aSubMesh );
1473                     break;
1474                   default:
1475                     continue;
1476                   }
1477                 }
1478                 // Treat positions on edges or faces
1479                 for ( int onFace = 0; onFace < 2; onFace++ )
1480                 {
1481                   // Create arrays to store in datasets
1482                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
1483                   if (!nbNodes) continue;
1484                   int* aNodeIDs = new int [ nbNodes ];
1485                   double* aUPos = new double [ nbNodes ];
1486                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
1487
1488                   // Fill arrays
1489                   // loop on sub-meshes
1490                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
1491                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
1492                   for ( ; itSM != pListSM->end(); itSM++ )
1493                   {
1494                     SMESHDS_SubMesh* aSubMesh = (*itSM);
1495                     if ( aSubMesh->IsComplexSubmesh() )
1496                       continue; // submesh containing other submeshs
1497
1498                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
1499                     // loop on nodes in aSubMesh
1500                     while ( itNode->more() )
1501                     {
1502                       //node ID
1503                       const SMDS_MeshNode* node = itNode->next();
1504                       aNodeIDs [ iNode ] = node->GetID();
1505
1506                       // Position
1507                       const SMDS_PositionPtr pos = node->GetPosition();
1508                       if ( onFace ) { // on FACE
1509                         const SMDS_FacePosition* fPos =
1510                           dynamic_cast<const SMDS_FacePosition*>( pos.get() );
1511                         if ( fPos ) {
1512                           aUPos[ iNode ] = fPos->GetUParameter();
1513                           aVPos[ iNode ] = fPos->GetVParameter();
1514                           iNode++;
1515                         }
1516                         else
1517                           nbNodes--;
1518                       }
1519                       else { // on EDGE
1520                         const SMDS_EdgePosition* ePos =
1521                           dynamic_cast<const SMDS_EdgePosition*>( pos.get() );
1522                         if ( ePos ) {
1523                           aUPos[ iNode ] = ePos->GetUParameter();
1524                           iNode++;
1525                         }
1526                         else
1527                           nbNodes--;
1528                       }
1529                     } // loop on nodes in aSubMesh
1530                   } // loop on sub-meshes
1531
1532                   // Write datasets
1533                   if ( nbNodes )
1534                   {
1535                     aSize[ 0 ] = nbNodes;
1536                     // IDS
1537                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
1538                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
1539                     aDataset->CreateOnDisk();
1540                     aDataset->WriteOnDisk( aNodeIDs );
1541                     aDataset->CloseOnDisk();
1542
1543                     // U Positions
1544                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
1545                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
1546                     aDataset->CreateOnDisk();
1547                     aDataset->WriteOnDisk( aUPos );
1548                     aDataset->CloseOnDisk();
1549                     // V Positions
1550                     if ( onFace ) {
1551                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
1552                       aDataset->CreateOnDisk();
1553                       aDataset->WriteOnDisk( aVPos );
1554                       aDataset->CloseOnDisk();
1555                     }
1556                   }
1557                   delete [] aNodeIDs;
1558                   delete [] aUPos;
1559                   if ( aVPos ) delete [] aVPos;
1560
1561                 } // treat positions on edges or faces
1562
1563                 // close "Node Positions" group
1564                 aGroup->CloseOnDisk(); 
1565
1566               } // if ( there are submeshes in SMESHDS_Mesh )
1567             } // if ( hasData )
1568
1569             // close mesh HDF group
1570             aTopGroup->CloseOnDisk();
1571           }
1572         }
1573       }
1574     }
1575   }
1576
1577   // close HDF file
1578   aFile->CloseOnDisk();
1579   delete aFile;
1580
1581   // Convert temporary files to stream
1582   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
1583
1584   // Remove temporary files and directory
1585   if ( !isMultiFile ) 
1586     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
1587
1588   INFOS( "SMESH_Gen_i::Save() completed" );
1589   return aStreamFile._retn();
1590 }
1591
1592 //=============================================================================
1593 /*!
1594  *  SMESH_Gen_i::SaveASCII
1595  *
1596  *  Save SMESH module's data in ASCII format (not implemented yet)
1597  */
1598 //=============================================================================
1599
1600 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
1601                                            const char*              theURL,
1602                                            bool                     isMultiFile ) {
1603   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
1604   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
1605   return aStreamFile._retn();
1606 }
1607
1608 //=============================================================================
1609 /*!
1610  *  SMESH_Gen_i::loadGeomData
1611  *
1612  *  Load GEOM module data
1613  */
1614 //=============================================================================
1615
1616 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
1617 {
1618   if ( theCompRoot->_is_nil() )
1619     return;
1620
1621   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
1622   if ( aStudy->_is_nil() )
1623     return;
1624
1625   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder(); 
1626   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
1627 }
1628
1629 //=============================================================================
1630 /*!
1631  *  SMESH_Gen_i::Load
1632  *
1633  *  Load SMESH module's data
1634  */
1635 //=============================================================================
1636
1637 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
1638                         const SALOMEDS::TMPFile& theStream,
1639                         const char*              theURL,
1640                         bool                     isMultiFile )
1641 {
1642   INFOS( "SMESH_Gen_i::Load" );
1643
1644   if ( myCurrentStudy->_is_nil() || 
1645        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
1646     SetCurrentStudy( theComponent->GetStudy() );
1647
1648   StudyContext* myStudyContext = GetCurrentStudyContext();
1649   
1650   // Get temporary files location
1651   TCollection_AsciiString tmpDir =
1652     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
1653
1654   // Convert the stream into sequence of files to process
1655   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
1656                                                                             tmpDir.ToCString(),
1657                                                                             isMultiFile );
1658   TCollection_AsciiString aStudyName( "" );
1659   if ( isMultiFile ) 
1660     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
1661
1662   // Set names of temporary files
1663   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
1664   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
1665
1666   int size;
1667   HDFfile*    aFile;
1668   HDFdataset* aDataset;
1669   HDFgroup*   aTopGroup;
1670   HDFgroup*   aGroup;
1671   HDFgroup*   aSubGroup;
1672   HDFgroup*   aSubSubGroup;
1673
1674   // Read data
1675   // ---> open HDF file
1676   aFile = new HDFfile( filename.ToCString() );
1677   try {
1678     aFile->OpenOnDisk( HDF_RDONLY );
1679   }
1680   catch ( HDFexception ) {
1681     INFOS( "Load(): " << filename << " not found!" );
1682     return false;
1683   }
1684
1685   DriverMED_R_SMESHDS_Mesh myReader;
1686   myReader.SetFile( meshfile.ToCString() );
1687
1688   // get total number of top-level groups
1689   int aNbGroups = aFile->nInternalObjects(); 
1690   if ( aNbGroups > 0 ) {
1691     // --> in first turn we should read&create hypotheses
1692     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
1693       // open hypotheses root HDF group
1694       aTopGroup = new HDFgroup( "Hypotheses", aFile ); 
1695       aTopGroup->OpenOnDisk();
1696
1697       // get number of hypotheses
1698       int aNbObjects = aTopGroup->nInternalObjects(); 
1699       for ( int j = 0; j < aNbObjects; j++ ) {
1700         // try to identify hypothesis
1701         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
1702         aTopGroup->InternalObjectIndentify( j, hypGrpName );
1703
1704         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
1705           // open hypothesis group
1706           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
1707           aGroup->OpenOnDisk();
1708
1709           // --> get hypothesis id
1710           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
1711           string hypname;
1712           string libname;
1713           string hypdata;
1714
1715           // get number of datasets
1716           int aNbSubObjects = aGroup->nInternalObjects();
1717           for ( int k = 0; k < aNbSubObjects; k++ ) {
1718             // identify dataset
1719             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
1720             aGroup->InternalObjectIndentify( k, name_of_subgroup );
1721             // --> get hypothesis name
1722             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
1723               aDataset = new HDFdataset( name_of_subgroup, aGroup );
1724               aDataset->OpenOnDisk();
1725               size = aDataset->GetSize();
1726               char* hypname_str = new char[ size ];
1727               aDataset->ReadFromDisk( hypname_str );
1728               hypname = string( hypname_str );
1729               delete hypname_str;
1730               aDataset->CloseOnDisk();
1731             }
1732             // --> get hypothesis plugin library name
1733             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
1734               aDataset = new HDFdataset( name_of_subgroup, aGroup );
1735               aDataset->OpenOnDisk();
1736               size = aDataset->GetSize();
1737               char* libname_str = new char[ size ];
1738               aDataset->ReadFromDisk( libname_str );
1739               if(MYDEBUG) SCRUTE( libname_str );
1740               libname = string( libname_str );
1741               delete libname_str;
1742               aDataset->CloseOnDisk();
1743             }
1744             // --> get hypothesis data
1745             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
1746               aDataset = new HDFdataset( name_of_subgroup, aGroup );
1747               aDataset->OpenOnDisk();
1748               size = aDataset->GetSize();
1749               char* hypdata_str = new char[ size ];
1750               aDataset->ReadFromDisk( hypdata_str );
1751               hypdata = string( hypdata_str );
1752               delete hypdata_str;
1753               aDataset->CloseOnDisk();
1754             }
1755           }
1756           // close hypothesis HDF group
1757           aGroup->CloseOnDisk();
1758
1759           // --> restore hypothesis from data
1760           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
1761             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
1762                     ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
1763             SMESH::SMESH_Hypothesis_var myHyp;
1764             
1765             try { // protect persistence mechanism against exceptions
1766               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
1767             }
1768             catch (...) {
1769               INFOS( "Exception during hypothesis creation" );
1770             }
1771
1772             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1773             if ( myImpl ) {
1774               myImpl->LoadFrom( hypdata.c_str() );
1775               string iorString = GetORB()->object_to_string( myHyp );
1776               int newId = myStudyContext->findId( iorString );
1777               myStudyContext->mapOldToNew( id, newId );
1778             }
1779             else
1780               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
1781           }
1782         }
1783       }
1784       // close hypotheses root HDF group
1785       aTopGroup->CloseOnDisk();
1786     }
1787
1788     // --> then we should read&create algorithms
1789     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
1790       // open algorithms root HDF group
1791       aTopGroup = new HDFgroup( "Algorithms", aFile ); 
1792       aTopGroup->OpenOnDisk();
1793
1794       // get number of algorithms
1795       int aNbObjects = aTopGroup->nInternalObjects(); 
1796       for ( int j = 0; j < aNbObjects; j++ ) {
1797         // try to identify algorithm
1798         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
1799         aTopGroup->InternalObjectIndentify( j, hypGrpName );
1800
1801         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
1802           // open algorithm group
1803           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
1804           aGroup->OpenOnDisk();
1805
1806           // --> get algorithm id
1807           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
1808           string hypname;
1809           string libname;
1810           string hypdata;
1811
1812           // get number of datasets
1813           int aNbSubObjects = aGroup->nInternalObjects();
1814           for ( int k = 0; k < aNbSubObjects; k++ ) {
1815             // identify dataset
1816             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
1817             aGroup->InternalObjectIndentify( k, name_of_subgroup );
1818             // --> get algorithm name
1819             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
1820               aDataset = new HDFdataset( name_of_subgroup, aGroup );
1821               aDataset->OpenOnDisk();
1822               size = aDataset->GetSize();
1823               char* hypname_str = new char[ size ];
1824               aDataset->ReadFromDisk( hypname_str );
1825               hypname = string( hypname_str );
1826               delete hypname_str;
1827               aDataset->CloseOnDisk();
1828             }
1829             // --> get algorithm plugin library name
1830             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
1831               aDataset = new HDFdataset( name_of_subgroup, aGroup );
1832               aDataset->OpenOnDisk();
1833               size = aDataset->GetSize();
1834               char* libname_str = new char[ size ];
1835               aDataset->ReadFromDisk( libname_str );
1836               if(MYDEBUG) SCRUTE( libname_str );
1837               libname = string( libname_str );
1838               delete libname_str;
1839               aDataset->CloseOnDisk();
1840             }
1841             // --> get algorithm data
1842             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
1843               aDataset = new HDFdataset( name_of_subgroup, aGroup );
1844               aDataset->OpenOnDisk();
1845               size = aDataset->GetSize();
1846               char* hypdata_str = new char[ size ];
1847               aDataset->ReadFromDisk( hypdata_str );
1848               if(MYDEBUG) SCRUTE( hypdata_str );
1849               hypdata = string( hypdata_str );
1850               delete hypdata_str;
1851               aDataset->CloseOnDisk();
1852             }
1853           }
1854           // close algorithm HDF group
1855           aGroup->CloseOnDisk();
1856           
1857           // --> restore algorithm from data
1858           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
1859             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
1860                     ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
1861             SMESH::SMESH_Hypothesis_var myHyp;
1862                     
1863             try { // protect persistence mechanism against exceptions
1864               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
1865             }
1866             catch (...) {
1867               INFOS( "Exception during hypothesis creation" );
1868             }
1869             
1870             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
1871             if ( myImpl ) {
1872               myImpl->LoadFrom( hypdata.c_str() );
1873               string iorString = GetORB()->object_to_string( myHyp );
1874               int newId = myStudyContext->findId( iorString );
1875               myStudyContext->mapOldToNew( id, newId );
1876             }
1877             else
1878               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
1879           }
1880         }
1881       }
1882       // close algorithms root HDF group
1883       aTopGroup->CloseOnDisk();
1884     }
1885
1886     // --> the rest groups should be meshes
1887     for ( int i = 0; i < aNbGroups; i++ ) {
1888       // identify next group
1889       char meshName[ HDF_NAME_MAX_LEN+1 ];
1890       aFile->InternalObjectIndentify( i, meshName );
1891
1892       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
1893         // --> get mesh id
1894         int id = atoi( string( meshName ).substr( 4 ).c_str() );
1895         if ( id <= 0 )
1896           continue;
1897
1898         bool hasData = false;
1899
1900         // open mesh HDF group
1901         aTopGroup = new HDFgroup( meshName, aFile ); 
1902         aTopGroup->OpenOnDisk();
1903
1904         // get number of child HDF objects
1905         int aNbObjects = aTopGroup->nInternalObjects(); 
1906         if ( aNbObjects > 0 ) {
1907           // create mesh
1908           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
1909           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
1910           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
1911           if ( !myNewMeshImpl )
1912             continue;
1913           string iorString = GetORB()->object_to_string( myNewMesh );
1914           int newId = myStudyContext->findId( iorString );
1915           myStudyContext->mapOldToNew( id, newId );
1916           
1917           ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
1918           SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
1919
1920           // try to find mesh data dataset
1921           if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
1922             // load mesh "has data" flag
1923             aDataset = new HDFdataset( "Has data", aTopGroup );
1924             aDataset->OpenOnDisk();
1925             size = aDataset->GetSize();
1926             char* strHasData = new char[ size ];
1927             aDataset->ReadFromDisk( strHasData );
1928             aDataset->CloseOnDisk();
1929             if ( strcmp( strHasData, "1") == 0 ) {
1930               // read mesh data from MED file
1931               myReader.SetMesh( mySMESHDSMesh );
1932               myReader.SetMeshId( id );
1933               myReader.Perform();
1934               hasData = true;
1935             }
1936           }
1937
1938           // try to read and set reference to shape
1939           GEOM::GEOM_Object_var aShapeObject;
1940           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
1941             // load mesh "Ref on shape" - it's an entry to SObject
1942             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
1943             aDataset->OpenOnDisk();
1944             size = aDataset->GetSize();
1945             char* refFromFile = new char[ size ];
1946             aDataset->ReadFromDisk( refFromFile );
1947             aDataset->CloseOnDisk();
1948             if ( strlen( refFromFile ) > 0 ) {
1949               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
1950
1951               // Make sure GEOM data are loaded first
1952               loadGeomData( shapeSO->GetFatherComponent() );
1953
1954               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
1955               if ( !CORBA::is_nil( shapeObject ) ) {
1956                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
1957                 if ( !aShapeObject->_is_nil() )
1958                   myNewMeshImpl->SetShape( aShapeObject );
1959               }
1960             }
1961           }
1962
1963           // try to get applied algorithms
1964           if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
1965             aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
1966             aGroup->OpenOnDisk();
1967             // get number of applied algorithms
1968             int aNbSubObjects = aGroup->nInternalObjects(); 
1969             if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
1970             for ( int j = 0; j < aNbSubObjects; j++ ) {
1971               char name_dataset[ HDF_NAME_MAX_LEN+1 ];
1972               aGroup->InternalObjectIndentify( j, name_dataset );
1973               // check if it is an algorithm
1974               if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
1975                 aDataset = new HDFdataset( name_dataset, aGroup );
1976                 aDataset->OpenOnDisk();
1977                 size = aDataset->GetSize();
1978                 char* refFromFile = new char[ size ];
1979                 aDataset->ReadFromDisk( refFromFile );
1980                 aDataset->CloseOnDisk();
1981
1982                 // san - it is impossible to recover applied algorithms using their entries within Load() method
1983                 
1984                 //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
1985                 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
1986                 int id = atoi( refFromFile );
1987                 string anIOR = myStudyContext->getIORbyOldId( id );
1988                 if ( !anIOR.empty() ) {
1989                   CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
1990                   if ( !CORBA::is_nil( hypObject ) ) {
1991                     SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
1992                     if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
1993                       myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
1994                   }
1995                 }
1996               }
1997             }
1998             aGroup->CloseOnDisk();
1999           }
2000
2001           // try to get applied hypotheses
2002           if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
2003             aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
2004             aGroup->OpenOnDisk();
2005             // get number of applied hypotheses
2006             int aNbSubObjects = aGroup->nInternalObjects(); 
2007             for ( int j = 0; j < aNbSubObjects; j++ ) {
2008               char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2009               aGroup->InternalObjectIndentify( j, name_dataset );
2010               // check if it is a hypothesis
2011               if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
2012                 aDataset = new HDFdataset( name_dataset, aGroup );
2013                 aDataset->OpenOnDisk();
2014                 size = aDataset->GetSize();
2015                 char* refFromFile = new char[ size ];
2016                 aDataset->ReadFromDisk( refFromFile );
2017                 aDataset->CloseOnDisk();
2018
2019                 // san - it is impossible to recover applied hypotheses using their entries within Load() method
2020                 
2021                 //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2022                 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2023                 int id = atoi( refFromFile );
2024                 string anIOR = myStudyContext->getIORbyOldId( id );
2025                 if ( !anIOR.empty() ) {
2026                   CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2027                   if ( !CORBA::is_nil( hypObject ) ) {
2028                     SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2029                     if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2030                       myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
2031                   }
2032                 }
2033               }
2034             }
2035             aGroup->CloseOnDisk();
2036           }
2037
2038           // --> try to find submeshes containers for each type of submesh
2039           for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
2040             char name_meshgroup[ 30 ];
2041             if ( j == GetSubMeshOnVertexTag() )
2042               strcpy( name_meshgroup, "SubMeshes On Vertex" );
2043             else if ( j == GetSubMeshOnEdgeTag() )
2044               strcpy( name_meshgroup, "SubMeshes On Edge" );
2045             else if ( j == GetSubMeshOnWireTag() )
2046               strcpy( name_meshgroup, "SubMeshes On Wire" );
2047             else if ( j == GetSubMeshOnFaceTag() )
2048               strcpy( name_meshgroup, "SubMeshes On Face" );
2049             else if ( j == GetSubMeshOnShellTag() )
2050               strcpy( name_meshgroup, "SubMeshes On Shell" );
2051             else if ( j == GetSubMeshOnSolidTag() )
2052               strcpy( name_meshgroup, "SubMeshes On Solid" );
2053             else if ( j == GetSubMeshOnCompoundTag() )
2054               strcpy( name_meshgroup, "SubMeshes On Compound" );
2055             
2056             // try to get submeshes container HDF group
2057             if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
2058               // open submeshes containers HDF group
2059               aGroup = new HDFgroup( name_meshgroup, aTopGroup );
2060               aGroup->OpenOnDisk();
2061               
2062               // get number of submeshes
2063               int aNbSubMeshes = aGroup->nInternalObjects(); 
2064               for ( int k = 0; k < aNbSubMeshes; k++ ) {
2065                 // identify submesh
2066                 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
2067                 aGroup->InternalObjectIndentify( k, name_submeshgroup );
2068                 if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
2069                   // --> get submesh id
2070                   int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
2071                   if ( subid <= 0 )
2072                     continue;
2073                   // open submesh HDF group
2074                   aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
2075                   aSubGroup->OpenOnDisk();
2076                   
2077                   // try to read and set reference to subshape
2078                   GEOM::GEOM_Object_var aSubShapeObject;
2079                   SMESH::SMESH_subMesh_var aSubMesh;
2080
2081                   if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
2082                     // load submesh "Ref on shape" - it's an entry to SObject
2083                     aDataset = new HDFdataset( "Ref on shape", aSubGroup );
2084                     aDataset->OpenOnDisk();
2085                     size = aDataset->GetSize();
2086                     char* refFromFile = new char[ size ];
2087                     aDataset->ReadFromDisk( refFromFile );
2088                     aDataset->CloseOnDisk();
2089                     if ( strlen( refFromFile ) > 0 ) {
2090                       SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
2091                       CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
2092                       if ( !CORBA::is_nil( subShapeObject ) ) {
2093                         aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
2094                         if ( !aSubShapeObject->_is_nil() )
2095                           aSubMesh = SMESH::SMESH_subMesh::_duplicate
2096                             ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
2097                         if ( aSubMesh->_is_nil() )
2098                           continue;
2099                         string iorSubString = GetORB()->object_to_string( aSubMesh );
2100                         int newSubId = myStudyContext->findId( iorSubString );
2101                         myStudyContext->mapOldToNew( subid, newSubId );
2102                       }
2103                     }
2104                   }
2105                   
2106                   if ( aSubMesh->_is_nil() )
2107                     continue;
2108
2109                   // VSR: Get submesh data from MED convertor
2110 //                int anInternalSubmeshId = aSubMesh->GetId(); // this is not a persistent ID, it's an internal one computed from sub-shape
2111 //                if (myNewMeshImpl->_mapSubMesh.find(anInternalSubmeshId) != myNewMeshImpl->_mapSubMesh.end()) {
2112 //                  if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): loading from MED file submesh with ID = " <<
2113 //                            subid << " for subshape # " << anInternalSubmeshId);
2114 //                  SMESHDS_SubMesh* aSubMeshDS =
2115 //                      myNewMeshImpl->_mapSubMesh[anInternalSubmeshId]->CreateSubMeshDS();
2116 //                  if ( !aSubMeshDS ) {
2117 //                    if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): FAILED to create a submesh for subshape # " <<
2118 //                              anInternalSubmeshId << " in current mesh!");
2119 //                  }
2120 //                  else
2121 //                    myReader.GetSubMesh( aSubMeshDS, subid );
2122 //                }
2123                     
2124                   // try to get applied algorithms
2125                   if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
2126                     // open "applied algorithms" HDF group
2127                     aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
2128                     aSubSubGroup->OpenOnDisk();
2129                     // get number of applied algorithms
2130                     int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
2131                     for ( int l = 0; l < aNbSubObjects; l++ ) {
2132                       char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2133                       aSubSubGroup->InternalObjectIndentify( l, name_dataset );
2134                       // check if it is an algorithm
2135                       if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
2136                         aDataset = new HDFdataset( name_dataset, aSubSubGroup );
2137                         aDataset->OpenOnDisk();
2138                         size = aDataset->GetSize();
2139                         char* refFromFile = new char[ size ];
2140                         aDataset->ReadFromDisk( refFromFile );
2141                         aDataset->CloseOnDisk();
2142
2143                         //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2144                         //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2145                         int id = atoi( refFromFile );
2146                         string anIOR = myStudyContext->getIORbyOldId( id );
2147                         if ( !anIOR.empty() ) {
2148                           CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2149                           if ( !CORBA::is_nil( hypObject ) ) {
2150                             SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2151                             if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2152                               myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
2153                           }
2154                         }
2155                       }
2156                     }
2157                     // close "applied algorithms" HDF group
2158                     aSubSubGroup->CloseOnDisk();
2159                   }
2160                   
2161                   // try to get applied hypotheses
2162                   if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
2163                     // open "applied hypotheses" HDF group
2164                     aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
2165                     aSubSubGroup->OpenOnDisk();
2166                     // get number of applied hypotheses
2167                     int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
2168                     for ( int l = 0; l < aNbSubObjects; l++ ) {
2169                       char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2170                       aSubSubGroup->InternalObjectIndentify( l, name_dataset );
2171                       // check if it is a hypothesis
2172                       if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
2173                         aDataset = new HDFdataset( name_dataset, aSubSubGroup );
2174                         aDataset->OpenOnDisk();
2175                         size = aDataset->GetSize();
2176                         char* refFromFile = new char[ size ];
2177                         aDataset->ReadFromDisk( refFromFile );
2178                         aDataset->CloseOnDisk();
2179                         
2180                         //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
2181                         //CORBA::Object_var hypObject = SObjectToObject( hypSO );
2182                         int id = atoi( refFromFile );
2183                         string anIOR = myStudyContext->getIORbyOldId( id );
2184                         if ( !anIOR.empty() ) {
2185                           CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
2186                           if ( !CORBA::is_nil( hypObject ) ) {
2187                             SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
2188                             if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
2189                               myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
2190                           }
2191                         }
2192                       }
2193                     }
2194                     // close "applied hypotheses" HDF group
2195                     aSubSubGroup->CloseOnDisk();
2196                   }
2197
2198                   // close submesh HDF group
2199                   aSubGroup->CloseOnDisk();
2200                 }
2201               }
2202               // close submeshes containers HDF group
2203               aGroup->CloseOnDisk();
2204             }
2205           }
2206
2207           if(hasData) {
2208             // Read sub-meshes from MED
2209             if(MYDEBUG) MESSAGE("JFA - Create all sub-meshes");
2210             myReader.CreateAllSubMeshes();
2211
2212
2213             // Read node positions on sub-shapes (SMDS_Position)
2214
2215             if ( aTopGroup->ExistInternalObject( "Node Positions" ))
2216             {
2217               // There are 5 datasets to read:
2218               // "Nodes on Edges" - ID of node on edge
2219               // "Edge positions" - U parameter on node on edge
2220               // "Nodes on Faces" - ID of node on face
2221               // "Face U positions" - U parameter of node on face
2222               // "Face V positions" - V parameter of node on face
2223               char* aEid_DSName = "Nodes on Edges";
2224               char* aEu_DSName  = "Edge positions";
2225               char* aFu_DSName  = "Face U positions";
2226               //char* aFid_DSName = "Nodes on Faces";
2227               //char* aFv_DSName  = "Face V positions";
2228
2229               // data to retrieve
2230               int nbEids = 0, nbFids = 0;
2231               int *aEids = 0, *aFids  = 0;
2232               double *aEpos = 0, *aFupos = 0, *aFvpos = 0;
2233
2234               // open a group
2235               aGroup = new HDFgroup( "Node Positions", aTopGroup ); 
2236               aGroup->OpenOnDisk();
2237
2238               // loop on 5 data sets
2239               int aNbObjects = aGroup->nInternalObjects();
2240               for ( int i = 0; i < aNbObjects; i++ )
2241               {
2242                 // identify dataset
2243                 char aDSName[ HDF_NAME_MAX_LEN+1 ];
2244                 aGroup->InternalObjectIndentify( i, aDSName );
2245                 // read data
2246                 aDataset = new HDFdataset( aDSName, aGroup );
2247                 aDataset->OpenOnDisk();
2248                 if ( aDataset->GetType() == HDF_FLOAT64 ) // Positions
2249                 {
2250                   double* pos = new double [ aDataset->GetSize() ];
2251                   aDataset->ReadFromDisk( pos );
2252                   // which one?
2253                   if ( strncmp( aDSName, aEu_DSName, strlen( aEu_DSName )) == 0 )
2254                     aEpos = pos;
2255                   else if ( strncmp( aDSName, aFu_DSName, strlen( aFu_DSName )) == 0 )
2256                     aFupos = pos;
2257                   else
2258                     aFvpos = pos;
2259                 }
2260                 else // NODE IDS
2261                 {
2262                   int* ids = new int [ aDataset->GetSize() ];
2263                   aDataset->ReadFromDisk( ids );
2264                   // on face or nodes?
2265                   if ( strncmp( aDSName, aEid_DSName, strlen( aEid_DSName )) == 0 ) {
2266                     aEids = ids;
2267                     nbEids = aDataset->GetSize();
2268                   }
2269                   else {
2270                     aFids = ids;
2271                     nbFids = aDataset->GetSize();
2272                   }
2273                 }
2274               } // loop on 5 datasets
2275
2276               // Set node positions on edges or faces
2277               for ( int onFace = 0; onFace < 2; onFace++ )
2278               {
2279                 int nbNodes = ( onFace ? nbFids : nbEids );
2280                 if ( nbNodes == 0 ) continue;
2281                 int* aNodeIDs = ( onFace ? aFids : aEids );
2282                 double* aUPos = ( onFace ? aFupos : aEpos );
2283                 double* aVPos = ( onFace ? aFvpos : 0 );
2284                 // loop on node IDs
2285                 for ( int iNode = 0; iNode < nbNodes; iNode++ )
2286                 {
2287                   const SMDS_MeshNode* node = mySMESHDSMesh->FindNode( aNodeIDs[ iNode ]);
2288                   ASSERT( node );
2289                   SMDS_PositionPtr aPos = node->GetPosition();
2290                   ASSERT( aPos )
2291                   if ( onFace ) {
2292                     ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_FACE );
2293                     SMDS_FacePosition* fPos = const_cast<SMDS_FacePosition*>
2294                       ( static_cast<const SMDS_FacePosition*>( aPos.get() ));
2295                     fPos->SetUParameter( aUPos[ iNode ]);
2296                     fPos->SetVParameter( aVPos[ iNode ]);
2297                   }
2298                   else {
2299                     ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE );
2300                     SMDS_EdgePosition* fPos = const_cast<SMDS_EdgePosition*>
2301                       ( static_cast<const SMDS_EdgePosition*>( aPos.get() ));
2302                     fPos->SetUParameter( aUPos[ iNode ]);
2303                   }
2304                 }
2305               }
2306               if ( aEids ) delete [] aEids;
2307               if ( aFids ) delete [] aFids;
2308               if ( aEpos ) delete [] aEpos;
2309               if ( aFupos ) delete [] aFupos;
2310               if ( aFvpos ) delete [] aFvpos;
2311               
2312               aGroup->CloseOnDisk();
2313
2314             } // if ( aTopGroup->ExistInternalObject( "Node Positions" ) )
2315           } // if ( hasData )
2316
2317           // Recompute State (as computed sub-meshes are restored from MED)
2318           if ( !aShapeObject->_is_nil() ) {
2319             MESSAGE("JFA - Compute State Engine ...");
2320             TopoDS_Shape myLocShape = GeomObjectToShape( aShapeObject );
2321             myNewMeshImpl->GetImpl().GetSubMesh(myLocShape)->ComputeStateEngine
2322               (SMESH_subMesh::SUBMESH_RESTORED);
2323             MESSAGE("JFA - Compute State Engine finished");
2324           }
2325
2326           // try to get groups
2327           for ( int ii = GetNodeGroupsTag(); ii <= GetVolumeGroupsTag(); ii++ ) {
2328             char name_group[ 30 ];
2329             if ( ii == GetNodeGroupsTag() )
2330               strcpy( name_group, "Groups of Nodes" );
2331             else if ( ii == GetEdgeGroupsTag() )
2332               strcpy( name_group, "Groups of Edges" );
2333             else if ( ii == GetFaceGroupsTag() )
2334               strcpy( name_group, "Groups of Faces" );
2335             else if ( ii == GetVolumeGroupsTag() )
2336               strcpy( name_group, "Groups of Volumes" );
2337
2338             if ( aTopGroup->ExistInternalObject( name_group ) ) {
2339               aGroup = new HDFgroup( name_group, aTopGroup );
2340               aGroup->OpenOnDisk();
2341               // get number of groups
2342               int aNbSubObjects = aGroup->nInternalObjects(); 
2343               for ( int j = 0; j < aNbSubObjects; j++ ) {
2344                 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
2345                 aGroup->InternalObjectIndentify( j, name_dataset );
2346                 // check if it is an group
2347                 if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
2348                   // --> get group id
2349                   int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
2350                   if ( subid <= 0 )
2351                     continue;
2352                   aDataset = new HDFdataset( name_dataset, aGroup );
2353                   aDataset->OpenOnDisk();
2354
2355                   // Retrieve actual group name
2356                   size = aDataset->GetSize();
2357                   char* nameFromFile = new char[ size ];
2358                   aDataset->ReadFromDisk( nameFromFile );
2359                   aDataset->CloseOnDisk();
2360
2361                   // Try to find a shape reference
2362                   TopoDS_Shape aShape;
2363                   char aRefName[ 30 ];
2364                   sprintf( aRefName, "Ref on shape %d", subid);
2365                   if ( aGroup->ExistInternalObject( aRefName ) ) {
2366                     // load mesh "Ref on shape" - it's an entry to SObject
2367                     aDataset = new HDFdataset( aRefName, aGroup );
2368                     aDataset->OpenOnDisk();
2369                     size = aDataset->GetSize();
2370                     char* refFromFile = new char[ size ];
2371                     aDataset->ReadFromDisk( refFromFile );
2372                     aDataset->CloseOnDisk();
2373                     if ( strlen( refFromFile ) > 0 ) {
2374                       SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
2375                       CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
2376                       if ( !CORBA::is_nil( shapeObject ) ) {
2377                         aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
2378                         if ( !aShapeObject->_is_nil() )
2379                           aShape = GeomObjectToShape( aShapeObject );
2380                       }
2381                     }
2382                   }
2383                   // Create group servant
2384                   SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
2385                   SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
2386                     ( myNewMeshImpl->createGroup( type, nameFromFile, aShape ) );
2387                   // Obtain a SMESHDS_Group object 
2388                   if ( aNewGroup->_is_nil() )
2389                     continue;
2390
2391                   string iorSubString = GetORB()->object_to_string( aNewGroup );
2392                   int newSubId = myStudyContext->findId( iorSubString );
2393                   myStudyContext->mapOldToNew( subid, newSubId );
2394
2395                   SMESH_GroupBase_i* aGroupImpl =
2396                     dynamic_cast<SMESH_GroupBase_i*>( GetServant( aNewGroup ).in() );
2397                   if ( !aGroupImpl )
2398                     continue;
2399
2400                   SMESH_Group* aLocalGroup  = myLocMesh.GetGroup( aGroupImpl->GetLocalID() );
2401                   if ( !aLocalGroup )
2402                     continue;
2403
2404                   SMESHDS_GroupBase* aGroupBaseDS = aLocalGroup->GetGroupDS();
2405                   aGroupBaseDS->SetStoreName( name_dataset );
2406
2407                   // Fill group with contents from MED file
2408                   SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
2409                   if ( aGrp )
2410                     myReader.GetGroup( aGrp );
2411                 }
2412               }
2413               aGroup->CloseOnDisk();
2414             }
2415           }
2416         }
2417         // close mesh group
2418         aTopGroup->CloseOnDisk();       
2419       }
2420     }
2421   }
2422   // close HDF file
2423   aFile->CloseOnDisk();
2424   delete aFile;
2425
2426   // Remove temporary files created from the stream
2427   if ( !isMultiFile ) 
2428     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
2429
2430   INFOS( "SMESH_Gen_i::Load completed" );
2431   return true;
2432 }
2433
2434 //=============================================================================
2435 /*!
2436  *  SMESH_Gen_i::LoadASCII
2437  *
2438  *  Load SMESH module's data in ASCII format (not implemented yet)
2439  */
2440 //=============================================================================
2441
2442 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
2443                              const SALOMEDS::TMPFile& theStream,
2444                              const char*              theURL,
2445                              bool                     isMultiFile ) {
2446   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
2447   return Load( theComponent, theStream, theURL, isMultiFile );
2448 }
2449
2450 //=============================================================================
2451 /*!
2452  *  SMESH_Gen_i::Close
2453  *
2454  *  Clears study-connected data when it is closed
2455  */
2456 //=============================================================================
2457
2458 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
2459 {
2460   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
2461
2462   // Clear study contexts data
2463   int studyId = GetCurrentStudyID();
2464   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
2465     delete myStudyContextMap[ studyId ];
2466     myStudyContextMap.erase( studyId );
2467   }
2468   return;
2469 }
2470
2471 //=============================================================================
2472 /*!
2473  *  SMESH_Gen_i::ComponentDataType
2474  * 
2475  *  Get component data type
2476  */
2477 //=============================================================================
2478
2479 char* SMESH_Gen_i::ComponentDataType()
2480 {
2481   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
2482   return CORBA::string_dup( "SMESH" );
2483 }
2484
2485     
2486 //=============================================================================
2487 /*!
2488  *  SMESH_Gen_i::IORToLocalPersistentID
2489  *  
2490  *  Transform data from transient form to persistent
2491  */
2492 //=============================================================================
2493
2494 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
2495                                            const char*           IORString,
2496                                            CORBA::Boolean        /*isMultiFile*/,
2497                                            CORBA::Boolean        /*isASCII*/ )
2498 {
2499   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
2500   StudyContext* myStudyContext = GetCurrentStudyContext();
2501   
2502   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
2503     int anId = myStudyContext->findId( IORString );
2504     if ( anId ) {
2505       if(MYDEBUG) MESSAGE( "VSR " << anId )
2506       char strId[ 20 ];
2507       sprintf( strId, "%d", anId );
2508       return  CORBA::string_dup( strId );
2509     }
2510   }
2511   return CORBA::string_dup( "" );
2512 }
2513
2514 //=============================================================================
2515 /*!
2516  *  SMESH_Gen_i::LocalPersistentIDToIOR
2517  *
2518  *  Transform data from persistent form to transient
2519  */
2520 //=============================================================================
2521
2522 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
2523                                            const char*           aLocalPersistentID,
2524                                            CORBA::Boolean        /*isMultiFile*/,
2525                                            CORBA::Boolean        /*isASCII*/ )
2526 {
2527   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
2528   StudyContext* myStudyContext = GetCurrentStudyContext();
2529
2530   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
2531     int anId = atoi( aLocalPersistentID );
2532     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
2533   }
2534   return CORBA::string_dup( "" );
2535 }
2536
2537 //=======================================================================
2538 //function : RegisterObject
2539 //purpose  : 
2540 //=======================================================================
2541
2542 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
2543 {
2544   StudyContext* myStudyContext = GetCurrentStudyContext();
2545   if ( myStudyContext && !CORBA::is_nil( theObject )) {
2546     string iorString = GetORB()->object_to_string( theObject );
2547     return myStudyContext->addObject( iorString );
2548   }
2549   return 0;
2550 }
2551       
2552 //=============================================================================
2553 /*! 
2554  *  SMESHEngine_factory
2555  *
2556  *  C factory, accessible with dlsym, after dlopen  
2557  */
2558 //=============================================================================
2559
2560 extern "C"
2561 {
2562   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
2563                                                  PortableServer::POA_ptr   poa, 
2564                                                  PortableServer::ObjectId* contId,
2565                                                  const char*               instanceName, 
2566                                                  const char*               interfaceName )
2567   {
2568     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
2569     if(MYDEBUG) SCRUTE(interfaceName);
2570     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
2571     return aSMESHGen->getId() ;
2572   }
2573 }