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