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