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