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