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