Salome HOME
0021347: [CEA 497] Visualisation into SMESH and VISU of hexagonal prism cells (MED_OC...
[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; SMDS_NodeIteratorPtr srcNodeIt;
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     srcNodeIt = srcMeshDS->nodesIterator();
2446   }
2447   else
2448   {
2449     SMESH::long_array_var ids = meshPart->GetIDs();
2450     if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2451     {
2452       for (int i=0; i < ids->length(); i++)
2453         if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2454           srcElems.insert( elem );
2455     }
2456     else
2457     {
2458       for (int i=0; i < ids->length(); i++)
2459         if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2460           srcElems.insert( elem );
2461     }
2462     if ( srcElems.empty() )
2463       return newMesh._retn();
2464
2465     typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2466     srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2467   }
2468
2469   // 4. Copy elements
2470
2471   typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2472   TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2473   TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2474   int iN;
2475   const SMDS_MeshNode *nSrc, *nTgt;
2476   vector< const SMDS_MeshNode* > nodes;
2477   while ( srcElemIt->more() )
2478   {
2479     const SMDS_MeshElement * elem = srcElemIt->next();
2480     nodes.resize( elem->NbNodes());
2481     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2482     if ( toKeepIDs ) {
2483       for ( iN = 0; nIt->more(); ++iN )
2484       {
2485         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2486         nTgt = newMeshDS->FindNode( nSrc->GetID());
2487         if ( !nTgt )
2488           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2489         nodes[ iN ] = nTgt;
2490       }
2491     }
2492     else {
2493       for ( iN = 0; nIt->more(); ++iN )
2494       {
2495         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2496         TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2497         if ( !n2n->second )
2498           n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2499         nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2500       }
2501     }
2502     if ( elem->GetType() != SMDSAbs_Node )
2503     {
2504       int ID = toKeepIDs ? elem->GetID() : 0;
2505       const SMDS_MeshElement * newElem;
2506       if ( elem->GetEntityType() == SMDSEntity_Polyhedra )
2507         newElem = editor.GetMeshDS()->
2508           AddPolyhedralVolumeWithID( nodes,
2509                                      static_cast<const SMDS_VtkVolume*>(elem)->GetQuantities(),
2510                                      elem->GetID());
2511       else
2512         newElem = editor.AddElement( nodes,elem->GetType(),elem->IsPoly(),ID);
2513
2514       if ( toCopyGroups && !toKeepIDs )
2515         e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2516     }
2517   }
2518
2519   // 4(b). Copy free nodes
2520
2521   if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2522   {
2523     while ( srcNodeIt->more() )
2524     {
2525       nSrc = srcNodeIt->next();
2526       if ( nSrc->NbInverseElements() == 0 )
2527       {
2528         if ( toKeepIDs )
2529           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2530         else
2531           n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2532       }
2533     }
2534   }
2535
2536   // 5. Copy groups
2537
2538   int nbNewGroups = 0;
2539   if ( toCopyGroups )
2540   {
2541     SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2542     while ( gIt->more() )
2543     {
2544       SMESH_Group* group = gIt->next();
2545       const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2546
2547       // Check group type. We copy nodal groups containing nodes of copied element
2548       SMDSAbs_ElementType groupType = groupDS->GetType();
2549       if ( groupType != SMDSAbs_Node &&
2550            newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2551         continue; // group type differs from types of meshPart
2552
2553       // Find copied elements in the group
2554       vector< const SMDS_MeshElement* > groupElems;
2555       SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2556       if ( toKeepIDs )
2557       {
2558         const SMDS_MeshElement* foundElem;
2559         if ( groupType == SMDSAbs_Node )
2560         {
2561           while ( eIt->more() )
2562             if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2563               groupElems.push_back( foundElem );
2564         }
2565         else
2566         {
2567           while ( eIt->more() )
2568             if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2569               groupElems.push_back( foundElem );
2570         }
2571       }
2572       else
2573       {
2574         TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2575         if ( e2eMap.empty() ) continue;
2576         int minID = e2eMap.begin()->first->GetID();
2577         int maxID = e2eMap.rbegin()->first->GetID();
2578         TE2EMap::iterator e2e;
2579         while ( eIt->more() && groupElems.size() < e2eMap.size())
2580         {
2581           const SMDS_MeshElement* e = eIt->next();
2582           if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2583           if ((e2e = e2eMap.find( e )) != e2eMap.end())
2584             groupElems.push_back( e2e->second );
2585         }
2586       }
2587       // Make a new group
2588       if ( !groupElems.empty() )
2589       {
2590         SMESH::SMESH_Group_var newGroupObj =
2591           newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2592         if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2593         {
2594           SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2595           SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2596           for ( unsigned i = 0; i < groupElems.size(); ++i )
2597             smdsGroup.Add( groupElems[i] );
2598
2599           nbNewGroups++;
2600         }
2601       }
2602     }
2603   }
2604
2605   newMeshDS->Modified();
2606
2607   *pyDump << newMesh << " = " << this
2608           << ".CopyMesh( " << meshPart << ", "
2609           << "'" << meshName << "', "
2610           << toCopyGroups << ", "
2611           << toKeepIDs << ")";
2612
2613   delete pyDump; pyDump = 0; // allow dump in GetGroups()
2614
2615   if ( nbNewGroups > 0 ) // dump created groups
2616     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2617
2618   return newMesh._retn();
2619 }
2620
2621 //================================================================================
2622 /*!
2623  *  SMESH_Gen_i::GetMEDVersion
2624  *
2625  *  Get MED version of the file by its name
2626  */
2627 //================================================================================
2628 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2629                                           SMESH::MED_VERSION& theVersion)
2630 {
2631   theVersion = SMESH::MED_V2_1;
2632   MED::EVersion aVersion = MED::GetVersionId( theFileName );
2633   switch( aVersion ) {
2634     case MED::eV2_1     : theVersion = SMESH::MED_V2_1; return true;
2635     case MED::eV2_2     : theVersion = SMESH::MED_V2_2; return true;
2636     case MED::eVUnknown : return false;
2637   }
2638   return false;
2639 }
2640
2641 //================================================================================
2642 /*!
2643  *  SMESH_Gen_i::GetMeshNames
2644  *
2645  *  Get names of meshes defined in file with the specified name
2646  */
2647 //================================================================================
2648 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2649 {
2650   SMESH::string_array_var aResult = new SMESH::string_array();
2651   MED::PWrapper aMed = MED::CrWrapper( theFileName );
2652   MED::TErr anErr;
2653   MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2654   if( anErr >= 0 ) {
2655     aResult->length( aNbMeshes );
2656     for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2657       MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2658       aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2659     }
2660   }
2661   return aResult._retn();
2662 }
2663
2664 //=============================================================================
2665 /*!
2666  *  SMESH_Gen_i::Save
2667  *
2668  *  Save SMESH module's data
2669  */
2670 //=============================================================================
2671 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
2672                                       const char*              theURL,
2673                                       bool                     isMultiFile )
2674 {
2675   INFOS( "SMESH_Gen_i::Save" );
2676
2677   //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
2678   // san -- in case <myCurrentStudy> differs from theComponent's study,
2679   // use that of the component
2680   if ( myCurrentStudy->_is_nil() ||
2681     theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
2682     SetCurrentStudy( theComponent->GetStudy() );
2683
2684   // Store study contents as a set of python commands
2685   SavePython(myCurrentStudy);
2686
2687   StudyContext* myStudyContext = GetCurrentStudyContext();
2688
2689   // Declare a byte stream
2690   SALOMEDS::TMPFile_var aStreamFile;
2691
2692   // Obtain a temporary dir
2693   TCollection_AsciiString tmpDir =
2694     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2695
2696   // Create a sequence of files processed
2697   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
2698   aFileSeq->length( NUM_TMP_FILES );
2699
2700   TCollection_AsciiString aStudyName( "" );
2701   if ( isMultiFile )
2702     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2703
2704   // Set names of temporary files
2705   TCollection_AsciiString filename =
2706     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
2707   TCollection_AsciiString meshfile =
2708     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
2709   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
2710   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
2711   filename = tmpDir + filename;
2712   meshfile = tmpDir + meshfile;
2713
2714   HDFfile*    aFile;
2715   HDFdataset* aDataset;
2716   HDFgroup*   aTopGroup;
2717   HDFgroup*   aGroup;
2718   HDFgroup*   aSubGroup;
2719   HDFgroup*   aSubSubGroup;
2720   hdf_size    aSize[ 1 ];
2721
2722
2723   //Remove the files if they exist: BugID: 11225
2724 #ifndef WNT /* unix functionality */
2725   TCollection_AsciiString cmd("rm -f \"");
2726 #else /* windows */
2727   TCollection_AsciiString cmd("del /F \"");
2728 #endif
2729
2730   cmd+=filename;
2731   cmd+="\" \"";
2732   cmd+=meshfile;
2733   cmd+="\"";
2734   system(cmd.ToCString());
2735
2736   // MED writer to be used by storage process
2737   DriverMED_W_SMESHDS_Mesh myWriter;
2738   myWriter.SetFile( meshfile.ToCString() );
2739
2740   // IMP issue 20918
2741   // SetStoreName() to groups before storing hypotheses to let them refer to
2742   // groups using "store name", which is "Group <group_persistent_id>"
2743   {
2744     SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
2745     for ( ; itBig->More(); itBig->Next() ) {
2746       SALOMEDS::SObject_var gotBranch = itBig->Value();
2747       if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
2748         CORBA::Object_var anObject = SObjectToObject( gotBranch );
2749         if ( !CORBA::is_nil( anObject ) ) {
2750           SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
2751           if ( !myMesh->_is_nil() ) {
2752             TPythonDump pd; // not to dump GetGroups()
2753             SMESH::ListOfGroups_var groups = myMesh->GetGroups();
2754             pd << ""; // to avoid optimizing pd out
2755             for ( int i = 0; i < groups->length(); ++i )
2756             {
2757               SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
2758               if ( grImpl )
2759               {
2760                 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
2761                 int anId = myStudyContext->findId( string( objStr.in() ) );
2762                 char grpName[ 30 ];
2763                 sprintf( grpName, "Group %d", anId );
2764                 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
2765                 aGrpBaseDS->SetStoreName( grpName );
2766               }
2767             }
2768           }
2769         }
2770       }
2771     }
2772   }
2773
2774   // Write data
2775   // ---> create HDF file
2776   aFile = new HDFfile( (char*) filename.ToCString() );
2777   aFile->CreateOnDisk();
2778
2779   // --> iterator for top-level objects
2780   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
2781   for ( ; itBig->More(); itBig->Next() ) {
2782     SALOMEDS::SObject_var gotBranch = itBig->Value();
2783
2784     // --> hypotheses root branch (only one for the study)
2785     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
2786       // create hypotheses root HDF group
2787       aTopGroup = new HDFgroup( "Hypotheses", aFile );
2788       aTopGroup->CreateOnDisk();
2789
2790       // iterator for all hypotheses
2791       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
2792       for ( ; it->More(); it->Next() ) {
2793         SALOMEDS::SObject_var mySObject = it->Value();
2794         CORBA::Object_var anObject = SObjectToObject( mySObject );
2795         if ( !CORBA::is_nil( anObject ) ) {
2796           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
2797           if ( !myHyp->_is_nil() ) {
2798             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2799             if ( myImpl ) {
2800               string hypname = string( myHyp->GetName() );
2801               string libname = string( myHyp->GetLibName() );
2802               // BUG SWP13062
2803               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
2804               // WNT and ".so" for X-system) must be deleted
2805               int libname_len = libname.length();
2806 #ifdef WNT
2807               if( libname_len > 4 )
2808                 libname.resize( libname_len - 4 );
2809 #else
2810               // PAL17753 (Regresion: missing hypothesis in restored study)
2811               // "lib" also should be removed from the beginning
2812               //if( libname_len > 3 )
2813                 //libname.resize( libname_len - 3 );
2814               if( libname_len > 6 )
2815                 libname = libname.substr( 3, libname_len - 3 - 3 );
2816 #endif
2817               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2818               int    id      = myStudyContext->findId( string( objStr.in() ) );
2819               string hypdata = string( myImpl->SaveTo() );
2820
2821               // for each hypothesis create HDF group basing on its id
2822               char hypGrpName[30];
2823               sprintf( hypGrpName, "Hypothesis %d", id );
2824               aGroup = new HDFgroup( hypGrpName, aTopGroup );
2825               aGroup->CreateOnDisk();
2826               // --> type name of hypothesis
2827               aSize[ 0 ] = hypname.length() + 1;
2828               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
2829               aDataset->CreateOnDisk();
2830               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
2831               aDataset->CloseOnDisk();
2832               // --> server plugin library name of hypothesis
2833               aSize[ 0 ] = libname.length() + 1;
2834               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
2835               aDataset->CreateOnDisk();
2836               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
2837               aDataset->CloseOnDisk();
2838               // --> persistent data of hypothesis
2839               aSize[ 0 ] = hypdata.length() + 1;
2840               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
2841               aDataset->CreateOnDisk();
2842               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
2843               aDataset->CloseOnDisk();
2844               // close hypothesis HDF group
2845               aGroup->CloseOnDisk();
2846             }
2847           }
2848         }
2849       }
2850       // close hypotheses root HDF group
2851       aTopGroup->CloseOnDisk();
2852     }
2853     // --> algorithms root branch (only one for the study)
2854     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
2855       // create algorithms root HDF group
2856       aTopGroup = new HDFgroup( "Algorithms", aFile );
2857       aTopGroup->CreateOnDisk();
2858
2859       // iterator for all algorithms
2860       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
2861       for ( ; it->More(); it->Next() ) {
2862         SALOMEDS::SObject_var mySObject = it->Value();
2863         CORBA::Object_var anObject = SObjectToObject( mySObject );
2864         if ( !CORBA::is_nil( anObject ) ) {
2865           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
2866           if ( !myHyp->_is_nil() ) {
2867             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2868             if ( myImpl ) {
2869               string hypname = string( myHyp->GetName() );
2870               string libname = string( myHyp->GetLibName() );
2871               // BUG SWP13062
2872               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
2873               // WNT and ".so" for X-system) must be deleted
2874               int libname_len = libname.length();
2875 #ifdef WNT
2876               if( libname_len > 4 )
2877                 libname.resize( libname_len - 4 );
2878 #else
2879               // PAL17753 (Regresion: missing hypothesis in restored study)
2880               // "lib" also should be removed from the beginning
2881               //if( libname_len > 3 )
2882                 //libname.resize( libname_len - 3 );
2883               if( libname_len > 6 )
2884                 libname = libname.substr( 3, libname_len - 3 - 3 );
2885 #endif
2886               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2887               int    id      = myStudyContext->findId( string( objStr.in() ) );
2888               string hypdata = string( myImpl->SaveTo() );
2889
2890               // for each algorithm create HDF group basing on its id
2891               char hypGrpName[30];
2892               sprintf( hypGrpName, "Algorithm %d", id );
2893               aGroup = new HDFgroup( hypGrpName, aTopGroup );
2894               aGroup->CreateOnDisk();
2895               // --> type name of algorithm
2896               aSize[0] = hypname.length() + 1;
2897               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
2898               aDataset->CreateOnDisk();
2899               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
2900               aDataset->CloseOnDisk();
2901               // --> server plugin library name of hypothesis
2902               aSize[0] = libname.length() + 1;
2903               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
2904               aDataset->CreateOnDisk();
2905               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
2906               aDataset->CloseOnDisk();
2907               // --> persistent data of algorithm
2908               aSize[0] = hypdata.length() + 1;
2909               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
2910               aDataset->CreateOnDisk();
2911               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
2912               aDataset->CloseOnDisk();
2913               // close algorithm HDF group
2914               aGroup->CloseOnDisk();
2915             }
2916           }
2917         }
2918       }
2919       // close algorithms root HDF group
2920       aTopGroup->CloseOnDisk();
2921     }
2922     // --> mesh objects roots branches
2923     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
2924       CORBA::Object_var anObject = SObjectToObject( gotBranch );
2925       if ( !CORBA::is_nil( anObject ) ) {
2926         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
2927         if ( !myMesh->_is_nil() ) {
2928           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
2929           if ( myImpl ) {
2930             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2931             int id = myStudyContext->findId( string( objStr.in() ) );
2932             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
2933             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
2934             bool hasShape = myLocMesh.HasShapeToMesh();
2935
2936             // for each mesh open the HDF group basing on its id
2937             char meshGrpName[ 30 ];
2938             sprintf( meshGrpName, "Mesh %d", id );
2939             aTopGroup = new HDFgroup( meshGrpName, aFile );
2940             aTopGroup->CreateOnDisk();
2941
2942             // --> put dataset to hdf file which is a flag that mesh has data
2943             string strHasData = "0";
2944             // check if the mesh is not empty
2945             if ( mySMESHDSMesh->NbNodes() > 0 ) {
2946               // write mesh data to med file
2947               myWriter.SetMesh( mySMESHDSMesh );
2948               myWriter.SetMeshId( id );
2949               strHasData = "1";
2950             }
2951             aSize[ 0 ] = strHasData.length() + 1;
2952             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
2953             aDataset->CreateOnDisk();
2954             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
2955             aDataset->CloseOnDisk();
2956
2957             // ouv : NPAL12872
2958             // for each mesh open the HDF group basing on its auto color parameter
2959             char meshAutoColorName[ 30 ];
2960             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
2961             int anAutoColor[1];
2962             anAutoColor[0] = myImpl->GetAutoColor();
2963             aSize[ 0 ] = 1;
2964             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
2965             aDataset->CreateOnDisk();
2966             aDataset->WriteOnDisk( anAutoColor );
2967             aDataset->CloseOnDisk();
2968
2969             // issue 0020693. Store _isModified flag
2970             int isModified = myLocMesh.GetIsModified();
2971             aSize[ 0 ] = 1;
2972             aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
2973             aDataset->CreateOnDisk();
2974             aDataset->WriteOnDisk( &isModified );
2975             aDataset->CloseOnDisk();
2976
2977             // issue 20918. Store Persistent Id of SMESHDS_Mesh
2978             int meshPersistentId = mySMESHDSMesh->GetPersistentId();
2979             aSize[ 0 ] = 1;
2980             aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
2981             aDataset->CreateOnDisk();
2982             aDataset->WriteOnDisk( &meshPersistentId );
2983             aDataset->CloseOnDisk();
2984
2985             // write reference on a shape if exists
2986             SALOMEDS::SObject_var myRef;
2987             bool shapeRefFound = false;
2988             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
2989             if ( found ) {
2990               SALOMEDS::SObject_var myShape;
2991               bool ok = myRef->ReferencedObject( myShape );
2992               if ( ok ) {
2993                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
2994                 string myRefOnObject = myShape->GetID();
2995                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
2996                   aSize[ 0 ] = myRefOnObject.length() + 1;
2997                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
2998                   aDataset->CreateOnDisk();
2999                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3000                   aDataset->CloseOnDisk();
3001                 }
3002               }
3003             }
3004
3005             // write applied hypotheses if exist
3006             SALOMEDS::SObject_var myHypBranch;
3007             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
3008             if ( found && !shapeRefFound && hasShape) { // remove applied hyps
3009               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3010             }
3011             if ( found && (shapeRefFound || !hasShape) ) {
3012               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3013               aGroup->CreateOnDisk();
3014
3015               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
3016               int hypNb = 0;
3017               for ( ; it->More(); it->Next() ) {
3018                 SALOMEDS::SObject_var mySObject = it->Value();
3019                 SALOMEDS::SObject_var myRefOnHyp;
3020                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
3021                 if ( ok ) {
3022                   // san - it is impossible to recover applied hypotheses
3023                   //       using their entries within Load() method,
3024                   // for there are no AttributeIORs in the study when Load() is working.
3025                   // Hence, it is better to store persistent IDs of hypotheses as references to them
3026
3027                   //string myRefOnObject = myRefOnHyp->GetID();
3028                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3029                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3030                   int id = myStudyContext->findId( string( objStr.in() ) );
3031                   //if ( myRefOnObject.length() > 0 ) {
3032                   //aSize[ 0 ] = myRefOnObject.length() + 1;
3033                   char hypName[ 30 ], hypId[ 30 ];
3034                   sprintf( hypName, "Hyp %d", ++hypNb );
3035                   sprintf( hypId, "%d", id );
3036                   aSize[ 0 ] = strlen( hypId ) + 1;
3037                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3038                   aDataset->CreateOnDisk();
3039                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3040                   aDataset->WriteOnDisk( hypId );
3041                   aDataset->CloseOnDisk();
3042                   //}
3043                 }
3044               }
3045               aGroup->CloseOnDisk();
3046             }
3047
3048             // write applied algorithms if exist
3049             SALOMEDS::SObject_var myAlgoBranch;
3050             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
3051             if ( found && !shapeRefFound && hasShape) { // remove applied algos
3052               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3053             }
3054             if ( found && (shapeRefFound || !hasShape)) {
3055               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3056               aGroup->CreateOnDisk();
3057
3058               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
3059               int algoNb = 0;
3060               for ( ; it->More(); it->Next() ) {
3061                 SALOMEDS::SObject_var mySObject = it->Value();
3062                 SALOMEDS::SObject_var myRefOnAlgo;
3063                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
3064                 if ( ok ) {
3065                   // san - it is impossible to recover applied algorithms
3066                   //       using their entries within Load() method,
3067                   // for there are no AttributeIORs in the study when Load() is working.
3068                   // Hence, it is better to store persistent IDs of algorithms as references to them
3069
3070                   //string myRefOnObject = myRefOnAlgo->GetID();
3071                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3072                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3073                   int id = myStudyContext->findId( string( objStr.in() ) );
3074                   //if ( myRefOnObject.length() > 0 ) {
3075                   //aSize[ 0 ] = myRefOnObject.length() + 1;
3076                   char algoName[ 30 ], algoId[ 30 ];
3077                   sprintf( algoName, "Algo %d", ++algoNb );
3078                   sprintf( algoId, "%d", id );
3079                   aSize[ 0 ] = strlen( algoId ) + 1;
3080                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3081                   aDataset->CreateOnDisk();
3082                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3083                   aDataset->WriteOnDisk( algoId );
3084                   aDataset->CloseOnDisk();
3085                   //}
3086                 }
3087               }
3088               aGroup->CloseOnDisk();
3089             }
3090
3091             // --> submesh objects sub-branches
3092
3093             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3094               SALOMEDS::SObject_var mySubmeshBranch;
3095               found = gotBranch->FindSubObject( i, mySubmeshBranch );
3096
3097               if ( found ) // check if there is shape reference in submeshes
3098               {
3099                 bool hasShapeRef = false;
3100                 SALOMEDS::ChildIterator_var itSM =
3101                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
3102                 for ( ; itSM->More(); itSM->Next() ) {
3103                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
3104                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
3105                     mySubRef->ReferencedObject( myShape );
3106                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3107                     hasShapeRef = true;
3108                   else
3109                   { // remove one submesh
3110                     if ( shapeRefFound )
3111                     { // unassign hypothesis
3112                       SMESH::SMESH_subMesh_var mySubMesh =
3113                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3114                       if ( !mySubMesh->_is_nil() ) {
3115                         int shapeID = mySubMesh->GetId();
3116                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3117                         const list<const SMESHDS_Hypothesis*>& hypList =
3118                           mySMESHDSMesh->GetHypothesis( S );
3119                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3120                         while ( hyp != hypList.end() ) {
3121                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
3122                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3123                         }
3124                       }
3125                     }
3126                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3127                   }
3128                 } // loop on submeshes of a type
3129                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3130                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3131                   found = false;
3132                 }
3133               }  // end check if there is shape reference in submeshes
3134               if ( found ) {
3135                 char name_meshgroup[ 30 ];
3136                 if ( i == GetSubMeshOnVertexTag() )
3137                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
3138                 else if ( i == GetSubMeshOnEdgeTag() )
3139                   strcpy( name_meshgroup, "SubMeshes On Edge" );
3140                 else if ( i == GetSubMeshOnWireTag() )
3141                   strcpy( name_meshgroup, "SubMeshes On Wire" );
3142                 else if ( i == GetSubMeshOnFaceTag() )
3143                   strcpy( name_meshgroup, "SubMeshes On Face" );
3144                 else if ( i == GetSubMeshOnShellTag() )
3145                   strcpy( name_meshgroup, "SubMeshes On Shell" );
3146                 else if ( i == GetSubMeshOnSolidTag() )
3147                   strcpy( name_meshgroup, "SubMeshes On Solid" );
3148                 else if ( i == GetSubMeshOnCompoundTag() )
3149                   strcpy( name_meshgroup, "SubMeshes On Compound" );
3150
3151                 // for each type of submeshes create container HDF group
3152                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3153                 aGroup->CreateOnDisk();
3154
3155                 // iterator for all submeshes of given type
3156                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
3157                 for ( ; itSM->More(); itSM->Next() ) {
3158                   SALOMEDS::SObject_var mySObject = itSM->Value();
3159                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3160                   if ( !CORBA::is_nil( anSubObject ))
3161                   {
3162                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3163                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3164                     int subid = myStudyContext->findId( string( objStr.in() ) );
3165
3166                     // for each mesh open the HDF group basing on its id
3167                     char submeshGrpName[ 30 ];
3168                     sprintf( submeshGrpName, "SubMesh %d", subid );
3169                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3170                     aSubGroup->CreateOnDisk();
3171
3172                     // write reference on a shape, already checked if it exists
3173                     SALOMEDS::SObject_var mySubRef, myShape;
3174                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
3175                       mySubRef->ReferencedObject( myShape );
3176                     string myRefOnObject = myShape->GetID();
3177                     if ( myRefOnObject.length() > 0 ) {
3178                       aSize[ 0 ] = myRefOnObject.length() + 1;
3179                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3180                       aDataset->CreateOnDisk();
3181                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3182                       aDataset->CloseOnDisk();
3183                     }
3184
3185                     // write applied hypotheses if exist
3186                     SALOMEDS::SObject_var mySubHypBranch;
3187                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
3188                     if ( found ) {
3189                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3190                       aSubSubGroup->CreateOnDisk();
3191
3192                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
3193                       int hypNb = 0;
3194                       for ( ; it->More(); it->Next() ) {
3195                         SALOMEDS::SObject_var mySubSObject = it->Value();
3196                         SALOMEDS::SObject_var myRefOnHyp;
3197                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
3198                         if ( ok ) {
3199                           //string myRefOnObject = myRefOnHyp->GetID();
3200                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3201                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3202                           int id = myStudyContext->findId( string( objStr.in() ) );
3203                           //if ( myRefOnObject.length() > 0 ) {
3204                           //aSize[ 0 ] = myRefOnObject.length() + 1;
3205                           char hypName[ 30 ], hypId[ 30 ];
3206                           sprintf( hypName, "Hyp %d", ++hypNb );
3207                           sprintf( hypId, "%d", id );
3208                           aSize[ 0 ] = strlen( hypId ) + 1;
3209                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3210                           aDataset->CreateOnDisk();
3211                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3212                           aDataset->WriteOnDisk( hypId );
3213                           aDataset->CloseOnDisk();
3214                           //}
3215                         }
3216                       }
3217                       aSubSubGroup->CloseOnDisk();
3218                     }
3219
3220                     // write applied algorithms if exist
3221                     SALOMEDS::SObject_var mySubAlgoBranch;
3222                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
3223                     if ( found ) {
3224                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3225                       aSubSubGroup->CreateOnDisk();
3226
3227                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
3228                       int algoNb = 0;
3229                       for ( ; it->More(); it->Next() ) {
3230                         SALOMEDS::SObject_var mySubSObject = it->Value();
3231                         SALOMEDS::SObject_var myRefOnAlgo;
3232                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
3233                         if ( ok ) {
3234                           //string myRefOnObject = myRefOnAlgo->GetID();
3235                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3236                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3237                           int id = myStudyContext->findId( string( objStr.in() ) );
3238                           //if ( myRefOnObject.length() > 0 ) {
3239                           //aSize[ 0 ] = myRefOnObject.length() + 1;
3240                           char algoName[ 30 ], algoId[ 30 ];
3241                           sprintf( algoName, "Algo %d", ++algoNb );
3242                           sprintf( algoId, "%d", id );
3243                           aSize[ 0 ] = strlen( algoId ) + 1;
3244                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3245                           aDataset->CreateOnDisk();
3246                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3247                           aDataset->WriteOnDisk( algoId );
3248                           aDataset->CloseOnDisk();
3249                           //}
3250                         }
3251                       }
3252                       aSubSubGroup->CloseOnDisk();
3253                     }
3254                     // close submesh HDF group
3255                     aSubGroup->CloseOnDisk();
3256                   }
3257                 }
3258                 // close container of submeshes by type HDF group
3259                 aGroup->CloseOnDisk();
3260               }
3261             }
3262             // All sub-meshes will be stored in MED file
3263             // .. will NOT (PAL 12992)
3264             //if ( shapeRefFound )
3265             //myWriter.AddAllSubMeshes();
3266
3267             // store submesh order if any
3268             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3269             if ( theOrderIds.size() ) {
3270               char order_list[ 30 ];
3271               strcpy( order_list, "Mesh Order" );
3272               // count number of submesh ids
3273               int nbIDs = 0;
3274               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3275               for ( ; idIt != theOrderIds.end(); idIt++ )
3276                 nbIDs += (*idIt).size();
3277               // number of values = number of IDs +
3278               //                    number of lists (for separators) - 1
3279               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3280               idIt = theOrderIds.begin();
3281               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3282                 const TListOfInt& idList = *idIt;
3283                 if (idIt != theOrderIds.begin()) // not first list
3284                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3285                 // dump submesh ids from current list
3286                 TListOfInt::const_iterator id_smId = idList.begin();
3287                 for( ; id_smId != idList.end(); id_smId++ )
3288                   smIDs[ i++ ] = *id_smId;
3289               }
3290               // write HDF group
3291               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3292
3293               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3294               aDataset->CreateOnDisk();
3295               aDataset->WriteOnDisk( smIDs );
3296               aDataset->CloseOnDisk();
3297               //
3298               delete[] smIDs;
3299             }
3300
3301             // groups root sub-branch
3302             SALOMEDS::SObject_var myGroupsBranch;
3303             for ( int i = GetNodeGroupsTag(); i <= Get0DElementsGroupsTag(); i++ ) {
3304               found = gotBranch->FindSubObject( i, myGroupsBranch );
3305               if ( found ) {
3306                 char name_group[ 30 ];
3307                 if ( i == GetNodeGroupsTag() )
3308                   strcpy( name_group, "Groups of Nodes" );
3309                 else if ( i == GetEdgeGroupsTag() )
3310                   strcpy( name_group, "Groups of Edges" );
3311                 else if ( i == GetFaceGroupsTag() )
3312                   strcpy( name_group, "Groups of Faces" );
3313                 else if ( i == GetVolumeGroupsTag() )
3314                   strcpy( name_group, "Groups of Volumes" );
3315                 else if ( i == Get0DElementsGroupsTag() )
3316                   strcpy( name_group, "Groups of 0D Elements" );
3317
3318                 aGroup = new HDFgroup( name_group, aTopGroup );
3319                 aGroup->CreateOnDisk();
3320
3321                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
3322                 for ( ; it->More(); it->Next() ) {
3323                   SALOMEDS::SObject_var mySObject = it->Value();
3324                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3325                   if ( !CORBA::is_nil( aSubObject ) ) {
3326                     SMESH_GroupBase_i* myGroupImpl =
3327                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3328                     if ( !myGroupImpl )
3329                       continue;
3330                     SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3331                     if ( !aGrpBaseDS )
3332                       continue;
3333
3334                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3335                     int anId = myStudyContext->findId( string( objStr.in() ) );
3336
3337                     // For each group, create a dataset named "Group <group_persistent_id>"
3338                     // and store the group's user name into it
3339                     const char* grpName = aGrpBaseDS->GetStoreName();
3340                     char* aUserName = myGroupImpl->GetName();
3341                     aSize[ 0 ] = strlen( aUserName ) + 1;
3342
3343                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3344                     aDataset->CreateOnDisk();
3345                     aDataset->WriteOnDisk( aUserName );
3346                     aDataset->CloseOnDisk();
3347
3348                     // ouv : NPAL12872
3349                     // For each group, create a dataset named "Group <group_persistent_id> Color"
3350                     // and store the group's color into it
3351                     char grpColorName[ 30 ];
3352                     sprintf( grpColorName, "ColorGroup %d", anId );
3353                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
3354                     double anRGB[3];
3355                     anRGB[ 0 ] = aColor.R;
3356                     anRGB[ 1 ] = aColor.G;
3357                     anRGB[ 2 ] = aColor.B;
3358                     aSize[ 0 ] = 3;
3359                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3360                     aDataset->CreateOnDisk();
3361                     aDataset->WriteOnDisk( anRGB );
3362                     aDataset->CloseOnDisk();
3363
3364                     // Pass SMESHDS_Group to MED writer
3365                     SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3366                     if ( aGrpDS )
3367                       myWriter.AddGroup( aGrpDS );
3368
3369                     // write reference on a shape if exists
3370                     SMESHDS_GroupOnGeom* aGeomGrp =
3371                       dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3372                     if ( aGeomGrp ) {
3373                       SALOMEDS::SObject_var mySubRef, myShape;
3374                       if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
3375                           mySubRef->ReferencedObject( myShape ) &&
3376                           !CORBA::is_nil( myShape->GetObject() ))
3377                       {
3378                         string myRefOnObject = myShape->GetID();
3379                         if ( myRefOnObject.length() > 0 ) {
3380                           char aRefName[ 30 ];
3381                           sprintf( aRefName, "Ref on shape %d", anId);
3382                           aSize[ 0 ] = myRefOnObject.length() + 1;
3383                           aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3384                           aDataset->CreateOnDisk();
3385                           aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3386                           aDataset->CloseOnDisk();
3387                         }
3388                       }
3389                       else // shape ref is invalid:
3390                       {
3391                         // save a group on geometry as ordinary group
3392                         myWriter.AddGroup( aGeomGrp );
3393                       }
3394                     }
3395                     else if ( SMESH_GroupOnFilter_i* aFilterGrp_i = 
3396                               dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3397                     {
3398                       std::string str = aFilterGrp_i->FilterToString();
3399                       std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3400                       aSize[ 0 ] = str.length() + 1;
3401                       aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3402                       aDataset->CreateOnDisk();
3403                       aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3404                       aDataset->CloseOnDisk();
3405                     }
3406                   }
3407                 }
3408                 aGroup->CloseOnDisk();
3409               }
3410             } // loop on groups
3411
3412             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3413             {
3414               // Flush current mesh information into MED file
3415               myWriter.Perform();
3416
3417               // maybe a shape was deleted in the study
3418               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3419                 TopoDS_Shape nullShape;
3420                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3421               }
3422
3423               if ( !mySMESHDSMesh->SubMeshes().empty() )
3424               {
3425                 // Store submeshes
3426                 // ----------------
3427                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3428                 aGroup->CreateOnDisk();
3429
3430                 // each element belongs to one or none submesh,
3431                 // so for each node/element, we store a submesh ID
3432
3433                 // Make maps of submesh IDs of elements sorted by element IDs
3434                 typedef int TElemID;
3435                 typedef int TSubMID;
3436                 map< TElemID, TSubMID > eId2smId, nId2smId;
3437                 map< TElemID, TSubMID >::iterator hint; // insertion to map is done before hint
3438                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
3439                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
3440                 SMDS_NodeIteratorPtr itNode;
3441                 SMDS_ElemIteratorPtr itElem;
3442                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
3443                 {
3444                   TSubMID          aSubMeID = itSubM->first;
3445                   SMESHDS_SubMesh* aSubMesh = itSubM->second;
3446                   if ( aSubMesh->IsComplexSubmesh() )
3447                     continue; // submesh containing other submeshs
3448                   // nodes
3449                   hint = nId2smId.begin(); // optimize insertion basing on increasing order of elem Ids in submesh
3450                   for ( itNode = aSubMesh->GetNodes(); itNode->more(); ++hint)
3451                     hint = nId2smId.insert( hint, make_pair( itNode->next()->GetID(), aSubMeID ));
3452                   // elements
3453                   hint = eId2smId.begin();
3454                   for ( itElem = aSubMesh->GetElements(); itElem->more(); ++hint)
3455                     hint = eId2smId.insert( hint, make_pair( itElem->next()->GetID(), aSubMeID ));
3456                 }
3457
3458                 // Care of elements that are not on submeshes
3459                 if ( mySMESHDSMesh->NbNodes() != nId2smId.size() ) {
3460                   for ( itNode = mySMESHDSMesh->nodesIterator(); itNode->more(); )
3461                     /*  --- stl_map.h says : */
3462                     /*  A %map relies on unique keys and thus a %pair is only inserted if its */
3463                     /*  first element (the key) is not already present in the %map.           */
3464                     nId2smId.insert( make_pair( itNode->next()->GetID(), 0 ));
3465                 }
3466                 int nbElems = mySMESHDSMesh->NbEdges() + mySMESHDSMesh->NbFaces() + mySMESHDSMesh->NbVolumes();
3467                 if ( nbElems != eId2smId.size() ) {
3468                   for ( itElem = mySMESHDSMesh->elementsIterator(); itElem->more(); )
3469                     eId2smId.insert( make_pair( itElem->next()->GetID(), 0 ));
3470                 }
3471
3472                 // Store submesh IDs
3473                 for ( int isNode = 0; isNode < 2; ++isNode )
3474                 {
3475                   map< TElemID, TSubMID >& id2smId = isNode ? nId2smId : eId2smId;
3476                   if ( id2smId.empty() ) continue;
3477                   map< TElemID, TSubMID >::const_iterator id_smId = id2smId.begin();
3478                   // make and fill array of submesh IDs
3479                   int* smIDs = new int [ id2smId.size() ];
3480                   for ( int i = 0; id_smId != id2smId.end(); ++id_smId, ++i )
3481                     smIDs[ i ] = id_smId->second;
3482                   // write HDF group
3483                   aSize[ 0 ] = id2smId.size();
3484                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3485                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3486                   aDataset->CreateOnDisk();
3487                   aDataset->WriteOnDisk( smIDs );
3488                   aDataset->CloseOnDisk();
3489                   //
3490                   delete[] smIDs;
3491                 }
3492
3493                 aGroup->CloseOnDisk();
3494
3495                 // Store node positions on sub-shapes (SMDS_Position):
3496                 // ----------------------------------------------------
3497
3498                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3499                 aGroup->CreateOnDisk();
3500
3501                 // in aGroup, create 5 datasets to contain:
3502                 // "Nodes on Edges" - ID of node on edge
3503                 // "Edge positions" - U parameter on node on edge
3504                 // "Nodes on Faces" - ID of node on face
3505                 // "Face U positions" - U parameter of node on face
3506                 // "Face V positions" - V parameter of node on face
3507
3508                 // Find out nb of nodes on edges and faces
3509                 // Collect corresponing sub-meshes
3510                 int nbEdgeNodes = 0, nbFaceNodes = 0;
3511                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3512                 // loop on SMESHDS_SubMesh'es
3513                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
3514                 {
3515                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
3516                   if ( aSubMesh->IsComplexSubmesh() )
3517                     continue; // submesh containing other submeshs
3518                   int nbNodes = aSubMesh->NbNodes();
3519                   if ( nbNodes == 0 ) continue;
3520
3521                   int aShapeID = (*itSubM).first;
3522                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3523                     continue;
3524                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3525                   // write only SMDS_FacePosition and SMDS_EdgePosition
3526                   switch ( aShapeType ) {
3527                   case TopAbs_FACE:
3528                     nbFaceNodes += nbNodes;
3529                     aFaceSM.push_back( aSubMesh );
3530                     break;
3531                   case TopAbs_EDGE:
3532                     nbEdgeNodes += nbNodes;
3533                     aEdgeSM.push_back( aSubMesh );
3534                     break;
3535                   default:
3536                     continue;
3537                   }
3538                 }
3539                 // Treat positions on edges or faces
3540                 for ( int onFace = 0; onFace < 2; onFace++ )
3541                 {
3542                   // Create arrays to store in datasets
3543                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3544                   if (!nbNodes) continue;
3545                   int* aNodeIDs = new int [ nbNodes ];
3546                   double* aUPos = new double [ nbNodes ];
3547                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3548
3549                   // Fill arrays
3550                   // loop on sub-meshes
3551                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3552                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3553                   for ( ; itSM != pListSM->end(); itSM++ )
3554                   {
3555                     SMESHDS_SubMesh* aSubMesh = (*itSM);
3556
3557                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3558                     // loop on nodes in aSubMesh
3559                     while ( itNode->more() )
3560                     {
3561                       //node ID
3562                       const SMDS_MeshNode* node = itNode->next();
3563                       aNodeIDs [ iNode ] = node->GetID();
3564
3565                       // Position
3566                       const SMDS_PositionPtr pos = node->GetPosition();
3567                       if ( onFace ) { // on FACE
3568                         const SMDS_FacePosition* fPos =
3569                           dynamic_cast<const SMDS_FacePosition*>( pos );
3570                         if ( fPos ) {
3571                           aUPos[ iNode ] = fPos->GetUParameter();
3572                           aVPos[ iNode ] = fPos->GetVParameter();
3573                           iNode++;
3574                         }
3575                         else
3576                           nbNodes--;
3577                       }
3578                       else { // on EDGE
3579                         const SMDS_EdgePosition* ePos =
3580                           dynamic_cast<const SMDS_EdgePosition*>( pos );
3581                         if ( ePos ) {
3582                           aUPos[ iNode ] = ePos->GetUParameter();
3583                           iNode++;
3584                         }
3585                         else
3586                           nbNodes--;
3587                       }
3588                     } // loop on nodes in aSubMesh
3589                   } // loop on sub-meshes
3590
3591                   // Write datasets
3592                   if ( nbNodes )
3593                   {
3594                     aSize[ 0 ] = nbNodes;
3595                     // IDS
3596                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3597                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3598                     aDataset->CreateOnDisk();
3599                     aDataset->WriteOnDisk( aNodeIDs );
3600                     aDataset->CloseOnDisk();
3601
3602                     // U Positions
3603                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
3604                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3605                     aDataset->CreateOnDisk();
3606                     aDataset->WriteOnDisk( aUPos );
3607                     aDataset->CloseOnDisk();
3608                     // V Positions
3609                     if ( onFace ) {
3610                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3611                       aDataset->CreateOnDisk();
3612                       aDataset->WriteOnDisk( aVPos );
3613                       aDataset->CloseOnDisk();
3614                     }
3615                   }
3616                   delete [] aNodeIDs;
3617                   delete [] aUPos;
3618                   if ( aVPos ) delete [] aVPos;
3619
3620                 } // treat positions on edges or faces
3621
3622                 // close "Node Positions" group
3623                 aGroup->CloseOnDisk();
3624
3625               } // if ( there are submeshes in SMESHDS_Mesh )
3626             } // if ( hasData )
3627
3628             // close mesh HDF group
3629             aTopGroup->CloseOnDisk();
3630           }
3631         }
3632       }
3633     }
3634   }
3635
3636   // close HDF file
3637   aFile->CloseOnDisk();
3638   delete aFile;
3639
3640   // Convert temporary files to stream
3641   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
3642
3643   // Remove temporary files and directory
3644   if ( !isMultiFile )
3645     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3646
3647   INFOS( "SMESH_Gen_i::Save() completed" );
3648   return aStreamFile._retn();
3649 }
3650
3651 //=============================================================================
3652 /*!
3653  *  SMESH_Gen_i::SaveASCII
3654  *
3655  *  Save SMESH module's data in ASCII format
3656  */
3657 //=============================================================================
3658
3659 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3660                                            const char*              theURL,
3661                                            bool                     isMultiFile ) {
3662   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3663   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3664   return aStreamFile._retn();
3665
3666   //after usual saving needs to encipher binary to text string
3667   //Any binary symbol will be represent as "|xx" () hexadecimal format number
3668   int size = aStreamFile.in().length();
3669   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3670   for ( int i = 0; i < size; i++ )
3671     sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
3672
3673   buffer[size * 3] = '\0';
3674
3675   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3676
3677   return anAsciiStreamFile._retn();
3678 }
3679
3680 //=============================================================================
3681 /*!
3682  *  SMESH_Gen_i::loadGeomData
3683  *
3684  *  Load GEOM module data
3685  */
3686 //=============================================================================
3687
3688 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3689 {
3690   if ( theCompRoot->_is_nil() )
3691     return;
3692
3693   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
3694   if ( aStudy->_is_nil() )
3695     return;
3696
3697   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
3698   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3699 }
3700 //=============================================================================
3701 /*!
3702  * \brief Creates SMDS_Position according to shape type
3703  */
3704 //=============================================================================
3705
3706 class PositionCreator {
3707 public:
3708   SMDS_PositionPtr MakePosition(const TopAbs_ShapeEnum type) {
3709     return (this->*myFuncTable[ type ])();
3710   }
3711   PositionCreator() {
3712     myFuncTable.resize( (size_t) TopAbs_SHAPE, & PositionCreator::defaultPosition );
3713     myFuncTable[ TopAbs_SOLID  ] = & PositionCreator::volumePosition;
3714     myFuncTable[ TopAbs_FACE   ] = & PositionCreator::facePosition;
3715     myFuncTable[ TopAbs_EDGE   ] = & PositionCreator::edgePosition;
3716     myFuncTable[ TopAbs_VERTEX ] = & PositionCreator::vertexPosition;
3717   }
3718 private:
3719   SMDS_PositionPtr edgePosition()    const { return SMDS_PositionPtr( new SMDS_EdgePosition  ); }
3720   SMDS_PositionPtr facePosition()    const { return SMDS_PositionPtr( new SMDS_FacePosition  ); }
3721   SMDS_PositionPtr volumePosition()  const { return SMDS_PositionPtr( new SMDS_SpacePosition ); }
3722   SMDS_PositionPtr vertexPosition()  const { return SMDS_PositionPtr( new SMDS_VertexPosition); }
3723   SMDS_PositionPtr defaultPosition() const { return SMDS_SpacePosition::originSpacePosition();  }
3724   typedef SMDS_PositionPtr (PositionCreator:: * FmakePos)() const;
3725   vector<FmakePos> myFuncTable;
3726 };
3727
3728 //=============================================================================
3729 /*!
3730  *  SMESH_Gen_i::Load
3731  *
3732  *  Load SMESH module's data
3733  */
3734 //=============================================================================
3735
3736 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
3737                         const SALOMEDS::TMPFile& theStream,
3738                         const char*              theURL,
3739                         bool                     isMultiFile )
3740 {
3741   INFOS( "SMESH_Gen_i::Load" );
3742
3743   if ( myCurrentStudy->_is_nil() ||
3744        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
3745     SetCurrentStudy( theComponent->GetStudy() );
3746
3747   /*  if( !theComponent->_is_nil() )
3748       {
3749       //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
3750       if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
3751       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
3752       }*/
3753
3754   StudyContext* myStudyContext = GetCurrentStudyContext();
3755
3756   // Get temporary files location
3757   TCollection_AsciiString tmpDir =
3758     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3759
3760     INFOS( "THE URL++++++++++++++" )
3761     INFOS( theURL );
3762     INFOS( "THE TMP PATH+++++++++" );
3763     INFOS( tmpDir );
3764
3765   // Convert the stream into sequence of files to process
3766   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
3767                                                                             tmpDir.ToCString(),
3768                                                                             isMultiFile );
3769   TCollection_AsciiString aStudyName( "" );
3770   if ( isMultiFile )
3771     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
3772
3773   // Set names of temporary files
3774   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
3775   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
3776
3777   int size;
3778   HDFfile*    aFile;
3779   HDFdataset* aDataset;
3780   HDFgroup*   aTopGroup;
3781   HDFgroup*   aGroup;
3782   HDFgroup*   aSubGroup;
3783   HDFgroup*   aSubSubGroup;
3784
3785   // Read data
3786   // ---> open HDF file
3787   aFile = new HDFfile( (char*) filename.ToCString() );
3788   try {
3789     aFile->OpenOnDisk( HDF_RDONLY );
3790   }
3791   catch ( HDFexception ) {
3792     INFOS( "Load(): " << filename << " not found!" );
3793     return false;
3794   }
3795
3796   DriverMED_R_SMESHDS_Mesh myReader;
3797   myReader.SetFile( meshfile.ToCString() );
3798
3799   // For PAL13473 ("Repetitive mesh") implementation.
3800   // New dependencies between SMESH objects are established:
3801   // now hypotheses can refer to meshes, shapes and other hypotheses.
3802   // To keep data consistent, the following order of data restoration
3803   // imposed:
3804   // 1. Create hypotheses
3805   // 2. Create all meshes
3806   // 3. Load hypotheses' data
3807   // 4. All the rest
3808
3809   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
3810   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
3811
3812   // get total number of top-level groups
3813   int aNbGroups = aFile->nInternalObjects();
3814   if ( aNbGroups > 0 ) {
3815     // --> in first turn we should read&create hypotheses
3816     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
3817       // open hypotheses root HDF group
3818       aTopGroup = new HDFgroup( "Hypotheses", aFile );
3819       aTopGroup->OpenOnDisk();
3820
3821       // get number of hypotheses
3822       int aNbObjects = aTopGroup->nInternalObjects();
3823       for ( int j = 0; j < aNbObjects; j++ ) {
3824         // try to identify hypothesis
3825         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
3826         aTopGroup->InternalObjectIndentify( j, hypGrpName );
3827
3828         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
3829           // open hypothesis group
3830           aGroup = new HDFgroup( hypGrpName, aTopGroup );
3831           aGroup->OpenOnDisk();
3832
3833           // --> get hypothesis id
3834           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
3835           string hypname;
3836           string libname;
3837           string hypdata;
3838
3839           // get number of datasets
3840           int aNbSubObjects = aGroup->nInternalObjects();
3841           for ( int k = 0; k < aNbSubObjects; k++ ) {
3842             // identify dataset
3843             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
3844             aGroup->InternalObjectIndentify( k, name_of_subgroup );
3845             // --> get hypothesis name
3846             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
3847               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3848               aDataset->OpenOnDisk();
3849               size = aDataset->GetSize();
3850               char* hypname_str = new char[ size ];
3851               aDataset->ReadFromDisk( hypname_str );
3852               hypname = string( hypname_str );
3853               delete [] hypname_str;
3854               aDataset->CloseOnDisk();
3855             }
3856             // --> get hypothesis plugin library name
3857             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
3858               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3859               aDataset->OpenOnDisk();
3860               size = aDataset->GetSize();
3861               char* libname_str = new char[ size ];
3862               aDataset->ReadFromDisk( libname_str );
3863               if(MYDEBUG) SCRUTE( libname_str );
3864               libname = string( libname_str );
3865               delete [] libname_str;
3866               aDataset->CloseOnDisk();
3867             }
3868             // --> get hypothesis data
3869             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
3870               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3871               aDataset->OpenOnDisk();
3872               size = aDataset->GetSize();
3873               char* hypdata_str = new char[ size ];
3874               aDataset->ReadFromDisk( hypdata_str );
3875               hypdata = string( hypdata_str );
3876               delete [] hypdata_str;
3877               aDataset->CloseOnDisk();
3878             }
3879           }
3880           // close hypothesis HDF group
3881           aGroup->CloseOnDisk();
3882
3883           // --> restore hypothesis from data
3884           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
3885             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
3886                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
3887             SMESH::SMESH_Hypothesis_var myHyp;
3888
3889             try { // protect persistence mechanism against exceptions
3890               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
3891             }
3892             catch (...) {
3893               INFOS( "Exception during hypothesis creation" );
3894             }
3895
3896             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3897             if ( myImpl ) {
3898               // myImpl->LoadFrom( hypdata.c_str() );
3899               hypDataList.push_back( make_pair( myImpl, hypdata ));
3900               string iorString = GetORB()->object_to_string( myHyp );
3901               int newId = myStudyContext->findId( iorString );
3902               myStudyContext->mapOldToNew( id, newId );
3903             }
3904             else
3905               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
3906           }
3907         }
3908       }
3909       // close hypotheses root HDF group
3910       aTopGroup->CloseOnDisk();
3911       aTopGroup = 0;
3912     }
3913
3914     // --> then we should read&create algorithms
3915     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
3916       // open algorithms root HDF group
3917       aTopGroup = new HDFgroup( "Algorithms", aFile );
3918       aTopGroup->OpenOnDisk();
3919
3920       // get number of algorithms
3921       int aNbObjects = aTopGroup->nInternalObjects();
3922       for ( int j = 0; j < aNbObjects; j++ ) {
3923         // try to identify algorithm
3924         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
3925         aTopGroup->InternalObjectIndentify( j, hypGrpName );
3926
3927         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
3928           // open algorithm group
3929           aGroup = new HDFgroup( hypGrpName, aTopGroup );
3930           aGroup->OpenOnDisk();
3931
3932           // --> get algorithm id
3933           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
3934           string hypname;
3935           string libname;
3936           string hypdata;
3937
3938           // get number of datasets
3939           int aNbSubObjects = aGroup->nInternalObjects();
3940           for ( int k = 0; k < aNbSubObjects; k++ ) {
3941             // identify dataset
3942             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
3943             aGroup->InternalObjectIndentify( k, name_of_subgroup );
3944             // --> get algorithm name
3945             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
3946               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3947               aDataset->OpenOnDisk();
3948               size = aDataset->GetSize();
3949               char* hypname_str = new char[ size ];
3950               aDataset->ReadFromDisk( hypname_str );
3951               hypname = string( hypname_str );
3952               delete [] hypname_str;
3953               aDataset->CloseOnDisk();
3954             }
3955             // --> get algorithm plugin library name
3956             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
3957               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3958               aDataset->OpenOnDisk();
3959               size = aDataset->GetSize();
3960               char* libname_str = new char[ size ];
3961               aDataset->ReadFromDisk( libname_str );
3962               if(MYDEBUG) SCRUTE( libname_str );
3963               libname = string( libname_str );
3964               delete [] libname_str;
3965               aDataset->CloseOnDisk();
3966             }
3967             // --> get algorithm data
3968             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
3969               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3970               aDataset->OpenOnDisk();
3971               size = aDataset->GetSize();
3972               char* hypdata_str = new char[ size ];
3973               aDataset->ReadFromDisk( hypdata_str );
3974               if(MYDEBUG) SCRUTE( hypdata_str );
3975               hypdata = string( hypdata_str );
3976               delete [] hypdata_str;
3977               aDataset->CloseOnDisk();
3978             }
3979           }
3980           // close algorithm HDF group
3981           aGroup->CloseOnDisk();
3982
3983           // --> restore algorithm from data
3984           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
3985             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
3986                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
3987             SMESH::SMESH_Hypothesis_var myHyp;
3988
3989             try { // protect persistence mechanism against exceptions
3990               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
3991             }
3992             catch (...) {
3993               INFOS( "Exception during hypothesis creation" );
3994             }
3995
3996             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3997             if ( myImpl ) {
3998               //myImpl->LoadFrom( hypdata.c_str() );
3999               hypDataList.push_back( make_pair( myImpl, hypdata ));
4000               string iorString = GetORB()->object_to_string( myHyp );
4001               int newId = myStudyContext->findId( iorString );
4002               myStudyContext->mapOldToNew( id, newId );
4003             }
4004             else
4005               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4006           }
4007         }
4008       }
4009       // close algorithms root HDF group
4010       aTopGroup->CloseOnDisk();
4011       aTopGroup = 0;
4012     }
4013
4014     // --> the rest groups should be meshes
4015     for ( int i = 0; i < aNbGroups; i++ ) {
4016       // identify next group
4017       char meshName[ HDF_NAME_MAX_LEN+1 ];
4018       aFile->InternalObjectIndentify( i, meshName );
4019
4020       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4021         // --> get mesh id
4022         int id = atoi( string( meshName ).substr( 4 ).c_str() );
4023         if ( id <= 0 )
4024           continue;
4025
4026         // open mesh HDF group
4027         aTopGroup = new HDFgroup( meshName, aFile );
4028         aTopGroup->OpenOnDisk();
4029
4030         // get number of child HDF objects
4031         int aNbObjects = aTopGroup->nInternalObjects();
4032         if ( aNbObjects > 0 ) {
4033           // create mesh
4034           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4035           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4036           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4037           if ( !myNewMeshImpl )
4038             continue;
4039           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4040
4041           string iorString = GetORB()->object_to_string( myNewMesh );
4042           int newId = myStudyContext->findId( iorString );
4043           myStudyContext->mapOldToNew( id, newId );
4044
4045           // ouv : NPAL12872
4046           // try to read and set auto color flag
4047           char aMeshAutoColorName[ 30 ];
4048           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4049           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4050           {
4051             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4052             aDataset->OpenOnDisk();
4053             size = aDataset->GetSize();
4054             int* anAutoColor = new int[ size ];
4055             aDataset->ReadFromDisk( anAutoColor );
4056             aDataset->CloseOnDisk();
4057             myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4058           }
4059
4060           // try to read and set reference to shape
4061           GEOM::GEOM_Object_var aShapeObject;
4062           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4063             // load mesh "Ref on shape" - it's an entry to SObject
4064             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4065             aDataset->OpenOnDisk();
4066             size = aDataset->GetSize();
4067             char* refFromFile = new char[ size ];
4068             aDataset->ReadFromDisk( refFromFile );
4069             aDataset->CloseOnDisk();
4070             if ( strlen( refFromFile ) > 0 ) {
4071               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4072
4073               // Make sure GEOM data are loaded first
4074               //loadGeomData( shapeSO->GetFatherComponent() );
4075
4076               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4077               if ( !CORBA::is_nil( shapeObject ) ) {
4078                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4079                 if ( !aShapeObject->_is_nil() )
4080                   myNewMeshImpl->SetShape( aShapeObject );
4081               }
4082             }
4083           }
4084
4085           // issue 0020693. Restore _isModified flag
4086           if( aTopGroup->ExistInternalObject( "_isModified" ) )
4087           {
4088             aDataset = new HDFdataset( "_isModified", aTopGroup );
4089             aDataset->OpenOnDisk();
4090             size = aDataset->GetSize();
4091             int* isModified = new int[ size ];
4092             aDataset->ReadFromDisk( isModified );
4093             aDataset->CloseOnDisk();
4094             myNewMeshImpl->GetImpl().SetIsModified( bool(*isModified));
4095           }
4096
4097           // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4098           if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4099           {
4100             aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4101             aDataset->OpenOnDisk();
4102             size = aDataset->GetSize();
4103             int* meshPersistentId = new int[ size ];
4104             aDataset->ReadFromDisk( meshPersistentId );
4105             aDataset->CloseOnDisk();
4106             myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4107           }
4108         }
4109       }
4110     }
4111
4112     // As all object that can be referred by hypothesis are created,
4113     // we can restore hypothesis data
4114
4115     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4116     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4117     {
4118       SMESH_Hypothesis_i* hyp  = hyp_data->first;
4119       string &            data = hyp_data->second;
4120       hyp->LoadFrom( data.c_str() );
4121     }
4122
4123     // Restore the rest mesh data
4124
4125     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4126     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4127     {
4128       aTopGroup                   = meshi_group->second;
4129       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4130       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
4131       SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4132
4133       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4134       bool hasData = false;
4135
4136       // get mesh old id
4137       string iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4138       int newId = myStudyContext->findId( iorString );
4139       int id = myStudyContext->getOldId( newId );
4140
4141       // try to find mesh data dataset
4142       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4143         // load mesh "has data" flag
4144         aDataset = new HDFdataset( "Has data", aTopGroup );
4145         aDataset->OpenOnDisk();
4146         size = aDataset->GetSize();
4147         char* strHasData = new char[ size ];
4148         aDataset->ReadFromDisk( strHasData );
4149         aDataset->CloseOnDisk();
4150         if ( strcmp( strHasData, "1") == 0 ) {
4151           // read mesh data from MED file
4152           myReader.SetMesh( mySMESHDSMesh );
4153           myReader.SetMeshId( id );
4154           myReader.Perform();
4155           hasData = true;
4156         }
4157       }
4158
4159       // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4160       // nodes and elements are not yet put into sub-meshes)
4161       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4162         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4163         aGroup->OpenOnDisk();
4164         // get number of applied algorithms
4165         int aNbSubObjects = aGroup->nInternalObjects();
4166         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4167         for ( int j = 0; j < aNbSubObjects; j++ ) {
4168           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4169           aGroup->InternalObjectIndentify( j, name_dataset );
4170           // check if it is an algorithm
4171           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4172             aDataset = new HDFdataset( name_dataset, aGroup );
4173             aDataset->OpenOnDisk();
4174             size = aDataset->GetSize();
4175             char* refFromFile = new char[ size ];
4176             aDataset->ReadFromDisk( refFromFile );
4177             aDataset->CloseOnDisk();
4178
4179             // san - it is impossible to recover applied algorithms using their entries within Load() method
4180
4181             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
4182             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4183             int id = atoi( refFromFile );
4184             string anIOR = myStudyContext->getIORbyOldId( id );
4185             if ( !anIOR.empty() ) {
4186               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4187               if ( !CORBA::is_nil( hypObject ) ) {
4188                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4189                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4190                                            || !myNewMeshImpl->HasShapeToMesh()) )
4191                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4192               }
4193             }
4194           }
4195         }
4196         aGroup->CloseOnDisk();
4197       }
4198
4199       // try to get applied hypotheses
4200       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4201         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4202         aGroup->OpenOnDisk();
4203         // get number of applied hypotheses
4204         int aNbSubObjects = aGroup->nInternalObjects();
4205         for ( int j = 0; j < aNbSubObjects; j++ ) {
4206           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4207           aGroup->InternalObjectIndentify( j, name_dataset );
4208           // check if it is a hypothesis
4209           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4210             aDataset = new HDFdataset( name_dataset, aGroup );
4211             aDataset->OpenOnDisk();
4212             size = aDataset->GetSize();
4213             char* refFromFile = new char[ size ];
4214             aDataset->ReadFromDisk( refFromFile );
4215             aDataset->CloseOnDisk();
4216
4217             // san - it is impossible to recover applied hypotheses using their entries within Load() method
4218
4219             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
4220             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4221             int id = atoi( refFromFile );
4222             string anIOR = myStudyContext->getIORbyOldId( id );
4223             if ( !anIOR.empty() ) {
4224               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4225               if ( !CORBA::is_nil( hypObject ) ) {
4226                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4227                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4228                                            || !myNewMeshImpl->HasShapeToMesh()) )
4229                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4230               }
4231             }
4232           }
4233         }
4234         aGroup->CloseOnDisk();
4235       }
4236
4237       // --> try to find submeshes containers for each type of submesh
4238       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4239         char name_meshgroup[ 30 ];
4240         if ( j == GetSubMeshOnVertexTag() )
4241           strcpy( name_meshgroup, "SubMeshes On Vertex" );
4242         else if ( j == GetSubMeshOnEdgeTag() )
4243           strcpy( name_meshgroup, "SubMeshes On Edge" );
4244         else if ( j == GetSubMeshOnWireTag() )
4245           strcpy( name_meshgroup, "SubMeshes On Wire" );
4246         else if ( j == GetSubMeshOnFaceTag() )
4247           strcpy( name_meshgroup, "SubMeshes On Face" );
4248         else if ( j == GetSubMeshOnShellTag() )
4249           strcpy( name_meshgroup, "SubMeshes On Shell" );
4250         else if ( j == GetSubMeshOnSolidTag() )
4251           strcpy( name_meshgroup, "SubMeshes On Solid" );
4252         else if ( j == GetSubMeshOnCompoundTag() )
4253           strcpy( name_meshgroup, "SubMeshes On Compound" );
4254
4255         // try to get submeshes container HDF group
4256         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4257           // open submeshes containers HDF group
4258           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4259           aGroup->OpenOnDisk();
4260
4261           // get number of submeshes
4262           int aNbSubMeshes = aGroup->nInternalObjects();
4263           for ( int k = 0; k < aNbSubMeshes; k++ ) {
4264             // identify submesh
4265             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4266             aGroup->InternalObjectIndentify( k, name_submeshgroup );
4267             if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
4268               // --> get submesh id
4269               int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
4270               if ( subid <= 0 )
4271                 continue;
4272               // open submesh HDF group
4273               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4274               aSubGroup->OpenOnDisk();
4275
4276               // try to read and set reference to subshape
4277               GEOM::GEOM_Object_var aSubShapeObject;
4278               SMESH::SMESH_subMesh_var aSubMesh;
4279
4280               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4281                 // load submesh "Ref on shape" - it's an entry to SObject
4282                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4283                 aDataset->OpenOnDisk();
4284                 size = aDataset->GetSize();
4285                 char* refFromFile = new char[ size ];
4286                 aDataset->ReadFromDisk( refFromFile );
4287                 aDataset->CloseOnDisk();
4288                 if ( strlen( refFromFile ) > 0 ) {
4289                   SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
4290                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4291                   if ( !CORBA::is_nil( subShapeObject ) ) {
4292                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4293                     if ( !aSubShapeObject->_is_nil() )
4294                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
4295                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4296                     if ( aSubMesh->_is_nil() )
4297                       continue;
4298                     string iorSubString = GetORB()->object_to_string( aSubMesh );
4299                     int newSubId = myStudyContext->findId( iorSubString );
4300                     myStudyContext->mapOldToNew( subid, newSubId );
4301                   }
4302                 }
4303               }
4304
4305               if ( aSubMesh->_is_nil() )
4306                 continue;
4307
4308               // try to get applied algorithms
4309               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4310                 // open "applied algorithms" HDF group
4311                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4312                 aSubSubGroup->OpenOnDisk();
4313                 // get number of applied algorithms
4314                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4315                 for ( int l = 0; l < aNbSubObjects; l++ ) {
4316                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4317                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4318                   // check if it is an algorithm
4319                   if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4320                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4321                     aDataset->OpenOnDisk();
4322                     size = aDataset->GetSize();
4323                     char* refFromFile = new char[ size ];
4324                     aDataset->ReadFromDisk( refFromFile );
4325                     aDataset->CloseOnDisk();
4326
4327                     int id = atoi( refFromFile );
4328                     string anIOR = myStudyContext->getIORbyOldId( id );
4329                     if ( !anIOR.empty() ) {
4330                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4331                       if ( !CORBA::is_nil( hypObject ) ) {
4332                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4333                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4334                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4335                       }
4336                     }
4337                   }
4338                 }
4339                 // close "applied algorithms" HDF group
4340                 aSubSubGroup->CloseOnDisk();
4341               }
4342
4343               // try to get applied hypotheses
4344               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4345                 // open "applied hypotheses" HDF group
4346                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4347                 aSubSubGroup->OpenOnDisk();
4348                 // get number of applied hypotheses
4349                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4350                 for ( int l = 0; l < aNbSubObjects; l++ ) {
4351                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4352                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4353                   // check if it is a hypothesis
4354                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4355                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4356                     aDataset->OpenOnDisk();
4357                     size = aDataset->GetSize();
4358                     char* refFromFile = new char[ size ];
4359                     aDataset->ReadFromDisk( refFromFile );
4360                     aDataset->CloseOnDisk();
4361
4362                     int id = atoi( refFromFile );
4363                     string anIOR = myStudyContext->getIORbyOldId( id );
4364                     if ( !anIOR.empty() ) {
4365                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4366                       if ( !CORBA::is_nil( hypObject ) ) {
4367                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4368                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4369                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4370                       }
4371                     }
4372                   }
4373                 }
4374                 // close "applied hypotheses" HDF group
4375                 aSubSubGroup->CloseOnDisk();
4376               }
4377
4378               // close submesh HDF group
4379               aSubGroup->CloseOnDisk();
4380             }
4381           }
4382           // close submeshes containers HDF group
4383           aGroup->CloseOnDisk();
4384         }
4385       }
4386
4387       if(hasData) {
4388
4389         // Read sub-meshes
4390         // ----------------
4391         if(MYDEBUG) MESSAGE("Create all sub-meshes");
4392         bool submeshesInFamilies = ( ! aTopGroup->ExistInternalObject( "Submeshes" ));
4393         if ( submeshesInFamilies ) // from MED
4394         {
4395           // old way working before fix of PAL 12992
4396           myReader.CreateAllSubMeshes();
4397         }
4398         else
4399         {
4400           // open a group
4401           aGroup = new HDFgroup( "Submeshes", aTopGroup );
4402           aGroup->OpenOnDisk();
4403
4404           int maxID = Max( mySMESHDSMesh->MaxSubMeshIndex(), mySMESHDSMesh->MaxShapeIndex() );
4405           vector< SMESHDS_SubMesh * > subMeshes( maxID + 1, (SMESHDS_SubMesh*) 0 );
4406           vector< TopAbs_ShapeEnum  > smType   ( maxID + 1, TopAbs_SHAPE );
4407
4408           PositionCreator aPositionCreator;
4409
4410           SMDS_NodeIteratorPtr nIt = mySMESHDSMesh->nodesIterator();
4411           SMDS_ElemIteratorPtr eIt = mySMESHDSMesh->elementsIterator();
4412           for ( int isNode = 0; isNode < 2; ++isNode )
4413           {
4414             string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4415             if ( aGroup->ExistInternalObject( (char*) aDSName.c_str() ))
4416             {
4417               aDataset = new HDFdataset( (char*) aDSName.c_str(), aGroup );
4418               aDataset->OpenOnDisk();
4419               // read submesh IDs for all elements sorted by ID
4420               int nbElems = aDataset->GetSize();
4421               int* smIDs = new int [ nbElems ];
4422               aDataset->ReadFromDisk( smIDs );
4423               aDataset->CloseOnDisk();
4424
4425               // get elements sorted by ID
4426               TIDSortedElemSet elemSet;
4427               if ( isNode )
4428                 while ( nIt->more() ) elemSet.insert( nIt->next() );
4429               else
4430                 while ( eIt->more() ) elemSet.insert( eIt->next() );
4431               //ASSERT( elemSet.size() == nbElems ); -- issue 20182
4432               // -- Most probably a bad study was saved when there were
4433               // not fixed bugs in SMDS_MeshInfo
4434               if ( elemSet.size() < nbElems ) {
4435 #ifdef _DEBUG_
4436                 cout << "SMESH_Gen_i::Load(), warning: Node position data is invalid" << endl;
4437 #endif
4438                 nbElems = elemSet.size();
4439               }
4440               // add elements to submeshes
4441               TIDSortedElemSet::iterator iE = elemSet.begin();
4442               for ( int i = 0; i < nbElems; ++i, ++iE )
4443               {
4444                 int smID = smIDs[ i ];
4445                 if ( smID == 0 ) continue;
4446                 const SMDS_MeshElement* elem = *iE;
4447                 if( smID > maxID ) {
4448                   // corresponding subshape no longer exists: maybe geom group has been edited
4449                   if ( myNewMeshImpl->HasShapeToMesh() )
4450                     mySMESHDSMesh->RemoveElement( elem );
4451                   continue;
4452                 }
4453                 // get or create submesh
4454                 SMESHDS_SubMesh* & sm = subMeshes[ smID ];
4455                 if ( ! sm ) {
4456                   sm = mySMESHDSMesh->NewSubMesh( smID );
4457                   smType[ smID ] = mySMESHDSMesh->IndexToShape( smID ).ShapeType();
4458                 }
4459                 // add
4460                 if ( isNode ) {
4461                   SMDS_PositionPtr pos = aPositionCreator.MakePosition( smType[ smID ]);
4462                   SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>( static_cast<const SMDS_MeshNode*>( elem ));
4463                   node->SetPosition( pos );
4464                   sm->AddNode( node );
4465                 } else {
4466                   sm->AddElement( elem );
4467                 }
4468               }
4469               delete [] smIDs;
4470             }
4471           }
4472         } // end reading submeshes
4473
4474         // Read node positions on sub-shapes (SMDS_Position)
4475
4476         if ( aTopGroup->ExistInternalObject( "Node Positions" ))
4477         {
4478           // There are 5 datasets to read:
4479           // "Nodes on Edges" - ID of node on edge
4480           // "Edge positions" - U parameter on node on edge
4481           // "Nodes on Faces" - ID of node on face
4482           // "Face U positions" - U parameter of node on face
4483           // "Face V positions" - V parameter of node on face
4484           const char* aEid_DSName = "Nodes on Edges";
4485           const char* aEu_DSName  = "Edge positions";
4486           const char* aFu_DSName  = "Face U positions";
4487           //char* aFid_DSName = "Nodes on Faces";
4488           //char* aFv_DSName  = "Face V positions";
4489
4490           // data to retrieve
4491           int nbEids = 0, nbFids = 0;
4492           int *aEids = 0, *aFids  = 0;
4493           double *aEpos = 0, *aFupos = 0, *aFvpos = 0;
4494
4495           // open a group
4496           aGroup = new HDFgroup( "Node Positions", aTopGroup );
4497           aGroup->OpenOnDisk();
4498
4499           // loop on 5 data sets
4500           int aNbObjects = aGroup->nInternalObjects();
4501           for ( int i = 0; i < aNbObjects; i++ )
4502           {
4503             // identify dataset
4504             char aDSName[ HDF_NAME_MAX_LEN+1 ];
4505             aGroup->InternalObjectIndentify( i, aDSName );
4506             // read data
4507             aDataset = new HDFdataset( aDSName, aGroup );
4508             aDataset->OpenOnDisk();
4509             if ( aDataset->GetType() == HDF_FLOAT64 ) // Positions
4510             {
4511               double* pos = new double [ aDataset->GetSize() ];
4512               aDataset->ReadFromDisk( pos );
4513               // which one?
4514               if ( strncmp( aDSName, aEu_DSName, strlen( aEu_DSName )) == 0 )
4515                 aEpos = pos;
4516               else if ( strncmp( aDSName, aFu_DSName, strlen( aFu_DSName )) == 0 )
4517                 aFupos = pos;
4518               else
4519                 aFvpos = pos;
4520             }
4521             else // NODE IDS
4522             {
4523               int aSize = aDataset->GetSize();
4524
4525               // for reading files, created from 18.07.2005 till 10.10.2005
4526               if (aDataset->GetType() == HDF_STRING)
4527                 aSize /= sizeof(int);
4528
4529               int* ids = new int [aSize];
4530               aDataset->ReadFromDisk( ids );
4531               // on face or nodes?
4532               if ( strncmp( aDSName, aEid_DSName, strlen( aEid_DSName )) == 0 ) {
4533                 aEids = ids;
4534                 nbEids = aSize;
4535               }
4536               else {
4537                 aFids = ids;
4538                 nbFids = aSize;
4539               }
4540             }
4541             aDataset->CloseOnDisk();
4542           } // loop on 5 datasets
4543
4544           // Set node positions on edges or faces
4545           for ( int onFace = 0; onFace < 2; onFace++ )
4546           {
4547             int nbNodes = ( onFace ? nbFids : nbEids );
4548             if ( nbNodes == 0 ) continue;
4549             int* aNodeIDs = ( onFace ? aFids : aEids );
4550             double* aUPos = ( onFace ? aFupos : aEpos );
4551             double* aVPos = ( onFace ? aFvpos : 0 );
4552             // loop on node IDs
4553             for ( int iNode = 0; iNode < nbNodes; iNode++ )
4554             {
4555               const SMDS_MeshNode* node = mySMESHDSMesh->FindNode( aNodeIDs[ iNode ]);
4556               if ( !node ) continue; // maybe removed while Loading() if geometry changed
4557               SMDS_PositionPtr aPos = node->GetPosition();
4558               ASSERT( aPos );
4559               if ( onFace ) {
4560                 // ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_FACE );-- issue 20182
4561                 // -- Most probably a bad study was saved when there were
4562                 // not fixed bugs in SMDS_MeshInfo
4563                 if ( aPos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
4564                   SMDS_FacePosition* fPos = const_cast<SMDS_FacePosition*>
4565                     ( static_cast<const SMDS_FacePosition*>( aPos ));
4566                   fPos->SetUParameter( aUPos[ iNode ]);
4567                   fPos->SetVParameter( aVPos[ iNode ]);
4568                 }
4569               }
4570               else {
4571                 // ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE );-- issue 20182
4572                 if ( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE ) {
4573                   SMDS_EdgePosition* fPos = const_cast<SMDS_EdgePosition*>
4574                     ( static_cast<const SMDS_EdgePosition*>( aPos ));
4575                   fPos->SetUParameter( aUPos[ iNode ]);
4576                 }
4577               }
4578             }
4579           }
4580           if ( aEids ) delete [] aEids;
4581           if ( aFids ) delete [] aFids;
4582           if ( aEpos ) delete [] aEpos;
4583           if ( aFupos ) delete [] aFupos;
4584           if ( aFvpos ) delete [] aFvpos;
4585
4586           aGroup->CloseOnDisk();
4587
4588         } // if ( aTopGroup->ExistInternalObject( "Node Positions" ) )
4589       } // if ( hasData )
4590
4591       // try to get groups
4592       for ( int ii = GetNodeGroupsTag(); ii <= Get0DElementsGroupsTag(); ii++ ) {
4593         char name_group[ 30 ];
4594         if ( ii == GetNodeGroupsTag() )
4595           strcpy( name_group, "Groups of Nodes" );
4596         else if ( ii == GetEdgeGroupsTag() )
4597           strcpy( name_group, "Groups of Edges" );
4598         else if ( ii == GetFaceGroupsTag() )
4599           strcpy( name_group, "Groups of Faces" );
4600         else if ( ii == GetVolumeGroupsTag() )
4601           strcpy( name_group, "Groups of Volumes" );
4602         else if ( ii == Get0DElementsGroupsTag() )
4603           strcpy( name_group, "Groups of 0D Elements" );
4604
4605         if ( aTopGroup->ExistInternalObject( name_group ) ) {
4606           aGroup = new HDFgroup( name_group, aTopGroup );
4607           aGroup->OpenOnDisk();
4608           // get number of groups
4609           int aNbSubObjects = aGroup->nInternalObjects();
4610           for ( int j = 0; j < aNbSubObjects; j++ ) {
4611             char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4612             aGroup->InternalObjectIndentify( j, name_dataset );
4613             // check if it is an group
4614             if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
4615               // --> get group id
4616               int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
4617               if ( subid <= 0 )
4618                 continue;
4619               aDataset = new HDFdataset( name_dataset, aGroup );
4620               aDataset->OpenOnDisk();
4621
4622               // Retrieve actual group name
4623               size = aDataset->GetSize();
4624               char* nameFromFile = new char[ size ];
4625               aDataset->ReadFromDisk( nameFromFile );
4626               aDataset->CloseOnDisk();
4627
4628               // Try to find a shape reference
4629               TopoDS_Shape aShape;
4630               char aRefName[ 30 ];
4631               sprintf( aRefName, "Ref on shape %d", subid);
4632               if ( aGroup->ExistInternalObject( aRefName ) ) {
4633                 // load mesh "Ref on shape" - it's an entry to SObject
4634                 aDataset = new HDFdataset( aRefName, aGroup );
4635                 aDataset->OpenOnDisk();
4636                 size = aDataset->GetSize();
4637                 char* refFromFile = new char[ size ];
4638                 aDataset->ReadFromDisk( refFromFile );
4639                 aDataset->CloseOnDisk();
4640                 if ( strlen( refFromFile ) > 0 ) {
4641                   SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4642                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4643                   if ( !CORBA::is_nil( shapeObject ) ) {
4644                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4645                     if ( !aShapeObject->_is_nil() )
4646                       aShape = GeomObjectToShape( aShapeObject );
4647                   }
4648                 }
4649               }
4650               // Try to read a filter of SMESH_GroupOnFilter
4651               SMESH::Filter_var filter;
4652               SMESH_PredicatePtr predicate;
4653               std::string hdfGrpName = "Filter " + SMESH_Comment(subid);
4654               if ( aGroup->ExistInternalObject( hdfGrpName.c_str() ))
4655               {
4656                 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4657                 aDataset->OpenOnDisk();
4658                 size = aDataset->GetSize();
4659                 char* persistStr = new char[ size ];
4660                 aDataset->ReadFromDisk( persistStr );
4661                 aDataset->CloseOnDisk();
4662                 if ( strlen( persistStr ) > 0 ) {
4663                   filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4664                   predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4665                 }
4666               }
4667
4668               // Create group servant
4669               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4670               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4671                 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4672               // Obtain a SMESHDS_Group object
4673               if ( aNewGroup->_is_nil() )
4674                 continue;
4675
4676               string iorSubString = GetORB()->object_to_string( aNewGroup );
4677               int newSubId = myStudyContext->findId( iorSubString );
4678               myStudyContext->mapOldToNew( subid, newSubId );
4679
4680               SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4681               if ( !aGroupImpl )
4682                 continue;
4683
4684               if ( SMESH_GroupOnFilter_i* aFilterGroup =
4685                    dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4686                 aFilterGroup->SetFilter( filter );
4687
4688               SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4689               if ( !aGroupBaseDS )
4690                 continue;
4691
4692               aGroupBaseDS->SetStoreName( name_dataset );
4693
4694               // ouv : NPAL12872
4695               // Read color of the group
4696               char aGroupColorName[ 30 ];
4697               sprintf( aGroupColorName, "ColorGroup %d", subid);
4698               if ( aGroup->ExistInternalObject( aGroupColorName ) )
4699               {
4700                 aDataset = new HDFdataset( aGroupColorName, aGroup );
4701                 aDataset->OpenOnDisk();
4702                 size = aDataset->GetSize();
4703                 double* anRGB = new double[ size ];
4704                 aDataset->ReadFromDisk( anRGB );
4705                 aDataset->CloseOnDisk();
4706                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4707                 aGroupBaseDS->SetColor( aColor );
4708               }
4709
4710               // Fill group with contents from MED file
4711               SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
4712               if ( aGrp )
4713                 myReader.GetGroup( aGrp );
4714             }
4715           }
4716           aGroup->CloseOnDisk();
4717         }
4718       }
4719
4720       // read submeh order if any
4721       if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4722         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4723         aDataset->OpenOnDisk();
4724         size = aDataset->GetSize();
4725         int* smIDs = new int[ size ];
4726         aDataset->ReadFromDisk( smIDs );
4727         aDataset->CloseOnDisk();
4728         TListOfListOfInt anOrderIds;
4729         anOrderIds.push_back( TListOfInt() );
4730         for ( int i = 0; i < size; i++ )
4731           if ( smIDs[ i ] < 0 ) // is separator
4732             anOrderIds.push_back( TListOfInt() );
4733           else
4734             anOrderIds.back().push_back(smIDs[ i ]);
4735
4736         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4737       }
4738     } // loop on meshes
4739
4740     // update hyps needing full mesh data restored (issue 20918)
4741     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4742     {
4743       SMESH_Hypothesis_i* hyp  = hyp_data->first;
4744       hyp->UpdateAsMeshesRestored();
4745     }
4746
4747     // notify algos on completed restoration
4748     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4749     {
4750       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4751       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
4752
4753       TopoDS_Shape myLocShape;
4754       if(myLocMesh.HasShapeToMesh())
4755         myLocShape = myLocMesh.GetShapeToMesh();
4756       else
4757         myLocShape = SMESH_Mesh::PseudoShape();
4758
4759       myLocMesh.GetSubMesh(myLocShape)->
4760         ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4761     }
4762
4763     // close mesh group
4764     if(aTopGroup)
4765       aTopGroup->CloseOnDisk();
4766   }
4767   // close HDF file
4768   aFile->CloseOnDisk();
4769   delete aFile;
4770
4771   // Remove temporary files created from the stream
4772   if ( !isMultiFile )
4773     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4774
4775   INFOS( "SMESH_Gen_i::Load completed" );
4776   return true;
4777 }
4778
4779 //=============================================================================
4780 /*!
4781  *  SMESH_Gen_i::LoadASCII
4782  *
4783  *  Load SMESH module's data in ASCII format
4784  */
4785 //=============================================================================
4786
4787 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4788                              const SALOMEDS::TMPFile& theStream,
4789                              const char*              theURL,
4790                              bool                     isMultiFile ) {
4791   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4792   return Load( theComponent, theStream, theURL, isMultiFile );
4793
4794   //before call main ::Load method it's need for decipher text format to
4795   //binary ( "|xx" => x' )
4796   int size = theStream.length();
4797   if ( int((size / 3 )*3) != size ) //error size of buffer
4798     return false;
4799
4800   int real_size = int(size / 3);
4801
4802   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4803   char tmp[3];
4804   tmp[2]='\0';
4805   int c = -1;
4806   for ( int i = 0; i < real_size; i++ )
4807   {
4808     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4809     sscanf( tmp, "%x", &c );
4810     sprintf( (char*)&(buffer[i]), "%c", (char)c );
4811   }
4812
4813   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4814
4815   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4816 }
4817
4818 //=============================================================================
4819 /*!
4820  *  SMESH_Gen_i::Close
4821  *
4822  *  Clears study-connected data when it is closed
4823  */
4824 //=============================================================================
4825
4826 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4827 {
4828   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4829
4830   // set correct current study
4831   if (theComponent->GetStudy()->StudyId() != GetCurrentStudyID())
4832     SetCurrentStudy(theComponent->GetStudy());
4833
4834   // Clear study contexts data
4835   int studyId = GetCurrentStudyID();
4836   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
4837     delete myStudyContextMap[ studyId ];
4838     myStudyContextMap.erase( studyId );
4839   }
4840
4841   // delete SMESH_Mesh's
4842 //   See bug IPAL19437.
4843 //
4844 //   StudyContextStruct* context = myGen.GetStudyContext( studyId );
4845 //   map< int, SMESH_Mesh* >::iterator i_mesh = context->mapMesh.begin();
4846 //   for ( ; i_mesh != context->mapMesh.end(); ++i_mesh ) {
4847 //     printf( "--------------------------- SMESH_Gen_i::Close, delete aGroup = %p \n", i_mesh->second );
4848 //     delete i_mesh->second;
4849 //   }
4850
4851
4852   // delete SMESHDS_Mesh's
4853   // it's too long on big meshes
4854 //   if ( context->myDocument ) {
4855 //     delete context->myDocument;
4856 //     context->myDocument = 0;
4857 //   }
4858
4859   myCurrentStudy = SALOMEDS::Study::_nil();
4860   return;
4861 }
4862
4863 //=============================================================================
4864 /*!
4865  *  SMESH_Gen_i::ComponentDataType
4866  *
4867  *  Get component data type
4868  */
4869 //=============================================================================
4870
4871 char* SMESH_Gen_i::ComponentDataType()
4872 {
4873   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4874   return CORBA::string_dup( "SMESH" );
4875 }
4876
4877
4878 //=============================================================================
4879 /*!
4880  *  SMESH_Gen_i::IORToLocalPersistentID
4881  *
4882  *  Transform data from transient form to persistent
4883  */
4884 //=============================================================================
4885
4886 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4887                                            const char*           IORString,
4888                                            CORBA::Boolean        /*isMultiFile*/,
4889                                            CORBA::Boolean        /*isASCII*/ )
4890 {
4891   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4892   StudyContext* myStudyContext = GetCurrentStudyContext();
4893
4894   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4895     int anId = myStudyContext->findId( IORString );
4896     if ( anId ) {
4897       if(MYDEBUG) MESSAGE( "VSR " << anId )
4898       char strId[ 20 ];
4899       sprintf( strId, "%d", anId );
4900       return  CORBA::string_dup( strId );
4901     }
4902   }
4903   return CORBA::string_dup( "" );
4904 }
4905
4906 //=============================================================================
4907 /*!
4908  *  SMESH_Gen_i::LocalPersistentIDToIOR
4909  *
4910  *  Transform data from persistent form to transient
4911  */
4912 //=============================================================================
4913
4914 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4915                                            const char*           aLocalPersistentID,
4916                                            CORBA::Boolean        /*isMultiFile*/,
4917                                            CORBA::Boolean        /*isASCII*/ )
4918 {
4919   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4920   StudyContext* myStudyContext = GetCurrentStudyContext();
4921
4922   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4923     int anId = atoi( aLocalPersistentID );
4924     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
4925   }
4926   return CORBA::string_dup( "" );
4927 }
4928
4929 //=======================================================================
4930 //function : RegisterObject
4931 //purpose  :
4932 //=======================================================================
4933
4934 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
4935 {
4936   StudyContext* myStudyContext = GetCurrentStudyContext();
4937   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4938     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
4939     return myStudyContext->addObject( string( iorString.in() ) );
4940   }
4941   return 0;
4942 }
4943
4944 //================================================================================
4945 /*!
4946  * \brief Return id of registered object
4947   * \param theObject - the Object
4948   * \retval int - Object id
4949  */
4950 //================================================================================
4951
4952 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
4953 {
4954   StudyContext* myStudyContext = GetCurrentStudyContext();
4955   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4956     string iorString = GetORB()->object_to_string( theObject );
4957     return myStudyContext->findId( iorString );
4958   }
4959   return 0;
4960 }
4961
4962 //=============================================================================
4963 /*!
4964  *  SMESH_Gen_i::SetName
4965  *
4966  *  Set a new object name
4967  */
4968 //=============================================================================
4969 void SMESH_Gen_i::SetName(const char* theIOR,
4970                           const char* theName)
4971 {
4972   if ( theIOR && strcmp( theIOR, "" ) ) {
4973     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
4974     SALOMEDS::SObject_var aSO = ObjectToSObject( myCurrentStudy, anObject );
4975     if ( !aSO->_is_nil() ) {
4976       SetName( aSO, theName );
4977     }
4978   }
4979 }
4980
4981 int SMESH_Gen_i::GetCurrentStudyID()
4982 {
4983   return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
4984 }
4985
4986 //=============================================================================
4987 /*!
4988  *  SMESHEngine_factory
4989  *
4990  *  C factory, accessible with dlsym, after dlopen
4991  */
4992 //=============================================================================
4993
4994 extern "C"
4995 { SMESH_I_EXPORT
4996   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
4997                                                  PortableServer::POA_ptr   poa,
4998                                                  PortableServer::ObjectId* contId,
4999                                                  const char*               instanceName,
5000                                                  const char*               interfaceName )
5001   {
5002     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
5003     if(MYDEBUG) SCRUTE(interfaceName);
5004     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
5005     return aSMESHGen->getId() ;
5006   }
5007 }