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