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