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