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