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