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