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