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