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