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