Salome HOME
5c72ecf45043ad161d8243fc4a58d42efcfc6e0c
[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 + "\", \"" +
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
2869   PyRun_String(cmd.c_str(), Py_file_input, py_dict, py_dict);
2870
2871   if (PyErr_Occurred()) {
2872     // Restrieving python error
2873     MESSAGE("Catching error");
2874     PyObject *errtype, *errvalue, *traceback;
2875     PyErr_Fetch(&errtype, &errvalue, &traceback);
2876     if(errvalue != NULL) {
2877       MESSAGE("Error has a value");
2878       PyObject *s = PyObject_Str(errvalue);
2879       Py_ssize_t size;
2880       std::string msg = PyUnicode_AsUTF8AndSize(s, &size);
2881       msg = "Issue with the execution of create_dual_mesh:\n"+msg;
2882       MESSAGE("throwing exception");
2883       // We need to deactivate the GIL before throwing the exception
2884       PyGILState_Release(gstate);
2885       THROW_SALOME_CORBA_EXCEPTION(msg.c_str(), SALOME::INTERNAL_ERROR );
2886       Py_DECREF(s);
2887     }
2888     Py_XDECREF(errvalue);
2889     Py_XDECREF(errtype);
2890     Py_XDECREF(traceback);
2891   }
2892
2893   PyGILState_Release(gstate);
2894
2895   MESSAGE("Mesh created in " + dual_mesh_file.string());
2896
2897   // Import created MED
2898   SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2899   SMESH_Mesh_i*       newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2900   if ( !newMesh_i )
2901     THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2902   SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2903   if ( !meshSO->_is_nil() )
2904   {
2905     SetName( meshSO, meshName, meshName );
2906     SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2907   }
2908   int ret = newMesh_i->ImportMEDFile(dual_mesh_file.string().c_str(), meshName);
2909   if(ret)
2910     THROW_SALOME_CORBA_EXCEPTION( "Issue when importing mesh", SALOME::INTERNAL_ERROR );
2911
2912   /*
2913   SMESH_Mesh& newMesh2 = newMesh_i->GetImpl();
2914
2915
2916   MESSAGE("Loading file: " << dual_mesh_file.string() << " with mesh " << meshName);
2917   int ret = newMesh2.MEDToMesh(dual_mesh_file.c_str(), meshName);
2918     */
2919
2920   newMesh_i->GetImpl().GetMeshDS()->Modified();
2921
2922   *pyDump << newMesh << " = " << this
2923           << ".CreateDualMesh("
2924           << mesh << ", "
2925           << "'" << mesh_name << "', "
2926           << ats << ") ";
2927
2928   pyDumpDeleter.reset(); // allow dump in GetGroups()
2929
2930   if ( srcMesh_i->GetImpl().GetGroupIds().size() > 0 ) // dump created groups
2931     MESSAGE("Dump of groups");
2932     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2933
2934   return newMesh._retn();
2935 }
2936
2937 //================================================================================
2938 /*!
2939  * \brief Create a mesh by copying a part of another mesh
2940  *  \param meshPart - a part of mesh to copy
2941  *  \param toCopyGroups - to create in the new mesh groups
2942  *                        the copied elements belongs to
2943  *  \param toKeepIDs - to preserve IDs of the copied elements or not
2944  *  \retval SMESH::SMESH_Mesh_ptr - the new mesh
2945  */
2946 //================================================================================
2947
2948 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2949                                             const char*               meshName,
2950                                             CORBA::Boolean            toCopyGroups,
2951                                             CORBA::Boolean            toKeepIDs)
2952 {
2953   Unexpect aCatch(SALOME_SalomeException);
2954
2955   TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2956   std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2957
2958   // 1. Get source mesh
2959
2960   if ( CORBA::is_nil( meshPart ))
2961     THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2962
2963   SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2964   SMESH_Mesh_i*       srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2965   if ( !srcMesh_i )
2966     THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2967
2968   SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2969
2970   // 2. Make a new mesh
2971
2972   SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2973   SMESH_Mesh_i*       newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2974   if ( !newMesh_i )
2975     THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2976   SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2977   if ( !meshSO->_is_nil() )
2978   {
2979     SetName( meshSO, meshName, "Mesh" );
2980     SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2981   }
2982   SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2983   ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2984   ::SMESH_MeshEditor::ElemFeatures elemType;
2985
2986   // 3. Get elements to copy
2987
2988   SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2989   TIDSortedElemSet srcElems;
2990   SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2991   if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2992   {
2993     srcMesh_i->Load();
2994     srcElemIt = srcMeshDS->elementsIterator();
2995     srcNodeIt = srcMeshDS->nodesIterator();
2996   }
2997   else
2998   {
2999     SMESH::smIdType_array_var ids = meshPart->GetIDs();
3000     if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
3001     {
3002       for ( CORBA::ULong i=0; i < ids->length(); i++ )
3003         if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
3004           srcElems.insert( elem );
3005     }
3006     else
3007     {
3008       for ( CORBA::ULong i = 0; i < ids->length(); i++ )
3009         if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
3010           srcElems.insert( elem );
3011     }
3012     if ( srcElems.empty() )
3013       return newMesh._retn();
3014
3015     typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
3016     srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
3017   }
3018
3019   // 4. Copy elements
3020
3021   typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
3022   TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
3023   TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
3024   int iN;
3025   const SMDS_MeshNode *nSrc, *nTgt;
3026   vector< const SMDS_MeshNode* > nodes;
3027   while ( srcElemIt->more() )
3028   {
3029     const SMDS_MeshElement * elem = srcElemIt->next();
3030     // find / add nodes
3031     nodes.resize( elem->NbNodes());
3032     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3033     if ( toKeepIDs ) {
3034       for ( iN = 0; nIt->more(); ++iN )
3035       {
3036         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3037         nTgt = newMeshDS->FindNode( nSrc->GetID());
3038         if ( !nTgt )
3039           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3040         nodes[ iN ] = nTgt;
3041       }
3042     }
3043     else {
3044       for ( iN = 0; nIt->more(); ++iN )
3045       {
3046         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3047         TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
3048         if ( !n2n->second )
3049           n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3050         nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
3051       }
3052     }
3053     // add elements
3054     if ( elem->GetType() != SMDSAbs_Node )
3055     {
3056       elemType.Init( elem, /*basicOnly=*/false );
3057       if ( toKeepIDs ) elemType.SetID( elem->GetID() );
3058
3059       const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
3060       if ( toCopyGroups && !toKeepIDs )
3061         e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
3062     }
3063   } // while ( srcElemIt->more() )
3064
3065   // 4(b). Copy free nodes
3066
3067   if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3068   {
3069     while ( srcNodeIt->more() )
3070     {
3071       nSrc = srcNodeIt->next();
3072       if ( nSrc->NbInverseElements() == 0 )
3073       {
3074         if ( toKeepIDs )
3075           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3076         else
3077           n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3078       }
3079     }
3080   }
3081
3082   // 5. Copy groups
3083
3084   int nbNewGroups = 0;
3085   if ( toCopyGroups )
3086   {
3087     SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3088     while ( gIt->more() )
3089     {
3090       SMESH_Group* group = gIt->next();
3091       const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3092
3093       // Check group type. We copy nodal groups containing nodes of copied element
3094       SMDSAbs_ElementType groupType = groupDS->GetType();
3095       if ( groupType != SMDSAbs_Node &&
3096            newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3097         continue; // group type differs from types of meshPart
3098
3099       // Find copied elements in the group
3100       vector< const SMDS_MeshElement* > groupElems;
3101       SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3102       if ( toKeepIDs )
3103       {
3104         const SMDS_MeshElement* foundElem;
3105         if ( groupType == SMDSAbs_Node )
3106         {
3107           while ( eIt->more() )
3108             if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3109               groupElems.push_back( foundElem );
3110         }
3111         else
3112         {
3113           while ( eIt->more() )
3114             if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3115               groupElems.push_back( foundElem );
3116         }
3117       }
3118       else
3119       {
3120         TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3121         if ( e2eMap.empty() ) continue;
3122         smIdType minID = e2eMap.begin()->first->GetID();
3123         smIdType maxID = e2eMap.rbegin()->first->GetID();
3124         TE2EMap::iterator e2e;
3125         while ( eIt->more() && groupElems.size() < e2eMap.size())
3126         {
3127           const SMDS_MeshElement* e = eIt->next();
3128           if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3129           if ((e2e = e2eMap.find( e )) != e2eMap.end())
3130             groupElems.push_back( e2e->second );
3131         }
3132       }
3133       // Make a new group
3134       if ( !groupElems.empty() )
3135       {
3136         SMESH::SMESH_Group_var newGroupObj =
3137           newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3138         if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3139         {
3140           SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3141           SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3142           for ( unsigned i = 0; i < groupElems.size(); ++i )
3143             smdsGroup.Add( groupElems[i] );
3144
3145           nbNewGroups++;
3146         }
3147       }
3148     }
3149   }
3150
3151   newMeshDS->Modified();
3152
3153   *pyDump << newMesh << " = " << this
3154           << ".CopyMesh( " << meshPart << ", "
3155           << "'" << meshName << "', "
3156           << toCopyGroups << ", "
3157           << toKeepIDs << ")";
3158
3159   pyDumpDeleter.reset(); // allow dump in GetGroups()
3160
3161   if ( nbNewGroups > 0 ) // dump created groups
3162     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3163
3164   return newMesh._retn();
3165 }
3166
3167
3168 namespace // utils for CopyMeshWithGeom()
3169 {
3170   typedef std::map< std::string, std::string >             TStr2StrMap;
3171   typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3172   typedef std::map< std::set<int>, int >                   TIdSet2IndexMap;
3173   typedef std::map< std::string, int >                     TName2IndexMap;
3174
3175   //================================================================================
3176   /*!
3177    * \brief Return a new sub-shape corresponding to an old one
3178    */
3179   //================================================================================
3180
3181   struct ShapeMapper
3182   {
3183     SMESH_Mesh_i* mySrcMesh_i;
3184     SMESH_Mesh_i* myNewMesh_i;
3185     SMESH_Gen_i*  myGen_i;
3186     bool          myToPublish;
3187     bool          myIsSameGeom;
3188
3189     TStr2StrMap   myOld2NewEntryMap; // map of study entries
3190
3191     GEOM::ListOfGO_var         mySubshapes; // sub-shapes existing in the new geometry
3192     TIdSet2IndexMap            myIds2SubshapeIndex; // to find an existing sub-shape
3193     TName2IndexMap             myName2SubshapeIndex; // to find an existing sub-shape by name
3194
3195     bool                       myGIPMapDone;
3196     GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3197
3198     // not directly relating to shape search
3199     TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3200
3201     //================================================================================
3202     /*!
3203      * \brief Constructor
3204      */
3205     ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3206                  SMESH_Mesh_i* newMesh_i,
3207                  SMESH_Gen_i*  smeshGen_i )
3208       : mySrcMesh_i( srcMesh_i ),
3209         myNewMesh_i( newMesh_i ),
3210         myGen_i    ( smeshGen_i ),
3211         myToPublish( smeshGen_i->IsEnablePublish() ),
3212         myGIPMapDone( false )
3213     {
3214       // retrieve from the study shape mapping made thanks to
3215       // "Set presentation parameters and sub-shapes from arguments" option
3216
3217       GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3218       GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3219       SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3220       SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3221       if ( newSO->_is_nil() )
3222       {
3223         myToPublish = false;
3224         return;
3225       }
3226       if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3227         return;
3228       CORBA::String_var oldEntry = oldSO->GetID();
3229       CORBA::String_var newEntry = newSO->GetID();
3230       myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3231                                                 std::string( newEntry.in() )));
3232       std::string  newMainEntry = newEntry.in();
3233
3234       SALOMEDS::Study_var            study = myGen_i->getStudyServant();
3235       GEOM::GEOM_Gen_var           geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3236       GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3237       mySubshapes                          = op->GetExistingSubObjects( mainShapeNew,
3238                                                                         /*groupsOnly=*/false );
3239       for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3240       {
3241         newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3242         SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3243         bool refFound = false;
3244         for ( ; anIter->More(); anIter->Next() )
3245         {
3246           SALOMEDS::SObject_wrap so = anIter->Value();
3247           if ( so->ReferencedObject( oldSO.inout() ))
3248           {
3249             oldEntry = oldSO->GetID();
3250             newEntry = newSO->GetID();
3251             if (( refFound = ( newMainEntry != oldEntry.in() )))
3252               myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3253                                                         std::string( newEntry.in() )));
3254           }
3255         }
3256         if ( !refFound )
3257         {
3258           GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3259           if ( father->_is_equivalent( mainShapeNew ))
3260           {
3261             GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3262             std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3263             myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3264             CORBA::String_var name = newSO->GetName();
3265             if ( name.in()[0] )
3266               myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3267           }
3268         }
3269       }
3270     }
3271
3272     //================================================================================
3273     /*!
3274      * \brief Find a new sub-shape corresponding to an old one
3275      */
3276     GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3277     {
3278       if ( myIsSameGeom )
3279         return GEOM::GEOM_Object::_duplicate( oldShape );
3280
3281       GEOM::GEOM_Object_var newShape;
3282
3283       if ( CORBA::is_nil( oldShape ))
3284         return newShape._retn();
3285
3286       if ( !isChildOfOld( oldShape ))
3287         return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3288
3289       GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3290       GEOM::GEOM_Gen_var         geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3291
3292       // try to find by entry or name
3293       if ( myToPublish )
3294       {
3295         CORBA::String_var  oldEntry = oldShape->GetStudyEntry();
3296         TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3297         if ( o2nID != myOld2NewEntryMap.end() )
3298         {
3299           newShape = getShapeByEntry( o2nID->second );
3300         }
3301         if ( newShape->_is_nil() )
3302         {
3303           CORBA::String_var name = oldShape->GetName();
3304           TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3305           if ( n2ind != myName2SubshapeIndex.end() )
3306           {
3307             newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3308             GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3309             GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3310             if ( oldIndices->length() == 0 ||
3311                  newIndices->length() == 0 ||
3312                  getShapeType( myNewMesh_i, newIndices[0] ) !=
3313                  getShapeType( mySrcMesh_i, oldIndices[0] ))
3314               newShape = GEOM::GEOM_Object::_nil();
3315           }
3316         }
3317       }
3318
3319       if ( newShape->_is_nil() )
3320       {
3321         // try to construct a new sub-shape using myGIPMap
3322         buildGIPMap();
3323         std::vector< int >   newIndices;
3324         GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3325         for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3326         {
3327           findNewIDs( oldIndices[i], newIndices );
3328         }
3329         if ( newIndices.size() < oldIndices->length() ) // issue #17096
3330         {
3331           newIndices.clear();
3332           newShape = getInPlace( oldShape );
3333         }
3334         if ( !newIndices.empty() && newShape->_is_nil() )
3335         {
3336           // search for a sub-shape with same ids
3337           std::set< int > idSet( newIndices.begin(), newIndices.end() );
3338           TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3339           if ( ids2ind != myIds2SubshapeIndex.end() ) {
3340             newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3341           }
3342           if ( newShape->_is_nil() )
3343             try
3344             {
3345               // create a new shape
3346               if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3347               {
3348                 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3349
3350                 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3351                 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3352
3353                 GEOM::ListOfLong_var  newIndicesList = new GEOM::ListOfLong();
3354                 newIndicesList->length( newIndices.size() );
3355                 for ( size_t i = 0; i < newIndices.size(); ++i )
3356                   newIndicesList[ i ] = newIndices[ i ];
3357                 grOp->UnionIDs( newShape, newIndicesList );
3358               }
3359               else
3360               {
3361                 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3362                 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3363               }
3364             }
3365             catch (...)
3366             {
3367             }
3368         }
3369       }
3370
3371       if ( !newShape->_is_nil() && myToPublish )
3372       {
3373         CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3374         if ( !newEntry.in() || !newEntry.in()[0] )
3375         {
3376           CORBA::String_var    name = oldShape->GetName();
3377           SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3378           newEntry = newShape->GetStudyEntry();
3379           oldEntry = oldShape->GetStudyEntry();
3380           myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3381                                                     std::string( newEntry.in() )));
3382         }
3383       }
3384
3385       return newShape._retn();
3386     }
3387
3388     //================================================================================
3389     /*!
3390      * \brief Return a study entry of a new shape by study entry of the old one
3391      */
3392     std::string FindNew( const std::string & oldEntry )
3393     {
3394       if ( myIsSameGeom )
3395         return oldEntry;
3396
3397       TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3398       if ( o2nID != myOld2NewEntryMap.end() )
3399         return o2nID->second;
3400
3401       GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3402       if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3403         return oldEntry;
3404
3405       GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3406       if ( newShape->_is_nil() )
3407         return std::string();
3408
3409       CORBA::String_var newEntry = newShape->GetStudyEntry();
3410       return newEntry.in();
3411     }
3412
3413     //================================================================================
3414     /*!
3415      * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3416      *        Return zero if not found or there are more than one new ID
3417      */
3418     int FindNew( int oldID )
3419     {
3420       if ( myIsSameGeom )
3421         return oldID;
3422
3423       buildGIPMap();
3424
3425       int newID = 0;
3426
3427       if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3428       {
3429         if ( myGIPMap[ oldID ].length() == 1 )
3430         {
3431           newID = myGIPMap[ oldID ][ 0 ];
3432         }
3433         else if ( myGIPMap[ oldID ].length() > 1 &&
3434                   getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3435         {
3436           // select a meshed VERTEX
3437           SMESH_subMesh* newSM;
3438           for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3439             if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3440                 ( !newSM->IsEmpty() ))
3441               newID = myGIPMap[ oldID ][ i ];
3442         }
3443       }
3444       return newID;
3445     }
3446
3447     //================================================================================
3448     /*!
3449      * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3450      *        Return zero if the old shape is not kept as is in the new shape.
3451      */
3452     int FindNewNotChanged( SMESH_subMesh* oldSM )
3453     {
3454       if ( myIsSameGeom )
3455         return oldSM->GetId();
3456
3457       int newID = FindNew( oldSM->GetId() );
3458       if ( !newID )
3459         return 0;
3460
3461       SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3462       if ( !newSM )
3463         return 0;
3464
3465       // consider a sub-shape as not changed if all its sub-shapes are mapped into
3466       // one new sub-shape of the same type.
3467
3468       if ( oldSM->DependsOn().size() !=
3469            newSM->DependsOn().size() )
3470         return 0;
3471
3472       SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3473       while ( srcSMIt->more() )
3474       {
3475         oldSM = srcSMIt->next();
3476         int newSubID = FindNew( oldSM->GetId() );
3477         if ( getShapeType( myNewMesh_i, newSubID ) !=
3478              getShapeType( mySrcMesh_i, oldSM->GetId() ))
3479           return 0;
3480       }
3481       return newID;
3482     }
3483
3484     //================================================================================
3485     /*!
3486      * \brief Return shape by study entry
3487      */
3488     GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3489     {
3490       GEOM::GEOM_Object_var shape;
3491       SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3492       if ( !so->_is_nil() )
3493       {
3494         CORBA::Object_var obj = so->GetObject();
3495         shape = GEOM::GEOM_Object::_narrow( obj );
3496       }
3497       return shape._retn();
3498     }
3499
3500     //================================================================================
3501     /*!
3502      * \brief Fill myGIPMap by calling GetInPlaceMap()
3503      */
3504     void buildGIPMap()
3505     {
3506       if ( !myGIPMapDone )
3507       {
3508         myGIPMapDone = true;
3509
3510         GEOM::GEOM_Object_var   mainShapeNew = myNewMesh_i->GetShapeToMesh();
3511         GEOM::GEOM_Object_var   mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3512         GEOM::GEOM_Gen_var           geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3513         GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3514         try
3515         {
3516           myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3517         }
3518         catch( ... )
3519         {
3520           myGIPMap = new GEOM::ListOfListOfLong();
3521         }
3522       }
3523     }
3524
3525     //================================================================================
3526     /*!
3527      * \brief Get new sub-shape by calling GetInPlace()
3528      */
3529     GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3530     {
3531       GEOM::GEOM_Object_var newShape;
3532
3533       GEOM::GEOM_Object_var   mainShapeNew = myNewMesh_i->GetShapeToMesh();
3534       GEOM::GEOM_Gen_var           geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3535       GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3536       try
3537       {
3538         newShape = op->GetInPlace( mainShapeNew, oldShape );
3539       }
3540       catch( ... )
3541       {
3542       }
3543       return newShape._retn();
3544     }
3545
3546     //================================================================================
3547     /*!
3548      * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3549      *        number of found IDs
3550      */
3551     int findNewIDs( int oldID, std::vector< int >& newIDs  )
3552     {
3553       size_t prevNbIDs = newIDs.size();
3554
3555       if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3556       {
3557         for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3558           newIDs.push_back( myGIPMap[ oldID ][ i ]);
3559       }
3560       return newIDs.size() - prevNbIDs;
3561     }
3562
3563     //================================================================================
3564     /*!
3565      * \brief Check if an object relates to the old shape
3566      */
3567     bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3568     {
3569       if ( CORBA::is_nil( oldShape ))
3570         return false;
3571       GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3572       GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3573       return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3574                mainShapeOld1->_is_equivalent( oldShape ));
3575     }
3576
3577     //================================================================================
3578     /*!
3579      * \brief Return shape type by shape ID
3580      */
3581     TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3582     {
3583       SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3584       const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3585       return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3586     }
3587
3588     //================================================================================
3589     /*!
3590      * \brief Store a source sub-shape for which a counterpart not found and
3591      *        a smesh object invalid due to that
3592      */
3593     void AddInvalid( GEOM::GEOM_Object_var  srcShape,
3594                      SALOMEDS::SObject_wrap smeshSO )
3595     {
3596       CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3597       if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3598       {
3599         CORBA::String_var smeshEntry = smeshSO->GetID();
3600         myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3601       }
3602     }
3603
3604     //================================================================================
3605     /*!
3606      * \brief Store a source sub-shape for which a counterpart not found and
3607      *        a smesh object invalid due to that
3608      */
3609     void AddInvalid( std::string            geomEntry,
3610                      SALOMEDS::SObject_wrap smeshSO )
3611     {
3612       if ( !geomEntry.empty() )
3613       {
3614         CORBA::String_var smeshEntry = smeshSO->GetID();
3615         myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3616       }
3617     }
3618
3619     //================================================================================
3620     /*!
3621      * \brief Store a source sub-shape for which a counterpart not found and
3622      *        a smesh object invalid due to that
3623      */
3624     void AddInvalid( int                    oldGeomID,
3625                      SALOMEDS::SObject_wrap smeshSO )
3626     {
3627       int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3628       if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3629         return;
3630
3631       const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3632                                  "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3633
3634       SMESH_Comment geomName( typeName[ shapeType ]);
3635       geomName << " #" << oldGeomID;
3636
3637       CORBA::String_var smeshEntry = smeshSO->GetID();
3638       myInvalidMap[ geomName ].insert( smeshEntry.in() );
3639     }
3640
3641     //================================================================================
3642     /*!
3643      * \brief Return entries of a source sub-shape for which a counterpart not found and
3644      *        of smesh objects invalid due to that
3645      */
3646     void GetInvalid( SMESH::string_array_out &               theInvalidEntries,
3647                      std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3648     {
3649       int nbSO = 0;
3650       TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3651       for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3652       {
3653         nbSO += 1 + entry2entrySet->second.size();
3654       }
3655       int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3656       theInvalidEntries->length  ( nbSO );
3657       theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3658
3659       entry2entrySet = myInvalidMap.begin();
3660       for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3661       {
3662         theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3663
3664         std::set< std::string > & entrySet = entry2entrySet->second;
3665         std::set< std::string >::iterator entry = entrySet.begin();
3666         for ( ; entry != entrySet.end(); ++entry )
3667         {
3668           theInvalidEntries[ iEntry++ ] = entry->c_str();
3669
3670           SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3671           if ( !so->_is_nil() )
3672             theInvalidMeshSObjects[ iSO++ ] = so;
3673         }
3674       }
3675     }
3676
3677   }; // struct ShapeMapper
3678
3679   //================================================================================
3680   /*!
3681    * \brief Append an item to a CORBA sequence
3682    */
3683   template < class CORBA_seq, class ITEM >
3684   void append( CORBA_seq& seq, ITEM item )
3685   {
3686     if ( !CORBA::is_nil( item ))
3687     {
3688       seq->length( 1 + seq->length() );
3689       seq[ seq->length() - 1 ] = item;
3690     }
3691   }
3692 } // namespace // utils for CopyMeshWithGeom()
3693
3694 //================================================================================
3695 /*!
3696  * \brief Create a mesh by copying definitions of another mesh to a given geometry
3697  *  \param [in] sourceMesh - a mesh to copy
3698  *  \param [in] newGeometry - a new geometry
3699  *  \param [in] toCopyGroups - to create groups in the new mesh
3700  *  \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3701  *         otherwise new hypotheses with the same parameters will be created for the new mesh.
3702  *  \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3703  *  \param [out] newMesh - return a new mesh
3704  *  \param [out] newGroups - return new groups
3705  *  \param [out] newSubmeshes - return new sub-meshes
3706  *  \param [out] newHypotheses - return new algorithms and hypotheses
3707  *  \param [out] invalidEntries - return study entries of objects whose
3708  *         counterparts are not found in the newGeometry, followed by entries
3709  *         of mesh sub-objects that are invalid because they depend on a not found
3710  *         preceding sub-shape
3711  *  \return CORBA::Boolean - is a success
3712  */
3713 //================================================================================
3714
3715 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr       theSourceMesh,
3716                                               GEOM::GEOM_Object_ptr       theNewGeometry,
3717                                               const char*                 theMeshName,
3718                                               CORBA::Boolean              theToCopyGroups,
3719                                               CORBA::Boolean              theToReuseHypotheses,
3720                                               CORBA::Boolean              theToCopyElements,
3721                                               SMESH::SMESH_Mesh_out       theNewMesh,
3722                                               SMESH::ListOfGroups_out     theNewGroups,
3723                                               SMESH::submesh_array_out    theNewSubmeshes,
3724                                               SMESH::ListOfHypothesis_out theNewHypotheses,
3725                                               SMESH::string_array_out     theInvalidEntries)
3726 {
3727   if ( CORBA::is_nil( theSourceMesh ) ||
3728        CORBA::is_nil( theNewGeometry ))
3729     THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3730
3731   if ( !theSourceMesh->HasShapeToMesh() )
3732     THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3733
3734   bool ok = true;
3735   SMESH_TRY;
3736
3737   TPythonDump pyDump(this); // prevent dump from CreateMesh()
3738
3739   theNewMesh        = CreateMesh( theNewGeometry );
3740   theNewGroups      = new SMESH::ListOfGroups();
3741   theNewSubmeshes   = new SMESH::submesh_array();
3742   theNewHypotheses  = new SMESH::ListOfHypothesis();
3743   theInvalidEntries = new SMESH::string_array();
3744
3745   std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3746
3747   GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3748   GEOM::GEOM_Object_var geom, newGeom;
3749   SALOMEDS::SObject_wrap so;
3750
3751   SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3752   SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3753   srcMesh_i->Load();
3754
3755   ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3756
3757   // treat hypotheses of mesh and sub-meshes
3758   SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3759   for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3760   {
3761     bool isSubMesh = ( iSM < smList->length() );
3762     if ( isSubMesh )
3763     {
3764       // create a new sub-mesh
3765       SMESH::SMESH_subMesh_var newSM;
3766       geom = smList[iSM]->GetSubShape();
3767       so   = ObjectToSObject( smList[iSM] );
3768       CORBA::String_var name;
3769       if ( !so->_is_nil() )
3770         name = so->GetName();
3771       newGeom = shapeMapper.FindNew( geom );
3772       if ( newGeom->_is_nil() )
3773       {
3774         newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3775         shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3776         ok = false;
3777       }
3778       else
3779       {
3780         newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3781       }
3782       append( theNewSubmeshes, newSM );
3783
3784       if ( newGeom->_is_nil() )
3785         continue; // don't assign hypotheses
3786     }
3787     else
3788     {
3789       newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3790       geom    = srcGeom;
3791       so      = ObjectToSObject( theNewMesh );
3792       SetName( so, theMeshName, "Mesh" );
3793     }
3794
3795     // assign hypotheses
3796     SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3797     for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3798     {
3799       SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3800       SMESH_Hypothesis_i*       hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3801
3802       // get geometry hyp depends on
3803       std::vector< std::string > entryArray;
3804       std::vector< int >         subIDArray;
3805       bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3806
3807       if ( !theToReuseHypotheses || dependsOnGeom )
3808       {
3809         // create a new hypothesis
3810         CORBA::String_var type = hyp->GetName();
3811         CORBA::String_var lib  = hyp->GetLibName();
3812         CORBA::String_var data = hyp_i->SaveTo();
3813         if ( data.in()[0] )
3814         {
3815           hyp   = CreateHypothesis( type, lib );
3816           hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3817           hyp_i->LoadFrom( data.in() );
3818           append( theNewHypotheses, hyp );
3819         }
3820       }
3821
3822       // update geometry hyp depends on
3823       if ( dependsOnGeom )
3824       {
3825         for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3826         {
3827           if ( !entryArray[ iGeo ].empty() )
3828           {
3829             std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3830             if ( newEntry.empty() )
3831             {
3832               ok = false;
3833               shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3834               shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3835             }
3836             entryArray[ iGeo ] = newEntry;
3837           }
3838         }
3839         for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3840         {
3841           if ( subIDArray[ iGeo ] > 0 )
3842           {
3843             int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3844             if ( newID < 1 )
3845             {
3846               ok = false;
3847               shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3848               shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3849             }
3850             subIDArray[ iGeo ] = newID;
3851           }
3852         }
3853         if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3854           ok = false;
3855       }
3856
3857       CORBA::String_var errorText;
3858       theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3859       if ( errorText.in()[0] )
3860         ok = false;
3861
3862     } // loop on hypotheses
3863   } // loop on sub-meshes and mesh
3864
3865
3866   // copy mesh elements, keeping IDs
3867   SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3868   if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3869   {
3870     ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3871     ::SMESH_MeshEditor::ElemFeatures elemData;
3872
3873     SMESH_subMesh*         srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3874     SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3875                                                                         /*vertexLast=*/false);
3876     while ( srcSMIt->more() )
3877     {
3878       SMESH_subMesh* srcSM = srcSMIt->next();
3879       if ( srcSM->IsEmpty() )
3880         continue; // not yet computed
3881       int newID = shapeMapper.FindNewNotChanged( srcSM );
3882       if ( newID < 1 )
3883         continue;
3884
3885       SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3886       SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3887       while ( nIt->more() )
3888       {
3889         SMESH_NodeXYZ node( nIt->next() );
3890         const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3891                                                                  node->GetID() );
3892         const SMDS_PositionPtr pos = node->GetPosition();
3893         const double*           uv = pos->GetParameters();
3894         switch ( pos->GetTypeOfPosition() )
3895         {
3896         case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID );               break;
3897         case SMDS_TOP_FACE:    newMeshDS->SetNodeOnFace  ( newNode, newID, uv[0], uv[1] ); break;
3898         case SMDS_TOP_EDGE:    newMeshDS->SetNodeOnEdge  ( newNode, newID, uv[0] );        break;
3899         case SMDS_TOP_VERTEX:  newMeshDS->SetNodeOnVertex( newNode, newID );               break;
3900         default: ;
3901         }
3902       }
3903       SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3904       while( eIt->more() )
3905       {
3906         const SMDS_MeshElement* e = eIt->next();
3907         elemData.Init( e, /*basicOnly=*/false );
3908         elemData.SetID( e->GetID() );
3909         elemData.myNodes.resize( e->NbNodes() );
3910         SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3911         size_t iN;
3912         for ( iN = 0; nnIt->more(); ++iN )
3913         {
3914           const SMDS_MeshNode* srcNode = nnIt->next();
3915           elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3916           if ( !elemData.myNodes[ iN ])
3917             break;
3918         }
3919         if ( iN == elemData.myNodes.size() )
3920           if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3921             newMeshDS->SetMeshElementOnShape( newElem, newID );
3922       }
3923       if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3924         newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3925     }
3926
3927     newMeshDS->Modified();
3928   }
3929
3930
3931   // treat groups
3932
3933   TStr2StrMap old2newGroupMap;
3934
3935   SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3936
3937   SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3938   CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3939   for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3940   {
3941     SMESH::SMESH_Group_var         stdlGroup = SMESH::SMESH_Group::_narrow        ( groups[ i ]);
3942     SMESH::SMESH_GroupOnGeom_var   geomGroup = SMESH::SMESH_GroupOnGeom::_narrow  ( groups[ i ]);
3943     SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3944
3945     CORBA::String_var      name = groups[ i ]->GetName();
3946     SMESH::ElementType elemType = groups[ i ]->GetType();
3947
3948     SMESH::SMESH_GroupBase_var newGroup;
3949
3950     if ( !stdlGroup->_is_nil() )
3951     {
3952       if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3953       {
3954         SMESH::smIdType_array_var elemIDs = stdlGroup->GetIDs();
3955         const bool isElem = ( elemType != SMESH::NODE );
3956         CORBA::ULong iE = 0;
3957         for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3958           if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3959             break;
3960         if ( iE < elemIDs->length() )
3961         {
3962           stdlGroup = theNewMesh->CreateGroup( elemType, name );
3963           stdlGroup->Add( elemIDs );
3964           newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3965         }
3966       }
3967     }
3968     else if ( !geomGroup->_is_nil() )
3969     {
3970       GEOM::GEOM_Object_var    geom = geomGroup->GetShape();
3971       GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3972       if ( newGeom->_is_nil() )
3973       {
3974         newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3975         shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3976         ok = false;
3977       }
3978       else
3979       {
3980         newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3981       }
3982     }
3983     else if ( !fltrGroup->_is_nil() )
3984     {
3985       // replace geometry in a filter
3986       SMESH::Filter_var filter = fltrGroup->GetFilter();
3987       SMESH::Filter::Criteria_var criteria;
3988       filter->GetCriteria( criteria.out() );
3989
3990       bool isMissingGroup = false;
3991       std::vector< std::string > badEntries;
3992
3993       for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3994       {
3995         const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3996         switch ( criteria[ iCr ].Type )
3997         {
3998         case SMESH::FT_BelongToMeshGroup:
3999         {
4000           SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
4001           btgg->SetGroupID( thresholdID );
4002           SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
4003           SALOMEDS::SObject_wrap   refGroupSO = ObjectToSObject( refGroup );
4004           if ( refGroupSO->_is_nil() )
4005             break;
4006           CORBA::String_var     refID = refGroupSO->GetID();
4007           TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
4008           if ( o2nID == old2newGroupMap.end() )
4009           {
4010             isMissingGroup = true; // corresponding new group not yet created
4011             break;
4012           }
4013           criteria[ iCr ].ThresholdID = o2nID->second.c_str();
4014
4015           if ( o2nID->second.empty() ) // new referred group is invalid
4016             badEntries.push_back( refID.in() );
4017           break;
4018         }
4019         case SMESH::FT_BelongToGeom:
4020         case SMESH::FT_BelongToPlane:
4021         case SMESH::FT_BelongToCylinder:
4022         case SMESH::FT_BelongToGenSurface:
4023         case SMESH::FT_LyingOnGeom:
4024         {
4025           std::string newID = shapeMapper.FindNew( thresholdID );
4026           criteria[ iCr ].ThresholdID = newID.c_str();
4027           if ( newID.empty() )
4028             badEntries.push_back( thresholdID );
4029           break;
4030         }
4031         case SMESH::FT_ConnectedElements:
4032         {
4033           if ( thresholdID && thresholdID[0] )
4034           {
4035             std::string newID = shapeMapper.FindNew( thresholdID );
4036             criteria[ iCr ].ThresholdID = newID.c_str();
4037             if ( newID.empty() )
4038               badEntries.push_back( thresholdID );
4039           }
4040           break;
4041         }
4042         default:;
4043         }
4044       } // loop on criteria
4045
4046       if ( isMissingGroup && i < nbGroups )
4047       {
4048         // to treat the group again
4049         append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
4050         ++nbAddedGroups;
4051         continue;
4052       }
4053       SMESH::Filter_var newFilter = filterMgr->CreateFilter();
4054       newFilter->SetCriteria( criteria );
4055
4056       newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
4057       newFilter->UnRegister();
4058
4059       SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4060       for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
4061         shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
4062
4063       if ( isMissingGroup ) // all groups treated but a referred groups still not found
4064       {
4065         invalidSObjects.push_back( ObjectToSObject( newGroup ));
4066         ok = false;
4067       }
4068       if ( !badEntries.empty() )
4069         ok = false;
4070
4071     } // treat a group on filter
4072
4073     append( theNewGroups, newGroup );
4074
4075     // fill old2newGroupMap
4076     SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4077     SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4078     if ( !srcSO->_is_nil() )
4079     {
4080       CORBA::String_var srcID, newID("");
4081       srcID = srcSO->GetID();
4082       if ( !newSO->_is_nil() )
4083         newID = newSO->GetID();
4084       old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4085                                               std::string( newID.in() )));
4086     }
4087
4088     if ( newGroup->_is_nil() )
4089       ok = false;
4090
4091   } // loop on groups
4092
4093   newMeshDS->CompactMesh();
4094
4095   // set mesh name
4096   if ( !theMeshName || !theMeshName[0] )
4097   {
4098     SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4099     SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4100     CORBA::String_var oldName = soOld->GetName();
4101     SetName( soNew, oldName.in(), "Mesh" );
4102   }
4103   // mark invalid objects
4104   shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4105
4106   for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4107     highLightInvalid( invalidSObjects[i].in(), true );
4108
4109   pyDump << "ok, "
4110          << theNewMesh << ", "
4111          << theNewGroups << ", "
4112          << *theNewSubmeshes.ptr() << ", "
4113          << *theNewHypotheses.ptr() << ", "
4114          << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4115          << theSourceMesh << ", "
4116          << theNewGeometry << ", "
4117          << "'" << theMeshName << "', "
4118          << theToCopyGroups << ", "
4119          << theToReuseHypotheses << ", "
4120          << theToCopyElements << " )";
4121
4122   SMESH_CATCH( SMESH::throwCorbaException );
4123
4124   return ok;
4125 }
4126
4127 //================================================================================
4128 /*!
4129  * \brief Get version of MED format being used.
4130  */
4131 //================================================================================
4132
4133 char* SMESH_Gen_i::GetMEDFileVersion()
4134 {
4135   MED::TInt majeur, mineur, release;
4136   majeur =  mineur = release = 0;
4137   MED::GetVersionRelease(majeur, mineur, release);
4138   std::ostringstream version;
4139   version << majeur << "." << mineur << "." << release;
4140   return CORBA::string_dup( version.str().c_str() );
4141 }
4142
4143 //================================================================================
4144 /*!
4145  *  SMESH_Gen_i::GetMEDVersion
4146  *
4147  *  Get MED version of the file by its name
4148  */
4149 //================================================================================
4150
4151 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4152 {
4153   std::string version = MED::GetMEDVersion( theFileName );
4154   return CORBA::string_dup( version.c_str() );
4155 }
4156
4157 //================================================================================
4158 /*!
4159  *  SMESH_Gen_i::CheckCompatibility
4160  *
4161  *  Check compatibility of file with MED format being used, read only.
4162  */
4163 //================================================================================
4164
4165 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4166 {
4167   return MED::CheckCompatibility( theFileName );
4168 }
4169
4170 //================================================================================
4171 /*!
4172  *  SMESH_Gen_i::CheckWriteCompatibility
4173  *
4174  *  Check compatibility of file with MED format being used, for append on write.
4175  */
4176 //================================================================================
4177
4178 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4179 {
4180   return MED::CheckCompatibility( theFileName, true );
4181 }
4182
4183 //================================================================================
4184 /*!
4185  *  SMESH_Gen_i::GetMeshNames
4186  *
4187  *  Get names of meshes defined in file with the specified name
4188  */
4189 //================================================================================
4190 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4191
4192 {
4193   SMESH::string_array_var aResult = new SMESH::string_array();
4194   MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4195   MED::TErr anErr;
4196   MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4197   if( anErr >= 0 ) {
4198     aResult->length( aNbMeshes );
4199     for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4200       MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4201       aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4202     }
4203   }
4204   return aResult._retn();
4205 }
4206
4207 //=============================================================================
4208 /*!
4209  *  SMESH_Gen_i::Save
4210  *
4211  *  Save SMESH module's data
4212  */
4213 //=============================================================================
4214
4215 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4216                                       const char*              theURL,
4217                                       bool                     isMultiFile )
4218 {
4219   // localizing
4220   Kernel_Utils::Localizer loc;
4221
4222   if (!myStudyContext)
4223     UpdateStudy();
4224
4225   // Store study contents as a set of python commands
4226   SavePython();
4227
4228   SALOMEDS::Study_var aStudy = getStudyServant();
4229
4230   // Declare a byte stream
4231   SALOMEDS::TMPFile_var aStreamFile;
4232
4233   // Obtain a temporary dir
4234   TCollection_AsciiString tmpDir =
4235     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4236
4237   // Create a sequence of files processed
4238   SALOMEDS_Tool::ListOfFiles aFileSeq;
4239   aFileSeq.reserve( NUM_TMP_FILES );
4240
4241   TCollection_AsciiString aStudyName( "" );
4242   if ( isMultiFile )
4243     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4244
4245   // Set names of temporary files
4246   TCollection_AsciiString filename =
4247     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
4248   TCollection_AsciiString meshfile =
4249     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
4250   aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4251   aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4252   filename = tmpDir + filename;
4253   meshfile = tmpDir + meshfile;
4254
4255   HDFfile*    aFile;
4256   HDFdataset* aDataset;
4257   HDFgroup*   aTopGroup;
4258   HDFgroup*   aGroup;
4259   HDFgroup*   aSubGroup;
4260   HDFgroup*   aSubSubGroup;
4261   hdf_size    aSize[ 1 ];
4262
4263
4264   //Remove the files if they exist: BugID: 11225
4265 #ifndef WIN32 /* unix functionality */
4266   TCollection_AsciiString cmd("rm -f \"");
4267 #else /* windows */
4268   TCollection_AsciiString cmd("del /F \"");
4269 #endif
4270
4271   cmd+=filename;
4272   cmd+="\" \"";
4273   cmd+=meshfile;
4274   cmd+="\"";
4275 #ifdef WIN32
4276   cmd+=" 2>NUL";
4277 #endif
4278   system(cmd.ToCString());
4279
4280   // MED writer to be used by storage process
4281   DriverMED_W_SMESHDS_Mesh writer;
4282   writer.SetFile( meshfile.ToCString() );
4283   //writer.SetSaveNumbers( false ); // bos #24400 -- it leads to change of element IDs
4284
4285   // IMP issue 20918
4286   // SetStoreName() to groups before storing hypotheses to let them refer to
4287   // groups using "store name", which is "Group <group_persistent_id>"
4288   {
4289     SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4290     for ( ; itBig->More(); itBig->Next() ) {
4291       SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4292       if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4293         CORBA::Object_var anObject = SObjectToObject( gotBranch );
4294         if ( !CORBA::is_nil( anObject ) ) {
4295           SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4296           if ( !myMesh->_is_nil() ) {
4297             myMesh->Load(); // load from study file if not yet done
4298             TPythonDump pd(this); // not to dump GetGroups()
4299             SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4300             for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4301             {
4302               SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4303               if ( grImpl )
4304               {
4305                 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4306                 int anId = myStudyContext->findId( string( objStr.in() ) );
4307                 char grpName[ 30 ];
4308                 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4309                 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4310                 aGrpBaseDS->SetStoreName( grpName );
4311               }
4312             }
4313           }
4314         }
4315       }
4316     }
4317   }
4318
4319   // Write data
4320   // ---> create HDF file
4321   aFile = new HDFfile( (char*) filename.ToCString() );
4322   aFile->CreateOnDisk();
4323
4324   // --> iterator for top-level objects
4325   SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4326   for ( ; itBig->More(); itBig->Next() ) {
4327     SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4328
4329     // --> hypotheses root branch (only one for the study)
4330     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4331       // create hypotheses root HDF group
4332       aTopGroup = new HDFgroup( "Hypotheses", aFile );
4333       aTopGroup->CreateOnDisk();
4334
4335       // iterator for all hypotheses
4336       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4337       for ( ; it->More(); it->Next() ) {
4338         SALOMEDS::SObject_wrap mySObject = it->Value();
4339         CORBA::Object_var anObject = SObjectToObject( mySObject );
4340         if ( !CORBA::is_nil( anObject ) ) {
4341           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4342           if ( !myHyp->_is_nil() ) {
4343             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4344             if ( myImpl ) {
4345               CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4346               std::string hypname = hn.in();
4347               std::string libname = ln.in();
4348               // BUG SWP13062
4349               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4350               // WIN32 and ".so" for X-system) must be deleted
4351               int libname_len = libname.length();
4352 #ifdef WIN32
4353               if( libname_len > 4 )
4354                 libname.resize( libname_len - 4 );
4355 #else
4356               // PAL17753 (Regression: missing hypothesis in restored study)
4357               // "lib" also should be removed from the beginning
4358               if( libname_len > 6 )
4359                 libname = libname.substr( 3, libname_len - 3 - 3 );
4360 #endif
4361               CORBA::String_var  objStr = GetORB()->object_to_string( anObject );
4362               CORBA::String_var hypdata = myImpl->SaveTo();
4363               int                    id = myStudyContext->findId( string( objStr.in() ));
4364
4365               // for each hypothesis create HDF group basing on its id
4366               char hypGrpName[30];
4367               sprintf( hypGrpName, "Hypothesis %d", id );
4368               aGroup = new HDFgroup( hypGrpName, aTopGroup );
4369               aGroup->CreateOnDisk();
4370               // --> type name of hypothesis
4371               aSize[ 0 ] = hypname.length() + 1;
4372               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4373               aDataset->CreateOnDisk();
4374               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4375               aDataset->CloseOnDisk();
4376               // --> server plugin library name of hypothesis
4377               aSize[ 0 ] = libname.length() + 1;
4378               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4379               aDataset->CreateOnDisk();
4380               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4381               aDataset->CloseOnDisk();
4382               // --> persistent data of hypothesis
4383               aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4384               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4385               aDataset->CreateOnDisk();
4386               aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4387               aDataset->CloseOnDisk();
4388               // close hypothesis HDF group
4389               aGroup->CloseOnDisk();
4390             }
4391           }
4392         }
4393       }
4394       // close hypotheses root HDF group
4395       aTopGroup->CloseOnDisk();
4396     }
4397     // --> algorithms root branch (only one for the study)
4398     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4399       // create algorithms root HDF group
4400       aTopGroup = new HDFgroup( "Algorithms", aFile );
4401       aTopGroup->CreateOnDisk();
4402
4403       // iterator for all algorithms
4404       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4405       for ( ; it->More(); it->Next() ) {
4406         SALOMEDS::SObject_wrap mySObject = it->Value();
4407         CORBA::Object_var anObject = SObjectToObject( mySObject );
4408         if ( !CORBA::is_nil( anObject ) ) {
4409           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4410           if ( !myHyp->_is_nil() ) {
4411             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4412             if ( myImpl ) {
4413               CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4414               std::string hypname = hn.in();
4415               std::string libname = ln.in();
4416               // BUG SWP13062
4417               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4418               // WIN32 and ".so" for X-system) must be deleted
4419               int libname_len = libname.length();
4420 #ifdef WIN32
4421               if( libname_len > 4 )
4422                 libname.resize( libname_len - 4 );
4423 #else
4424               // PAL17753 (Regression: missing hypothesis in restored study)
4425               // "lib" also should be removed from the beginning
4426               if( libname_len > 6 )
4427                 libname = libname.substr( 3, libname_len - 3 - 3 );
4428 #endif
4429               CORBA::String_var  objStr = GetORB()->object_to_string( anObject );
4430               CORBA::String_var hypdata = myImpl->SaveTo();
4431               int                    id = myStudyContext->findId( string( objStr.in() ) );
4432
4433               // for each algorithm create HDF group basing on its id
4434               char hypGrpName[30];
4435               sprintf( hypGrpName, "Algorithm %d", id );
4436               aGroup = new HDFgroup( hypGrpName, aTopGroup );
4437               aGroup->CreateOnDisk();
4438               // --> type name of algorithm
4439               aSize[0] = hypname.length() + 1;
4440               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4441               aDataset->CreateOnDisk();
4442               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4443               aDataset->CloseOnDisk();
4444               // --> server plugin library name of hypothesis
4445               aSize[0] = libname.length() + 1;
4446               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4447               aDataset->CreateOnDisk();
4448               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4449               aDataset->CloseOnDisk();
4450               // --> persistent data of algorithm
4451               aSize[0] = strlen( hypdata.in() ) + 1;
4452               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4453               aDataset->CreateOnDisk();
4454               aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4455               aDataset->CloseOnDisk();
4456               // close algorithm HDF group
4457               aGroup->CloseOnDisk();
4458             }
4459           }
4460         }
4461       }
4462       // close algorithms root HDF group
4463       aTopGroup->CloseOnDisk();
4464     }
4465     // --> mesh objects roots branches
4466     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4467       CORBA::Object_var anObject = SObjectToObject( gotBranch );
4468       if ( !CORBA::is_nil( anObject ) ) {
4469         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4470         if ( !myMesh->_is_nil() ) {
4471           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4472           if ( myImpl ) {
4473             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4474             int id = myStudyContext->findId( string( objStr.in() ) );
4475             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4476             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4477             bool hasShape = myLocMesh.HasShapeToMesh();
4478
4479             // for each mesh open the HDF group basing on its id
4480             char meshGrpName[ 30 ];
4481             sprintf( meshGrpName, "Mesh %d", id );
4482             aTopGroup = new HDFgroup( meshGrpName, aFile );
4483             aTopGroup->CreateOnDisk();
4484
4485             // --> put dataset to hdf file which is a flag that mesh has data
4486             string strHasData = "0";
4487             // check if the mesh is not empty
4488             if ( mySMESHDSMesh->NbNodes() > 0 ) {
4489               // write mesh data to med file
4490               writer.SetMesh( mySMESHDSMesh );
4491               writer.SetMeshId( id );
4492               strHasData = "1";
4493             }
4494             aSize[ 0 ] = strHasData.length() + 1;
4495             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4496             aDataset->CreateOnDisk();
4497             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4498             aDataset->CloseOnDisk();
4499
4500             // ouv : NPAL12872
4501             // for each mesh open the HDF group basing on its auto color parameter
4502             char meshAutoColorName[ 30 ];
4503             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4504             int anAutoColor[1];
4505             anAutoColor[0] = myImpl->GetAutoColor();
4506             aSize[ 0 ] = 1;
4507             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4508             aDataset->CreateOnDisk();
4509             aDataset->WriteOnDisk( anAutoColor );
4510             aDataset->CloseOnDisk();
4511
4512             // issue 0020693. Store _isModified flag
4513             int isModified = myLocMesh.GetIsModified();
4514             aSize[ 0 ] = 1;
4515             aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4516             aDataset->CreateOnDisk();
4517             aDataset->WriteOnDisk( &isModified );
4518             aDataset->CloseOnDisk();
4519
4520             // issue 20918. Store Persistent Id of SMESHDS_Mesh
4521             int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4522             aSize[ 0 ] = 1;
4523             aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4524             aDataset->CreateOnDisk();
4525             aDataset->WriteOnDisk( &meshPersistentId );
4526             aDataset->CloseOnDisk();
4527
4528             // Store SMESH_Mesh_i::_mainShapeTick
4529             int shapeTick = myImpl->MainShapeTick();
4530             aSize[ 0 ] = 1;
4531             aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4532             aDataset->CreateOnDisk();
4533             aDataset->WriteOnDisk( &shapeTick );
4534             aDataset->CloseOnDisk();
4535
4536             // write reference on a shape if exists
4537             SALOMEDS::SObject_wrap myRef;
4538             bool shapeRefFound = false;
4539             bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4540             if ( found ) {
4541               SALOMEDS::SObject_wrap myShape;
4542               bool ok = myRef->ReferencedObject( myShape.inout() );
4543               if ( ok ) {
4544                 CORBA::Object_var shapeObj = myShape->GetObject();
4545                 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4546                 CORBA::String_var myRefOnObject = myShape->GetID();
4547                 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4548                   aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4549                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4550                   aDataset->CreateOnDisk();
4551                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4552                   aDataset->CloseOnDisk();
4553                 }
4554               }
4555             }
4556
4557             // Store file info
4558             std::string info = myImpl->FileInfoToString();
4559             if ( !info.empty() )
4560             {
4561               aSize[ 0 ] = info.size();
4562               aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4563               aDataset->CreateOnDisk();
4564               aDataset->WriteOnDisk( (char*) info.data() );
4565               aDataset->CloseOnDisk();
4566             }
4567
4568             // write applied hypotheses if exist
4569             SALOMEDS::SObject_wrap myHypBranch;
4570             found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4571             if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4572               aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4573             }
4574             if ( found && (shapeRefFound || !hasShape) ) {
4575               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4576               aGroup->CreateOnDisk();
4577
4578               SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4579               int hypNb = 0;
4580               for ( ; it->More(); it->Next() ) {
4581                 SALOMEDS::SObject_wrap mySObject = it->Value();
4582                 SALOMEDS::SObject_wrap myRefOnHyp;
4583                 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4584                 if ( ok ) {
4585                   // san - it is impossible to recover applied hypotheses
4586                   //       using their entries within Load() method,
4587                   // for there are no AttributeIORs in the study when Load() is working.
4588                   // Hence, it is better to store persistent IDs of hypotheses as references to them
4589
4590                   //string myRefOnObject = myRefOnHyp->GetID();
4591                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4592                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4593                   int id = myStudyContext->findId( string( objStr.in() ) );
4594                   //if ( myRefOnObject.length() > 0 ) {
4595                   //aSize[ 0 ] = myRefOnObject.length() + 1;
4596                   char hypName[ 30 ], hypId[ 30 ];
4597                   sprintf( hypName, "Hyp %d", ++hypNb );
4598                   sprintf( hypId, "%d", id );
4599                   aSize[ 0 ] = strlen( hypId ) + 1;
4600                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4601                   aDataset->CreateOnDisk();
4602                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4603                   aDataset->WriteOnDisk( hypId );
4604                   aDataset->CloseOnDisk();
4605                   //}
4606                 }
4607               }
4608               aGroup->CloseOnDisk();
4609             }
4610
4611             // write applied algorithms if exist
4612             SALOMEDS::SObject_wrap myAlgoBranch;
4613             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4614                                               myAlgoBranch.inout() );
4615             if ( found && !shapeRefFound && hasShape) { // remove applied algos
4616               aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4617             }
4618             if ( found && (shapeRefFound || !hasShape)) {
4619               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4620               aGroup->CreateOnDisk();
4621
4622               SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4623               int algoNb = 0;
4624               for ( ; it->More(); it->Next() ) {
4625                 SALOMEDS::SObject_wrap mySObject = it->Value();
4626                 SALOMEDS::SObject_wrap myRefOnAlgo;
4627                 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4628                 if ( ok ) {
4629                   // san - it is impossible to recover applied algorithms
4630                   //       using their entries within Load() method,
4631                   // for there are no AttributeIORs in the study when Load() is working.
4632                   // Hence, it is better to store persistent IDs of algorithms as references to them
4633
4634                   //string myRefOnObject = myRefOnAlgo->GetID();
4635                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4636                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4637                   int id = myStudyContext->findId( string( objStr.in() ) );
4638                   //if ( myRefOnObject.length() > 0 ) {
4639                   //aSize[ 0 ] = myRefOnObject.length() + 1;
4640                   char algoName[ 30 ], algoId[ 30 ];
4641                   sprintf( algoName, "Algo %d", ++algoNb );
4642                   sprintf( algoId, "%d", id );
4643                   aSize[ 0 ] = strlen( algoId ) + 1;
4644                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4645                   aDataset->CreateOnDisk();
4646                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4647                   aDataset->WriteOnDisk( algoId );
4648                   aDataset->CloseOnDisk();
4649                   //}
4650                 }
4651               }
4652               aGroup->CloseOnDisk();
4653             }
4654
4655             // --> submesh objects sub-branches
4656
4657             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4658               SALOMEDS::SObject_wrap mySubmeshBranch;
4659               found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4660
4661               if ( found ) // check if there is shape reference in submeshes
4662               {
4663                 bool hasShapeRef = false;
4664                 SALOMEDS::ChildIterator_wrap itSM =
4665                   aStudy->NewChildIterator( mySubmeshBranch );
4666                 for ( ; itSM->More(); itSM->Next() ) {
4667                   SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4668                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4669                     mySubRef->ReferencedObject( myShape.inout() );
4670                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4671                     hasShapeRef = true;
4672                   else
4673                   { // remove one submesh
4674                     if ( shapeRefFound )
4675                     { // unassign hypothesis
4676                       SMESH::SMESH_subMesh_var mySubMesh =
4677                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4678                       if ( !mySubMesh->_is_nil() ) {
4679                         int shapeID = mySubMesh->GetId();
4680                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4681                         const list<const SMESHDS_Hypothesis*>& hypList =
4682                           mySMESHDSMesh->GetHypothesis( S );
4683                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4684                         while ( hyp != hypList.end() ) {
4685                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
4686                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4687                         }
4688                       }
4689                     }
4690                     aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4691                   }
4692                 } // loop on submeshes of a type
4693                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4694                   aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4695                   found = false;
4696                 }
4697               }  // end check if there is shape reference in submeshes
4698               if ( found ) {
4699                 char name_meshgroup[ 30 ];
4700                 if ( i == GetSubMeshOnVertexTag() )
4701                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
4702                 else if ( i == GetSubMeshOnEdgeTag() )
4703                   strcpy( name_meshgroup, "SubMeshes On Edge" );
4704                 else if ( i == GetSubMeshOnWireTag() )
4705                   strcpy( name_meshgroup, "SubMeshes On Wire" );
4706                 else if ( i == GetSubMeshOnFaceTag() )
4707                   strcpy( name_meshgroup, "SubMeshes On Face" );
4708                 else if ( i == GetSubMeshOnShellTag() )
4709                   strcpy( name_meshgroup, "SubMeshes On Shell" );
4710                 else if ( i == GetSubMeshOnSolidTag() )
4711                   strcpy( name_meshgroup, "SubMeshes On Solid" );
4712                 else if ( i == GetSubMeshOnCompoundTag() )
4713                   strcpy( name_meshgroup, "SubMeshes On Compound" );
4714
4715                 // for each type of submeshes create container HDF group
4716                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4717                 aGroup->CreateOnDisk();
4718
4719                 // iterator for all submeshes of given type
4720                 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4721                 for ( ; itSM->More(); itSM->Next() ) {
4722                   SALOMEDS::SObject_wrap mySObject = itSM->Value();
4723                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4724                   if ( !CORBA::is_nil( anSubObject ))
4725                   {
4726                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4727                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4728                     int subid = myStudyContext->findId( string( objStr.in() ) );
4729
4730                     // for each mesh open the HDF group basing on its id
4731                     char submeshGrpName[ 30 ];
4732                     sprintf( submeshGrpName, "SubMesh %d", subid );
4733                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4734                     aSubGroup->CreateOnDisk();
4735
4736                     // write reference on a shape, already checked if it exists
4737                     SALOMEDS::SObject_wrap mySubRef, myShape;
4738                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4739                       mySubRef->ReferencedObject( myShape.inout() );
4740                     string myRefOnObject = myShape->GetID();
4741                     if ( myRefOnObject.length() > 0 ) {
4742                       aSize[ 0 ] = myRefOnObject.length() + 1;
4743                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4744                       aDataset->CreateOnDisk();
4745                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4746                       aDataset->CloseOnDisk();
4747                     }
4748
4749                     // write applied hypotheses if exist
4750                     SALOMEDS::SObject_wrap mySubHypBranch;
4751                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4752                                                       mySubHypBranch.inout() );
4753                     if ( found ) {
4754                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4755                       aSubSubGroup->CreateOnDisk();
4756
4757                       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4758                       int hypNb = 0;
4759                       for ( ; it->More(); it->Next() ) {
4760                         SALOMEDS::SObject_wrap mySubSObject = it->Value();
4761                         SALOMEDS::SObject_wrap myRefOnHyp;
4762                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4763                         if ( ok ) {
4764                           //string myRefOnObject = myRefOnHyp->GetID();
4765                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4766                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4767                           int id = myStudyContext->findId( string( objStr.in() ) );
4768                           //if ( myRefOnObject.length() > 0 ) {
4769                           //aSize[ 0 ] = myRefOnObject.length() + 1;
4770                           char hypName[ 30 ], hypId[ 30 ];
4771                           sprintf( hypName, "Hyp %d", ++hypNb );
4772                           sprintf( hypId, "%d", id );
4773                           aSize[ 0 ] = strlen( hypId ) + 1;
4774                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4775                           aDataset->CreateOnDisk();
4776                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4777                           aDataset->WriteOnDisk( hypId );
4778                           aDataset->CloseOnDisk();
4779                           //}
4780                         }
4781                       }
4782                       aSubSubGroup->CloseOnDisk();
4783                     }
4784
4785                     // write applied algorithms if exist
4786                     SALOMEDS::SObject_wrap mySubAlgoBranch;
4787                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4788                                                       mySubAlgoBranch.inout() );
4789                     if ( found ) {
4790                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4791                       aSubSubGroup->CreateOnDisk();
4792
4793                       SALOMEDS::ChildIterator_wrap it =
4794                         aStudy->NewChildIterator( mySubAlgoBranch );
4795                       int algoNb = 0;
4796                       for ( ; it->More(); it->Next() ) {
4797                         SALOMEDS::SObject_wrap mySubSObject = it->Value();
4798                         SALOMEDS::SObject_wrap myRefOnAlgo;
4799                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4800                         if ( ok ) {
4801                           //string myRefOnObject = myRefOnAlgo->GetID();
4802                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4803                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4804                           int id = myStudyContext->findId( string( objStr.in() ) );
4805                           //if ( myRefOnObject.length() > 0 ) {
4806                           //aSize[ 0 ] = myRefOnObject.length() + 1;
4807                           char algoName[ 30 ], algoId[ 30 ];
4808                           sprintf( algoName, "Algo %d", ++algoNb );
4809                           sprintf( algoId, "%d", id );
4810                           aSize[ 0 ] = strlen( algoId ) + 1;
4811                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4812                           aDataset->CreateOnDisk();
4813                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4814                           aDataset->WriteOnDisk( algoId );
4815                           aDataset->CloseOnDisk();
4816                           //}
4817                         }
4818                       }
4819                       aSubSubGroup->CloseOnDisk();
4820                     }
4821                     // close submesh HDF group
4822                     aSubGroup->CloseOnDisk();
4823                   }
4824                 }
4825                 // close container of submeshes by type HDF group
4826                 aGroup->CloseOnDisk();
4827               }
4828             }
4829
4830             // store submesh order if any
4831             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4832             const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4833             if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4834               char order_list[ 30 ];
4835               strcpy( order_list, "Mesh Order" );
4836               // count number of submesh ids
4837               int nbIDs = 0;
4838               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4839               for ( ; idIt != theOrderIds.end(); idIt++ )
4840                 nbIDs += (*idIt).size();
4841               // number of values = number of IDs +
4842               //                    number of lists (for separators) - 1
4843               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4844               idIt = theOrderIds.begin();
4845               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4846                 const TListOfInt& idList = *idIt;
4847                 if (idIt != theOrderIds.begin()) // not first list
4848                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4849                 // dump submesh ids from current list
4850                 TListOfInt::const_iterator id_smId = idList.begin();
4851                 for( ; id_smId != idList.end(); id_smId++ )
4852                   smIDs[ i++ ] = *id_smId;
4853               }
4854               // write HDF group
4855               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4856
4857               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4858               aDataset->CreateOnDisk();
4859               aDataset->WriteOnDisk( smIDs );
4860               aDataset->CloseOnDisk();
4861               //
4862               delete[] smIDs;
4863             }
4864             if ( !theOrderIds.empty() && isNewOrederVersion )
4865             {
4866               // convert ids to entries
4867               std::list< std::list< std::string > > orderEntryLists;
4868               for ( const TListOfInt& idList : theOrderIds )
4869               {
4870                 orderEntryLists.emplace_back();
4871                 std::list< std::string > & entryList = orderEntryLists.back();
4872                 for ( const int& id : idList )
4873                 {
4874                   const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4875                   GEOM::GEOM_Object_var  go = ShapeToGeomObject( shape );
4876                   SALOMEDS::SObject_var  so = ObjectToSObject( go );
4877                   if ( !so->_is_nil() )
4878                   {
4879                     CORBA::String_var entry = so->GetID();
4880                     entryList.emplace_back( entry.in() );
4881                   }
4882                 }
4883               }
4884               // convert orderEntryLists to string
4885               std::ostringstream ostream;
4886               boost::archive::text_oarchive( ostream ) << orderEntryLists;
4887               std::string orderEntryString = ostream.str();
4888
4889               // write HDF group
4890               aSize[ 0 ] = orderEntryString.size() + 1;
4891               aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4892               aDataset->CreateOnDisk();
4893               aDataset->WriteOnDisk((char*) orderEntryString.data() );
4894               aDataset->CloseOnDisk();
4895             }
4896
4897             // groups root sub-branch
4898             SALOMEDS::SObject_wrap myGroupsBranch;
4899             for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4900               found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4901               if ( found ) {
4902                 char name_group[ 30 ];
4903                 if ( i == GetNodeGroupsTag() )
4904                   strcpy( name_group, "Groups of Nodes" );
4905                 else if ( i == GetEdgeGroupsTag() )
4906                   strcpy( name_group, "Groups of Edges" );
4907                 else if ( i == GetFaceGroupsTag() )
4908                   strcpy( name_group, "Groups of Faces" );
4909                 else if ( i == GetVolumeGroupsTag() )
4910                   strcpy( name_group, "Groups of Volumes" );
4911                 else if ( i == Get0DElementsGroupsTag() )
4912                   strcpy( name_group, "Groups of 0D Elements" );
4913                 else if ( i == GetBallElementsGroupsTag() )
4914                   strcpy( name_group, "Groups of Balls" );
4915
4916                 aGroup = new HDFgroup( name_group, aTopGroup );
4917                 aGroup->CreateOnDisk();
4918
4919                 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4920                 for ( ; it->More(); it->Next() ) {
4921                   SALOMEDS::SObject_wrap mySObject = it->Value();
4922                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4923                   if ( !CORBA::is_nil( aSubObject ) ) {
4924                     SMESH_GroupBase_i* myGroupImpl =
4925                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4926                     if ( !myGroupImpl )
4927                       continue;
4928                     SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4929                     if ( !aGrpBaseDS )
4930                       continue;
4931
4932                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4933                     int anId = myStudyContext->findId( string( objStr.in() ) );
4934
4935                     // For each group, create a dataset named "Group <group_persistent_id>"
4936                     // and store the group's user name into it
4937                     const char*         grpName = aGrpBaseDS->GetStoreName();
4938                     CORBA::String_var aUserName = myGroupImpl->GetName();
4939                     aSize[ 0 ] = strlen( aUserName ) + 1;
4940
4941                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4942                     aDataset->CreateOnDisk();
4943                     aDataset->WriteOnDisk( aUserName );
4944                     aDataset->CloseOnDisk();
4945
4946                     // ouv : NPAL12872
4947                     // For each group, create a dataset named "Group <group_persistent_id> Color"
4948                     // and store the group's color into it
4949                     char grpColorName[ 30 ];
4950                     sprintf( grpColorName, "ColorGroup %d", anId );
4951                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
4952                     double anRGB[3];
4953                     anRGB[ 0 ] = aColor.R;
4954                     anRGB[ 1 ] = aColor.G;
4955                     anRGB[ 2 ] = aColor.B;
4956                     aSize[ 0 ] = 3;
4957                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4958                     aDataset->CreateOnDisk();
4959                     aDataset->WriteOnDisk( anRGB );
4960                     aDataset->CloseOnDisk();
4961
4962                     // Pass SMESHDS_Group to MED writer
4963                     SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4964                     if ( aGrpDS )
4965                       writer.AddGroup( aGrpDS );
4966
4967                     // write reference on a shape if exists
4968                     SMESHDS_GroupOnGeom* aGeomGrp =
4969                       dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4970                     if ( aGeomGrp ) {
4971                       SALOMEDS::SObject_wrap mySubRef, myShape;
4972                       if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4973                           mySubRef->ReferencedObject( myShape.inout() ) &&
4974                           !CORBA::is_nil( myShape->GetObject() ))
4975                       {
4976                         CORBA::String_var myRefOnObject = myShape->GetID();
4977                         if ( myRefOnObject.in()[0] ) {
4978                           char aRefName[ 30 ];
4979                           sprintf( aRefName, "Ref on shape %d", anId);
4980                           aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4981                           aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4982                           aDataset->CreateOnDisk();
4983                           aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4984                           aDataset->CloseOnDisk();
4985                         }
4986                       }
4987                       else // shape ref is invalid:
4988                       {
4989                         // save a group on geometry as ordinary group
4990                         writer.AddGroup( aGeomGrp );
4991                       }
4992                     }
4993                     else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4994                               dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4995                     {
4996                       std::string str = aFilterGrp_i->FilterToString();
4997                       std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4998                       aSize[ 0 ] = str.length() + 1;
4999                       aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
5000                       aDataset->CreateOnDisk();
5001                       aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
5002                       aDataset->CloseOnDisk();
5003                     }
5004                   }
5005                 }
5006                 aGroup->CloseOnDisk();
5007               }
5008             } // loop on groups
5009
5010             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
5011             {
5012               // Flush current mesh information into MED file
5013               writer.Perform();
5014
5015               // save info on nb of elements
5016               SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
5017
5018               // maybe a shape was deleted in the study
5019               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
5020                 TopoDS_Shape nullShape;
5021                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
5022               }
5023
5024               SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
5025               if ( smIt->more() )
5026               {
5027                 // Store submeshes
5028                 // ----------------
5029                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
5030                 aGroup->CreateOnDisk();
5031
5032                 // each element belongs to one or none submesh,
5033                 // so for each node/element, we store a submesh ID
5034
5035                 // Store submesh IDs
5036                 for ( int isNode = 0; isNode < 2; ++isNode )
5037                 {
5038                   SMDS_ElemIteratorPtr eIt =
5039                     mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
5040                   smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
5041                   if ( nbElems < 1 )
5042                     continue;
5043                   std::vector<int> smIDs; smIDs.reserve( nbElems );
5044                   while ( eIt->more() )
5045                     if ( const SMDS_MeshElement* e = eIt->next())
5046                       smIDs.push_back( e->getshapeId() );
5047                   // write HDF group
5048                   aSize[ 0 ] = nbElems;
5049                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
5050                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5051                   aDataset->CreateOnDisk();
5052                   aDataset->WriteOnDisk( & smIDs[0] );
5053                   aDataset->CloseOnDisk();
5054                 }
5055
5056                 aGroup->CloseOnDisk();
5057
5058                 // Store node positions on sub-shapes (SMDS_Position):
5059                 // ----------------------------------------------------
5060
5061                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
5062                 aGroup->CreateOnDisk();
5063
5064                 // in aGroup, create 5 datasets to contain:
5065                 // "Nodes on Edges" - ID of node on edge
5066                 // "Edge positions" - U parameter on node on edge
5067                 // "Nodes on Faces" - ID of node on face
5068                 // "Face U positions" - U parameter of node on face
5069                 // "Face V positions" - V parameter of node on face
5070
5071                 // Find out nb of nodes on edges and faces
5072                 // Collect corresponding sub-meshes
5073                 int nbEdgeNodes = 0, nbFaceNodes = 0;
5074                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5075                 // loop on SMESHDS_SubMesh'es
5076                 while ( smIt->more() )
5077                 {
5078                   SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5079                   if ( aSubMesh->IsComplexSubmesh() )
5080                     continue; // submesh containing other submeshs
5081                   smIdType nbNodes = aSubMesh->NbNodes();
5082                   if ( nbNodes == 0 ) continue;
5083
5084                   int aShapeID = aSubMesh->GetID();
5085                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5086                     continue;
5087                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5088                   // write only SMDS_FacePosition and SMDS_EdgePosition
5089                   switch ( aShapeType ) {
5090                   case TopAbs_FACE:
5091                     nbFaceNodes += nbNodes;
5092                     aFaceSM.push_back( aSubMesh );
5093                     break;
5094                   case TopAbs_EDGE:
5095                     nbEdgeNodes += nbNodes;
5096                     aEdgeSM.push_back( aSubMesh );
5097                     break;
5098                   default:
5099                     continue;
5100                   }
5101                 }
5102                 // Treat positions on edges or faces
5103                 for ( int onFace = 0; onFace < 2; onFace++ )
5104                 {
5105                   // Create arrays to store in datasets
5106                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5107                   if (!nbNodes) continue;
5108                   int* aNodeIDs = new int [ nbNodes ];
5109                   double* aUPos = new double [ nbNodes ];
5110                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5111
5112                   // Fill arrays
5113                   // loop on sub-meshes
5114                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5115                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5116                   for ( ; itSM != pListSM->end(); itSM++ )
5117                   {
5118                     SMESHDS_SubMesh* aSubMesh = (*itSM);
5119
5120                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5121                     // loop on nodes in aSubMesh
5122                     while ( itNode->more() )
5123                     {
5124                       //node ID
5125                       const SMDS_MeshNode* node = itNode->next();
5126                       aNodeIDs [ iNode ] = node->GetID();
5127
5128                       // Position
5129                       const SMDS_PositionPtr pos = node->GetPosition();
5130                       if ( onFace ) { // on FACE
5131                         SMDS_FacePositionPtr fPos = pos;
5132                         if ( fPos ) {
5133                           aUPos[ iNode ] = fPos->GetUParameter();
5134                           aVPos[ iNode ] = fPos->GetVParameter();
5135                           iNode++;
5136                         }
5137                         else
5138                           nbNodes--;
5139                       }
5140                       else { // on EDGE
5141                         SMDS_EdgePositionPtr ePos = pos;
5142                         if ( ePos ) {
5143                           aUPos[ iNode ] = ePos->GetUParameter();
5144                           iNode++;
5145                         }
5146                         else
5147                           nbNodes--;
5148                       }
5149                     } // loop on nodes in aSubMesh
5150                   } // loop on sub-meshes
5151
5152                   // Write datasets
5153                   if ( nbNodes )
5154                   {
5155                     aSize[ 0 ] = nbNodes;
5156                     // IDS
5157                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5158                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5159                     aDataset->CreateOnDisk();
5160                     aDataset->WriteOnDisk( aNodeIDs );
5161                     aDataset->CloseOnDisk();
5162
5163                     // U Positions
5164                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
5165                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5166                     aDataset->CreateOnDisk();
5167                     aDataset->WriteOnDisk( aUPos );
5168                     aDataset->CloseOnDisk();
5169                     // V Positions
5170                     if ( onFace ) {
5171                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5172                       aDataset->CreateOnDisk();
5173                       aDataset->WriteOnDisk( aVPos );
5174                       aDataset->CloseOnDisk();
5175                     }
5176                   }
5177                   delete [] aNodeIDs;
5178                   delete [] aUPos;
5179                   if ( aVPos ) delete [] aVPos;
5180
5181                 } // treat positions on edges or faces
5182
5183                 // close "Node Positions" group
5184                 aGroup->CloseOnDisk();
5185
5186               } // if ( there are submeshes in SMESHDS_Mesh )
5187             } // if ( hasData )
5188
5189             // close mesh HDF group
5190             aTopGroup->CloseOnDisk();
5191           }
5192         }
5193       }
5194     }
5195   }
5196
5197   // close HDF file
5198   aFile->CloseOnDisk();
5199   delete aFile;
5200
5201   // Convert temporary files to stream
5202   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5203
5204   // Remove temporary files and directory
5205   if ( !isMultiFile )
5206     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5207
5208   return aStreamFile._retn();
5209 }
5210
5211 //=============================================================================
5212 /*!
5213  *  SMESH_Gen_i::SaveASCII
5214  *
5215  *  Save SMESH module's data in ASCII format
5216  */
5217 //=============================================================================
5218
5219 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5220                                            const char*              theURL,
5221                                            bool                     isMultiFile ) {
5222   MESSAGE( "SMESH_Gen_i::SaveASCII" );
5223   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5224   return aStreamFile._retn();
5225
5226   //after usual saving needs to encipher binary to text string
5227   //Any binary symbol will be represent as "|xx" () hexadecimal format number
5228   int size = aStreamFile.in().length();
5229   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5230   for ( int i = 0; i < size; i++ )
5231     sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5232
5233   buffer[size * 3] = '\0';
5234
5235   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5236
5237   return anAsciiStreamFile._retn();
5238 }
5239
5240 //=============================================================================
5241 /*!
5242  *  SMESH_Gen_i::Load
5243  *
5244  *  Load SMESH module's data
5245  */
5246 //=============================================================================
5247
5248 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5249                         const SALOMEDS::TMPFile& theStream,
5250                         const char*              theURL,
5251                         bool                     isMultiFile )
5252 {
5253   UpdateStudy(); // load geom data
5254   Kernel_Utils::Localizer loc;
5255
5256   SALOMEDS::Study_var aStudy = getStudyServant();
5257
5258   // Get temporary files location
5259   TCollection_AsciiString tmpDir =
5260     ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5261
5262   // Convert the stream into sequence of files to process
5263   SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5264                                                                          tmpDir.ToCString(),
5265                                                                          isMultiFile );
5266   TCollection_AsciiString aStudyName( "" );
5267   if ( isMultiFile ) {
5268     CORBA::WString_var url = aStudy->URL();
5269     SMESHUtils::ArrayDeleter<const char> urlMulibyte( Kernel_Utils::encode( url.in()) );
5270     aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( urlMulibyte.get() ).c_str();
5271   }
5272   // Set names of temporary files
5273   TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5274   TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5275
5276   int size;
5277   HDFfile*    aFile;
5278   HDFdataset* aDataset;
5279   HDFgroup*   aTopGroup;
5280   HDFgroup*   aGroup;
5281   HDFgroup*   aSubGroup;
5282   HDFgroup*   aSubSubGroup;
5283
5284   // Read data
5285   // ---> open HDF file
5286   aFile = new HDFfile( (char*) filename.ToCString() );
5287   try {
5288     aFile->OpenOnDisk( HDF_RDONLY );
5289   }
5290   catch ( HDFexception ) {
5291     INFOS( "Load(): " << filename << " not found!" );
5292     return false;
5293   }
5294
5295   TPythonDump pd(this); // prevent dump during loading
5296
5297   // For PAL13473 ("Repetitive mesh") implementation.
5298   // New dependencies between SMESH objects are established:
5299   // now hypotheses can refer to meshes, shapes and other hypotheses.
5300   // To keep data consistent, the following order of data restoration
5301   // imposed:
5302   // 1. Create hypotheses
5303   // 2. Create all meshes
5304   // 3. Load hypotheses' data
5305   // 4. All the rest
5306
5307   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
5308   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
5309   list< SMESH::Filter_var >                      filters;
5310
5311   // get total number of top-level groups
5312   int aNbGroups = aFile->nInternalObjects();
5313   if ( aNbGroups > 0 ) {
5314     // --> in first turn we should read&create hypotheses
5315     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5316       // open hypotheses root HDF group
5317       aTopGroup = new HDFgroup( "Hypotheses", aFile );
5318       aTopGroup->OpenOnDisk();
5319
5320       // get number of hypotheses
5321       int aNbObjects = aTopGroup->nInternalObjects();
5322       for ( int j = 0; j < aNbObjects; j++ ) {
5323         // try to identify hypothesis
5324         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5325         aTopGroup->InternalObjectIndentify( j, hypGrpName );
5326
5327         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5328           // open hypothesis group
5329           aGroup = new HDFgroup( hypGrpName, aTopGroup );
5330           aGroup->OpenOnDisk();
5331
5332           // --> get hypothesis id
5333           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5334           string hypname;
5335           string libname;
5336           string hypdata;
5337
5338           // get number of datasets
5339           int aNbSubObjects = aGroup->nInternalObjects();
5340           for ( int k = 0; k < aNbSubObjects; k++ ) {
5341             // identify dataset
5342             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5343             aGroup->InternalObjectIndentify( k, name_of_subgroup );
5344             // --> get hypothesis name
5345             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
5346               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5347               aDataset->OpenOnDisk();
5348               size = aDataset->GetSize();
5349               char* hypname_str = new char[ size ];
5350               aDataset->ReadFromDisk( hypname_str );
5351               hypname = string( hypname_str );
5352               delete [] hypname_str;
5353               aDataset->CloseOnDisk();
5354             }
5355             // --> get hypothesis plugin library name
5356             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
5357               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5358               aDataset->OpenOnDisk();
5359               size = aDataset->GetSize();
5360               char* libname_str = new char[ size ];
5361               aDataset->ReadFromDisk( libname_str );
5362               SCRUTE( libname_str );
5363               libname = string( libname_str );
5364               delete [] libname_str;
5365               aDataset->CloseOnDisk();
5366             }
5367             // --> get hypothesis data
5368             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
5369               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5370               aDataset->OpenOnDisk();
5371               size = aDataset->GetSize();
5372               char* hypdata_str = new char[ size ];
5373               aDataset->ReadFromDisk( hypdata_str );
5374               hypdata = string( hypdata_str );
5375               delete [] hypdata_str;
5376               aDataset->CloseOnDisk();
5377             }
5378           }
5379           // close hypothesis HDF group
5380           aGroup->CloseOnDisk();
5381
5382           // --> restore hypothesis from data
5383           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5384             MESSAGE("VSR - load hypothesis : id = " << id <<
5385                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5386             SMESH::SMESH_Hypothesis_var myHyp;
5387
5388             try { // protect persistence mechanism against exceptions
5389               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5390             }
5391             catch (...) {
5392               INFOS( "Exception during hypothesis creation" );
5393             }
5394
5395             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5396             if ( myImpl ) {
5397               // myImpl->LoadFrom( hypdata.c_str() );
5398               hypDataList.push_back( make_pair( myImpl, hypdata ));
5399               CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5400               int newId = myStudyContext->findId( iorString.in() );
5401               myStudyContext->mapOldToNew( id, newId );
5402             }
5403             else
5404               MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5405           }
5406         }
5407       }
5408       // close hypotheses root HDF group
5409       aTopGroup->CloseOnDisk();
5410       aTopGroup = 0;
5411     }
5412
5413     // --> then we should read&create algorithms
5414     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5415       // open algorithms root HDF group
5416       aTopGroup = new HDFgroup( "Algorithms", aFile );
5417       aTopGroup->OpenOnDisk();
5418
5419       // get number of algorithms
5420       int aNbObjects = aTopGroup->nInternalObjects();
5421       for ( int j = 0; j < aNbObjects; j++ ) {
5422         // try to identify algorithm
5423         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5424         aTopGroup->InternalObjectIndentify( j, hypGrpName );
5425
5426         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5427           // open algorithm group
5428           aGroup = new HDFgroup( hypGrpName, aTopGroup );
5429           aGroup->OpenOnDisk();
5430
5431           // --> get algorithm id
5432           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5433           string hypname;
5434           string libname;
5435           string hypdata;
5436
5437           // get number of datasets
5438           int aNbSubObjects = aGroup->nInternalObjects();
5439           for ( int k = 0; k < aNbSubObjects; k++ ) {
5440             // identify dataset
5441             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5442             aGroup->InternalObjectIndentify( k, name_of_subgroup );
5443             // --> get algorithm name
5444             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
5445               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5446               aDataset->OpenOnDisk();
5447               size = aDataset->GetSize();
5448               char* hypname_str = new char[ size ];
5449               aDataset->ReadFromDisk( hypname_str );
5450               hypname = string( hypname_str );
5451               delete [] hypname_str;
5452               aDataset->CloseOnDisk();
5453             }
5454             // --> get algorithm plugin library name
5455             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
5456               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5457               aDataset->OpenOnDisk();
5458               size = aDataset->GetSize();
5459               char* libname_str = new char[ size ];
5460               aDataset->ReadFromDisk( libname_str );
5461               SCRUTE( libname_str );
5462               libname = string( libname_str );
5463               delete [] libname_str;
5464               aDataset->CloseOnDisk();
5465             }
5466             // --> get algorithm data
5467             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
5468               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5469               aDataset->OpenOnDisk();
5470               size = aDataset->GetSize();
5471               char* hypdata_str = new char[ size ];
5472               aDataset->ReadFromDisk( hypdata_str );
5473               SCRUTE( hypdata_str );
5474               hypdata = string( hypdata_str );
5475               delete [] hypdata_str;
5476               aDataset->CloseOnDisk();
5477             }
5478           }
5479           // close algorithm HDF group
5480           aGroup->CloseOnDisk();
5481
5482           // --> restore algorithm from data
5483           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5484             MESSAGE("VSR - load algo : id = " << id <<
5485                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5486             SMESH::SMESH_Hypothesis_var myHyp;
5487
5488             try { // protect persistence mechanism against exceptions
5489               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5490             }
5491             catch( SALOME::SALOME_Exception& ex )
5492             {
5493               INFOS( "Exception during hypothesis creation: " << ex.details.text );
5494             }
5495             catch (...) {
5496               INFOS( "Exception during hypothesis creation" );
5497             }
5498
5499             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5500             if ( myImpl ) {
5501               //myImpl->LoadFrom( hypdata.c_str() );
5502               hypDataList.push_back( make_pair( myImpl, hypdata ));
5503               CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5504               int newId = myStudyContext->findId( iorString.in() );
5505               myStudyContext->mapOldToNew( id, newId );
5506             }
5507             else
5508               MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5509           }
5510         }
5511       }
5512       // close algorithms root HDF group
5513       aTopGroup->CloseOnDisk();
5514       aTopGroup = 0;
5515     }
5516
5517     // --> the rest groups should be meshes
5518     for ( int i = 0; i < aNbGroups; i++ ) {
5519       // identify next group
5520       char meshName[ HDF_NAME_MAX_LEN+1 ];
5521       aFile->InternalObjectIndentify( i, meshName );
5522
5523       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5524         // --> get mesh id
5525         int id = atoi( string( meshName ).substr( 4 ).c_str() );
5526         if ( id <= 0 )
5527           continue;
5528
5529         // open mesh HDF group
5530         aTopGroup = new HDFgroup( meshName, aFile );
5531         aTopGroup->OpenOnDisk();
5532
5533         // get number of child HDF objects
5534         int aNbObjects = aTopGroup->nInternalObjects();
5535         if ( aNbObjects > 0 ) {
5536           // create mesh
5537           MESSAGE( "VSR - load mesh : id = " << id );
5538           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5539           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5540           if ( !myNewMeshImpl )
5541             continue;
5542           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5543
5544           CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5545           int newId = myStudyContext->findId( iorString.in() );
5546           myStudyContext->mapOldToNew( id, newId );
5547
5548           // ouv : NPAL12872
5549           // try to read and set auto color flag
5550           char aMeshAutoColorName[ 30 ];
5551           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5552           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5553           {
5554             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5555             aDataset->OpenOnDisk();
5556             size = aDataset->GetSize();
5557             int* anAutoColor = new int[ size ];
5558             aDataset->ReadFromDisk( anAutoColor );
5559             aDataset->CloseOnDisk();
5560             myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5561             delete [] anAutoColor;
5562           }
5563
5564           // try to read and set reference to shape
5565           GEOM::GEOM_Object_var aShapeObject;
5566           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5567             // load mesh "Ref on shape" - it's an entry to SObject
5568             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5569             aDataset->OpenOnDisk();
5570             size = aDataset->GetSize();
5571             char* refFromFile = new char[ size ];
5572             aDataset->ReadFromDisk( refFromFile );
5573             aDataset->CloseOnDisk();
5574             if ( strlen( refFromFile ) > 0 ) {
5575               SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5576               CORBA::Object_var  shapeObject = SObjectToObject( shapeSO );
5577               if ( !CORBA::is_nil( shapeObject ) ) {
5578                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5579                 if ( !aShapeObject->_is_nil() )
5580                   myNewMeshImpl->SetShape( aShapeObject );
5581               }
5582             }
5583             delete [] refFromFile;
5584           }
5585
5586           // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5587           if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5588           {
5589             aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5590             aDataset->OpenOnDisk();
5591             size = aDataset->GetSize();
5592             int* meshPersistentId = new int[ size ];
5593             aDataset->ReadFromDisk( meshPersistentId );
5594             aDataset->CloseOnDisk();
5595             myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5596             delete [] meshPersistentId;
5597           }
5598
5599           // Restore SMESH_Mesh_i::_mainShapeTick
5600           if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5601           {
5602             aDataset = new HDFdataset( "shapeTick", aTopGroup );
5603             aDataset->OpenOnDisk();
5604             int* shapeTick = & myNewMeshImpl->MainShapeTick();
5605             aDataset->ReadFromDisk( shapeTick );
5606             aDataset->CloseOnDisk();
5607           }
5608
5609           // Restore file info
5610           if ( aTopGroup->ExistInternalObject( "file info" ))
5611           {
5612             aDataset = new HDFdataset( "file info", aTopGroup );
5613             aDataset->OpenOnDisk();
5614             size = aDataset->GetSize();
5615             std::string info( size, ' ');
5616             aDataset->ReadFromDisk( (char*) info.data() );
5617             aDataset->CloseOnDisk();
5618             myNewMeshImpl->FileInfoFromString( info );
5619           }
5620         }
5621       }
5622     } // reading MESHes
5623
5624     // As all objects that can be referred by hypothesis are created,
5625     // we can restore hypothesis data
5626
5627     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5628     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5629     {
5630       SMESH_Hypothesis_i* hyp  = hyp_data->first;
5631       string &            data = hyp_data->second;
5632       hyp->LoadFrom( data.c_str() );
5633     }
5634
5635     // Restore the rest mesh data
5636
5637     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5638     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5639     {
5640       aTopGroup                   = meshi_group->second;
5641       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5642
5643       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5644       bool hasData = false;
5645
5646       // get mesh old id
5647       CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5648       int newId = myStudyContext->findId( iorString.in() );
5649       int meshOldId = myStudyContext->getOldId( newId );
5650
5651       // try to find mesh data dataset
5652       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5653         // load mesh "has data" flag
5654         aDataset = new HDFdataset( "Has data", aTopGroup );
5655         aDataset->OpenOnDisk();
5656         size = aDataset->GetSize();
5657         char* strHasData = new char[ size ];
5658         aDataset->ReadFromDisk( strHasData );
5659         aDataset->CloseOnDisk();
5660         if ( strcmp( strHasData, "1") == 0 ) {
5661           hasData = true;
5662         }
5663         delete [] strHasData;
5664       }
5665
5666       // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5667       // nodes and elements are not yet put into sub-meshes)
5668       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5669         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5670         aGroup->OpenOnDisk();
5671         // get number of applied algorithms
5672         int aNbSubObjects = aGroup->nInternalObjects();
5673         MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5674         for ( int j = 0; j < aNbSubObjects; j++ ) {
5675           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5676           aGroup->InternalObjectIndentify( j, name_dataset );
5677           // check if it is an algorithm
5678           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5679             aDataset = new HDFdataset( name_dataset, aGroup );
5680             aDataset->OpenOnDisk();
5681             size = aDataset->GetSize();
5682             char* refFromFile = new char[ size ];
5683             aDataset->ReadFromDisk( refFromFile );
5684             aDataset->CloseOnDisk();
5685             // san - it is impossible to recover applied algorithms using their entries within Load() method
5686             int id = atoi( refFromFile );
5687             delete [] refFromFile;
5688             string anIOR = myStudyContext->getIORbyOldId( id );
5689             if ( !anIOR.empty() ) {
5690               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5691               if ( !CORBA::is_nil( hypObject ) ) {
5692                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5693                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5694                                            || !myNewMeshImpl->HasShapeToMesh()) )
5695                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5696               }
5697             }
5698           }
5699         }
5700         aGroup->CloseOnDisk();
5701       }
5702
5703       // try to get applied hypotheses
5704       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5705         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5706         aGroup->OpenOnDisk();
5707         // get number of applied hypotheses
5708         int aNbSubObjects = aGroup->nInternalObjects();
5709         for ( int j = 0; j < aNbSubObjects; j++ ) {
5710           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5711           aGroup->InternalObjectIndentify( j, name_dataset );
5712           // check if it is a hypothesis
5713           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5714             aDataset = new HDFdataset( name_dataset, aGroup );
5715             aDataset->OpenOnDisk();
5716             size = aDataset->GetSize();
5717             char* refFromFile = new char[ size ];
5718             aDataset->ReadFromDisk( refFromFile );
5719             aDataset->CloseOnDisk();
5720             // san - it is impossible to recover applied hypotheses using their entries within Load() method
5721             int id = atoi( refFromFile );
5722             delete [] refFromFile;
5723             string anIOR = myStudyContext->getIORbyOldId( id );
5724             if ( !anIOR.empty() ) {
5725               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5726               if ( !CORBA::is_nil( hypObject ) ) {
5727                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5728                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5729                                            || !myNewMeshImpl->HasShapeToMesh()) )
5730                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5731               }
5732             }
5733           }
5734         }
5735         aGroup->CloseOnDisk();
5736       }
5737
5738       // --> try to find SUB-MESHES containers for each type of submesh
5739       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5740         const char* name_meshgroup = 0;
5741         if ( j == GetSubMeshOnVertexTag() )
5742           name_meshgroup = "SubMeshes On Vertex";
5743         else if ( j == GetSubMeshOnEdgeTag() )
5744           name_meshgroup = "SubMeshes On Edge";
5745         else if ( j == GetSubMeshOnWireTag() )
5746           name_meshgroup = "SubMeshes On Wire";
5747         else if ( j == GetSubMeshOnFaceTag() )
5748           name_meshgroup = "SubMeshes On Face";
5749         else if ( j == GetSubMeshOnShellTag() )
5750           name_meshgroup = "SubMeshes On Shell";
5751         else if ( j == GetSubMeshOnSolidTag() )
5752           name_meshgroup = "SubMeshes On Solid";
5753         else if ( j == GetSubMeshOnCompoundTag() )
5754           name_meshgroup = "SubMeshes On Compound";
5755
5756         // try to get submeshes container HDF group
5757         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5758           // open submeshes containers HDF group
5759           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5760           aGroup->OpenOnDisk();
5761
5762           // get number of submeshes
5763           int aNbSubMeshes = aGroup->nInternalObjects();
5764           for ( int k = 0; k < aNbSubMeshes; k++ ) {
5765             // identify submesh
5766             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5767             aGroup->InternalObjectIndentify( k, name_submeshgroup );
5768             if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5769               // --> get submesh id
5770               int subid = atoi( name_submeshgroup + 7 );
5771               if ( subid <= 0 )
5772                 continue;
5773               // open submesh HDF group
5774               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5775               aSubGroup->OpenOnDisk();
5776
5777               // try to read and set reference to subshape
5778               GEOM::GEOM_Object_var aSubShapeObject;
5779               SMESH::SMESH_subMesh_var aSubMesh;
5780
5781               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5782                 // load submesh "Ref on shape" - it's an entry to SObject
5783                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5784                 aDataset->OpenOnDisk();
5785                 size = aDataset->GetSize();
5786                 char* refFromFile = new char[ size ];
5787                 aDataset->ReadFromDisk( refFromFile );
5788                 aDataset->CloseOnDisk();
5789                 if ( strlen( refFromFile ) > 0 ) {
5790                   SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5791                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5792                   if ( !CORBA::is_nil( subShapeObject ) ) {
5793                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5794                     if ( !aSubShapeObject->_is_nil() )
5795                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
5796                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5797                     if ( aSubMesh->_is_nil() )
5798                       continue;
5799                     string iorSubString = GetORB()->object_to_string( aSubMesh );
5800                     int        newSubId = myStudyContext->findId( iorSubString );
5801                     myStudyContext->mapOldToNew( subid, newSubId );
5802                   }
5803                 }
5804                 delete [] refFromFile;
5805               }
5806
5807               if ( aSubMesh->_is_nil() )
5808                 continue;
5809
5810               // try to get applied algorithms
5811               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5812                 // open "applied algorithms" HDF group
5813                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5814                 aSubSubGroup->OpenOnDisk();
5815                 // get number of applied algorithms
5816                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5817                 for ( int l = 0; l < aNbSubObjects; l++ ) {
5818                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5819                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5820                   // check if it is an algorithm
5821                   if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5822                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5823                     aDataset->OpenOnDisk();
5824                     size = aDataset->GetSize();
5825                     char* refFromFile = new char[ size ];
5826                     aDataset->ReadFromDisk( refFromFile );
5827                     aDataset->CloseOnDisk();
5828
5829                     int id = atoi( refFromFile );
5830                     string anIOR = myStudyContext->getIORbyOldId( id );
5831                     if ( !anIOR.empty() ) {
5832                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5833                       if ( !CORBA::is_nil( hypObject ) ) {
5834                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5835                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5836                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5837                       }
5838                     }
5839                     delete [] refFromFile;
5840                   }
5841                 }
5842                 // close "applied algorithms" HDF group
5843                 aSubSubGroup->CloseOnDisk();
5844               }
5845
5846               // try to get applied hypotheses
5847               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5848                 // open "applied hypotheses" HDF group
5849                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5850                 aSubSubGroup->OpenOnDisk();
5851                 // get number of applied hypotheses
5852                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5853                 for ( int l = 0; l < aNbSubObjects; l++ ) {
5854                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5855                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5856                   // check if it is a hypothesis
5857                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5858                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5859                     aDataset->OpenOnDisk();
5860                     size = aDataset->GetSize();
5861                     char* refFromFile = new char[ size ];
5862                     aDataset->ReadFromDisk( refFromFile );
5863                     aDataset->CloseOnDisk();
5864
5865                     int id = atoi( refFromFile );
5866                     string anIOR = myStudyContext->getIORbyOldId( id );
5867                     if ( !anIOR.empty() ) {
5868                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5869                       if ( !CORBA::is_nil( hypObject ) ) {
5870                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5871                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5872                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5873                       }
5874                     }
5875                     delete [] refFromFile;
5876                   }
5877                 }
5878                 // close "APPLIED HYPOTHESES" hdf group
5879                 aSubSubGroup->CloseOnDisk();
5880               }
5881
5882               // close SUB-MESH hdf group
5883               aSubGroup->CloseOnDisk();
5884             }
5885           }
5886           // close SUB-MESHES containers hdf group
5887           aGroup->CloseOnDisk();
5888         }
5889       }
5890
5891       // try to get GROUPS
5892       for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5893         char name_group[ 30 ];
5894         if ( ii == GetNodeGroupsTag() )
5895           strcpy( name_group, "Groups of Nodes" );
5896         else if ( ii == GetEdgeGroupsTag() )
5897           strcpy( name_group, "Groups of Edges" );
5898         else if ( ii == GetFaceGroupsTag() )
5899           strcpy( name_group, "Groups of Faces" );
5900         else if ( ii == GetVolumeGroupsTag() )
5901           strcpy( name_group, "Groups of Volumes" );
5902         else if ( ii == Get0DElementsGroupsTag() )
5903           strcpy( name_group, "Groups of 0D Elements" );
5904         else if ( ii == GetBallElementsGroupsTag() )
5905           strcpy( name_group, "Groups of Balls" );
5906
5907         if ( aTopGroup->ExistInternalObject( name_group ) ) {
5908           aGroup = new HDFgroup( name_group, aTopGroup );
5909           aGroup->OpenOnDisk();
5910           // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5911           // within aGroup->ExistInternalObject( name )
5912           std::vector< std::string > subNames;
5913           TColStd_MapOfAsciiString mapOfNames;
5914           aGroup->GetAllObjects( subNames );
5915           for ( size_t iN = 0; iN < subNames.size(); ++iN )
5916             mapOfNames.Add( subNames[ iN ].c_str() );
5917           // loop on groups
5918           for ( size_t j = 0; j < subNames.size(); j++ ) {
5919             const std::string& name_dataset = subNames[ j ];
5920             // check if it is a group
5921             if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5922               // --> get group id
5923               char * endptr;
5924               int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5925               if ( subid <= 0 )
5926                 continue;
5927               int groupID = -1; // group local ID (also persistent)
5928               if ( *endptr )
5929                 groupID = atoi( endptr + 1 );
5930               aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5931               aDataset->OpenOnDisk();
5932
5933               // Retrieve actual group name
5934               size = aDataset->GetSize();
5935               char* nameFromFile = new char[ size ];
5936               aDataset->ReadFromDisk( nameFromFile );
5937               aDataset->CloseOnDisk();
5938
5939               // Try to find a shape reference
5940               TopoDS_Shape aShape;
5941               char aRefName[ 30 ];
5942               sprintf( aRefName, "Ref on shape %d", subid);
5943               if ( mapOfNames.Contains( aRefName ))
5944               {
5945                 // load mesh "Ref on shape" - it's an entry to SObject
5946                 aDataset = new HDFdataset( aRefName, aGroup );
5947                 aDataset->OpenOnDisk();
5948                 size = aDataset->GetSize();
5949                 char* refFromFile = new char[ size ];
5950                 aDataset->ReadFromDisk( refFromFile );
5951                 aDataset->CloseOnDisk();
5952                 if ( strlen( refFromFile ) > 0 ) {
5953                   SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5954                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5955                   if ( !CORBA::is_nil( shapeObject ) ) {
5956                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5957                     if ( !aShapeObject->_is_nil() )
5958                       aShape = GeomObjectToShape( aShapeObject );
5959                   }
5960                 }
5961                 delete [] refFromFile;
5962               }
5963               // Try to read a filter of SMESH_GroupOnFilter
5964               SMESH::Filter_var filter;
5965               SMESH_PredicatePtr predicate;
5966               std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5967               if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5968               {
5969                 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5970                 aDataset->OpenOnDisk();
5971                 size = aDataset->GetSize();
5972                 char* persistStr = new char[ size ];
5973                 aDataset->ReadFromDisk( persistStr );
5974                 aDataset->CloseOnDisk();
5975                 if ( strlen( persistStr ) > 0 ) {
5976                   filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5977                   predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5978                   filters.push_back( filter );
5979                 }
5980                 delete [] persistStr;
5981               }
5982
5983               // Create group servant
5984               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5985               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5986                 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5987               delete [] nameFromFile;
5988               // Obtain a SMESHDS_Group object
5989               if ( aNewGroup->_is_nil() )
5990                 continue;
5991
5992               CORBA::String_var iorSubStringVar = GetORB()->object_to_string( aNewGroup );
5993               string iorSubString(iorSubStringVar.in());
5994               int        newSubId = myStudyContext->findId( iorSubString );
5995               myStudyContext->mapOldToNew( subid, newSubId );
5996
5997               SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5998               if ( !aGroupImpl )
5999                 continue;
6000
6001               if ( SMESH_GroupOnFilter_i* aFilterGroup =
6002                    dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
6003               {
6004                 aFilterGroup->SetFilter( filter );
6005                 filter->UnRegister();
6006               }
6007               SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
6008               if ( !aGroupBaseDS )
6009                 continue;
6010
6011               aGroupBaseDS->SetStoreName( name_dataset.c_str() );
6012
6013               // ouv : NPAL12872
6014               // Read color of the group
6015               char aGroupColorName[ 30 ];
6016               sprintf( aGroupColorName, "ColorGroup %d", subid);
6017               if ( mapOfNames.Contains( aGroupColorName ))
6018               {
6019                 aDataset = new HDFdataset( aGroupColorName, aGroup );
6020                 aDataset->OpenOnDisk();
6021                 size = aDataset->GetSize();
6022                 double* anRGB = new double[ size ];
6023                 aDataset->ReadFromDisk( anRGB );
6024                 aDataset->CloseOnDisk();
6025                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
6026                 aGroupBaseDS->SetColor( aColor );
6027                 delete [] anRGB;
6028               }
6029             }
6030           }
6031           aGroup->CloseOnDisk();
6032         }
6033       } // reading GROUPs
6034
6035       // instead of reading mesh data, we read only brief information of all
6036       // objects: mesh, groups, sub-meshes (issue 0021208)
6037       if ( hasData )
6038       {
6039         SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
6040                                          meshfile.ToCString(), filename.ToCString(),
6041                                          !isMultiFile );
6042       }
6043
6044       // read Sub-Mesh ORDER if any
6045       if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
6046         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
6047         aDataset->OpenOnDisk();
6048         size = aDataset->GetSize();
6049         int* smIDs = new int[ size ];
6050         aDataset->ReadFromDisk( smIDs );
6051         aDataset->CloseOnDisk();
6052         TListOfListOfInt anOrderIds;
6053         anOrderIds.push_back( TListOfInt() );
6054         for ( int i = 0; i < size; i++ )
6055           if ( smIDs[ i ] < 0 ) // is separator
6056             anOrderIds.push_back( TListOfInt() );
6057           else
6058             anOrderIds.back().push_back(smIDs[ i ]);
6059
6060         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6061         delete [] smIDs;
6062       }
6063       if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
6064       {
6065         aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
6066         aDataset->OpenOnDisk();
6067         size = aDataset->GetSize();
6068         std::string dataString; dataString.resize( size );
6069         aDataset->ReadFromDisk((char*) dataString.data() );
6070         aDataset->CloseOnDisk();
6071
6072         std::list< std::list< std::string > > orderEntryLists;
6073         SMESHUtils::BoostTxtArchive( dataString ) >> orderEntryLists;
6074
6075         TListOfListOfInt anOrderIds;
6076         for ( const std::list< std::string >& entryList : orderEntryLists )
6077         {
6078           anOrderIds.emplace_back();
6079           for ( const std::string & entry : entryList )
6080           {
6081             GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6082             TopoDS_Shape       shape = GeomObjectToShape( go );
6083             if ( SMESH_subMesh*   sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6084               anOrderIds.back().emplace_back( sm->GetId() );
6085           }
6086         }
6087         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6088       }
6089     } // loop on meshes
6090
6091     // update hyps needing full mesh data restored (issue 20918)
6092     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6093     {
6094       SMESH_Hypothesis_i* hyp  = hyp_data->first;
6095       hyp->UpdateAsMeshesRestored();
6096     }
6097
6098     // notify algos on completed restoration to set sub-mesh event listeners
6099     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6100     {
6101       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6102       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
6103
6104       TopoDS_Shape myLocShape;
6105       if(myLocMesh.HasShapeToMesh())
6106         myLocShape = myLocMesh.GetShapeToMesh();
6107       else
6108         myLocShape = SMESH_Mesh::PseudoShape();
6109
6110       myLocMesh.GetSubMesh(myLocShape)->
6111         ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6112     }
6113
6114     // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6115     list< SMESH::Filter_var >::iterator f = filters.begin();
6116     for ( ; f != filters.end(); ++f )
6117       if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6118         fi->FindBaseObjects();
6119
6120
6121     // close mesh group
6122     if(aTopGroup)
6123       aTopGroup->CloseOnDisk();
6124   }
6125   // close HDF file
6126   aFile->CloseOnDisk();
6127   delete aFile;
6128
6129   // Remove temporary files created from the stream
6130   if ( !isMultiFile )
6131   {
6132     SMESH_File meshFile( meshfile.ToCString() );
6133     if ( !meshFile ) // no meshfile exists
6134     {
6135       SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6136     }
6137     else
6138     {
6139       Engines::Container_var container = GetContainerRef();
6140       if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6141       {
6142         container_i->registerTemporaryFile( filename.ToCString() );
6143         container_i->registerTemporaryFile( meshfile.ToCString() );
6144         container_i->registerTemporaryFile( tmpDir.ToCString() );
6145       }
6146     }
6147   }
6148
6149   // creation of tree nodes for all data objects in the study
6150   // to support tree representation customization and drag-n-drop:
6151   SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6152   if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6153     useCaseBuilder->SetRootCurrent();
6154     useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6155     SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6156     for (it->InitEx(true); it->More(); it->Next()) {
6157       useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6158     }
6159   }
6160
6161   return true;
6162 }
6163
6164 //=============================================================================
6165 /*!
6166  *  SMESH_Gen_i::LoadASCII
6167  *
6168  *  Load SMESH module's data in ASCII format
6169  */
6170 //=============================================================================
6171
6172 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6173                              const SALOMEDS::TMPFile& theStream,
6174                              const char*              theURL,
6175                              bool                     isMultiFile ) {
6176   MESSAGE( "SMESH_Gen_i::LoadASCII" );
6177   return Load( theComponent, theStream, theURL, isMultiFile );
6178
6179   //before call main ::Load method it's need for decipher text format to
6180   //binary ( "|xx" => x' )
6181   int size = theStream.length();
6182   if ( int((size / 3 )*3) != size ) //error size of buffer
6183     return false;
6184
6185   int real_size = int(size / 3);
6186
6187   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6188   char tmp[3];
6189   tmp[2]='\0';
6190   unsigned int c = -1;
6191   for ( int i = 0; i < real_size; i++ )
6192   {
6193     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6194     sscanf( tmp, "%x", &c );
6195     sprintf( (char*)&(buffer[i]), "%c", (char)c );
6196   }
6197
6198   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6199
6200   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6201 }
6202
6203 //=============================================================================
6204 /*!
6205  *  SMESH_Gen_i::Close
6206  *
6207  *  Clears study-connected data when it is closed
6208  */
6209 //=============================================================================
6210
6211 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6212 {
6213   MESSAGE( "SMESH_Gen_i::Close" );
6214
6215   // Clear study contexts data
6216   myStudyContext->Clear();
6217
6218   // remove the tmp files meshes are loaded from
6219   SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6220
6221   // Clean trace of API methods calls
6222   CleanPythonTrace();
6223
6224   return;
6225 }
6226
6227 //=============================================================================
6228 /*!
6229  *  SMESH_Gen_i::ComponentDataType
6230  *
6231  *  Get component data type
6232  */
6233 //=============================================================================
6234
6235 char* SMESH_Gen_i::ComponentDataType()
6236 {
6237   MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6238   return CORBA::string_dup( "SMESH" );
6239 }
6240
6241
6242 //=============================================================================
6243 /*!
6244  *  SMESH_Gen_i::IORToLocalPersistentID
6245  *
6246  *  Transform data from transient form to persistent
6247  */
6248 //=============================================================================
6249
6250 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6251                                            const char*           IORString,
6252                                            CORBA::Boolean        /*isMultiFile*/,
6253                                            CORBA::Boolean        /*isASCII*/ )
6254 {
6255   MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6256
6257   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6258     int anId = myStudyContext->findId( IORString );
6259     if ( anId ) {
6260       MESSAGE( "VSR " << anId );
6261       char strId[ 20 ];
6262       sprintf( strId, "%d", anId );
6263       return  CORBA::string_dup( strId );
6264     }
6265   }
6266   return CORBA::string_dup( "" );
6267 }
6268
6269 //=============================================================================
6270 /*!
6271  *  SMESH_Gen_i::LocalPersistentIDToIOR
6272  *
6273  *  Transform data from persistent form to transient
6274  */
6275 //=============================================================================
6276
6277 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6278                                            const char*           aLocalPersistentID,
6279                                            CORBA::Boolean        /*isMultiFile*/,
6280                                            CORBA::Boolean        /*isASCII*/ )
6281 {
6282   MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6283
6284   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6285     int anId = atoi( aLocalPersistentID );
6286     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6287   }
6288   return CORBA::string_dup( "" );
6289 }
6290
6291 //=======================================================================
6292 //function : RegisterObject
6293 //purpose  :
6294 //=======================================================================
6295
6296 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6297 {
6298   if ( myStudyContext && !CORBA::is_nil( theObject )) {
6299     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6300     return myStudyContext->addObject( string( iorString.in() ) );
6301   }
6302   return 0;
6303 }
6304
6305 //================================================================================
6306 /*!
6307  * \brief Return id of registered object
6308   * \param theObject - the Object
6309   * \retval int - Object id
6310  */
6311 //================================================================================
6312
6313 CORBA::Long  SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6314 {
6315   if ( myStudyContext && !CORBA::is_nil( theObject )) {
6316     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6317     string iorStringCpp(iorString.in());
6318     return myStudyContext->findId( iorStringCpp );
6319   }
6320   return 0;
6321 }
6322
6323 //=============================================================================
6324 /*!
6325  *  SMESH_Gen_i::SetName
6326  *
6327  *  Set a new object name
6328  */
6329 //=============================================================================
6330
6331 void SMESH_Gen_i::SetName(const char* theIOR,
6332                           const char* theName)
6333 {
6334   if ( theIOR && strcmp( theIOR, "" ) ) {
6335     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6336     SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6337     if ( !aSO->_is_nil() ) {
6338       SetName( aSO, theName );
6339     }
6340   }
6341 }
6342
6343 // Version information
6344 char* SMESH_Gen_i::getVersion()
6345 {
6346 #if SMESH_DEVELOPMENT
6347   return CORBA::string_dup(SMESH_VERSION_STR"dev");
6348 #else
6349   return CORBA::string_dup(SMESH_VERSION_STR);
6350 #endif
6351 }
6352
6353 //=================================================================================
6354 // function : Move()
6355 // purpose  : Moves objects to the specified position.
6356 //            Is used in the drag-n-drop functionality.
6357 //=================================================================================
6358
6359 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6360                         SALOMEDS::SObject_ptr      where,
6361                         CORBA::Long                row )
6362 {
6363   if ( CORBA::is_nil( where ) ) return;
6364
6365   SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6366   SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6367   SALOMEDS::SComponent_var father = where->GetFatherComponent();
6368   std::string dataType = father->ComponentDataType();
6369   if ( dataType != "SMESH" ) return; // not a SMESH component
6370
6371   SALOMEDS::SObject_var objAfter;
6372   if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6373     // insert at given row -> find insertion position
6374     SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6375     int i;
6376     for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6377     if ( i == row && useCaseIt->More() ) {
6378       objAfter = useCaseIt->Value();
6379     }
6380   }
6381
6382   for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6383     SALOMEDS::SObject_var sobj = what[i];
6384     if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6385     // insert the object to the use case tree
6386     if ( !CORBA::is_nil( objAfter ) )
6387       useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6388     else
6389       useCaseBuilder->AppendTo( where, sobj );        // append to the end of list
6390   }
6391 }
6392
6393 //================================================================================
6394 /*!
6395  * \brief Collect indices of elements, which are located inside the sphere
6396  */
6397 //================================================================================
6398
6399 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6400                                                  SMESH::ElementType     theElemType,
6401                                                  CORBA::Double         theX,
6402                                                  CORBA::Double         theY,
6403                                                  CORBA::Double         theZ,
6404                                                  CORBA::Double         theR)
6405 {
6406   SMESH::long_array_var aResult = new SMESH::long_array();
6407   if ( meshPart->_is_nil() )
6408     return aResult._retn();
6409
6410   // 1. Create geometrical object
6411   gp_Pnt aP( theX, theY, theZ );
6412   TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6413
6414   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6415
6416   if ( lst.size() > 0 ) {
6417     aResult->length( lst.size() );
6418     for ( size_t i = 0; i < lst.size(); i++ ) {
6419       aResult[i] = lst[i];
6420     }
6421   }
6422   return aResult._retn();
6423 }
6424
6425 //================================================================================
6426 /*!
6427  * \brief Collect indices of elements, which are located inside the box
6428  */
6429 //================================================================================
6430
6431 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6432                                               SMESH::ElementType        theElemType,
6433                                               CORBA::Double             theX1,
6434                                               CORBA::Double             theY1,
6435                                               CORBA::Double             theZ1,
6436                                               CORBA::Double             theX2,
6437                                               CORBA::Double             theY2,
6438                                               CORBA::Double             theZ2)
6439 {
6440   SMESH::long_array_var aResult = new SMESH::long_array();
6441   if( meshPart->_is_nil() )
6442     return aResult._retn();
6443
6444   TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6445                                              gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6446
6447   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6448
6449   if( lst.size() > 0 ) {
6450     aResult->length( lst.size() );
6451     for ( size_t i = 0; i < lst.size(); i++ ) {
6452       aResult[i] = lst[i];
6453     }
6454   }
6455   return aResult._retn();
6456 }
6457
6458 //================================================================================
6459 /*!
6460  * \brief Collect indices of elements, which are located inside the cylinder
6461  */
6462 //================================================================================
6463
6464 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6465                                                    SMESH::ElementType        theElemType,
6466                                                    CORBA::Double             theX,
6467                                                    CORBA::Double             theY,
6468                                                    CORBA::Double             theZ,
6469                                                    CORBA::Double             theDX,
6470                                                    CORBA::Double             theDY,
6471                                                    CORBA::Double             theDZ,
6472                                                    CORBA::Double             theH,
6473                                                    CORBA::Double             theR )
6474 {
6475   SMESH::long_array_var aResult = new SMESH::long_array();
6476   if( meshPart->_is_nil() )
6477     return aResult._retn();
6478
6479   gp_Pnt aP( theX, theY, theZ );
6480   gp_Vec aV( theDX, theDY, theDZ );
6481   gp_Ax2 anAxes (aP, aV);
6482
6483   TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6484
6485   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6486
6487   if( lst.size() > 0 ) {
6488     aResult->length( lst.size() );
6489     for ( size_t i = 0; i < lst.size(); i++ ) {
6490       aResult[i] = lst[i];
6491     }
6492   }
6493   return aResult._retn();
6494 }
6495
6496 //================================================================================
6497 /*!
6498  * \brief Collect indices of elements, which are located inside the geom object
6499  */
6500 //================================================================================
6501
6502 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6503                                            SMESH::ElementType        theElemType,
6504                                            GEOM::GEOM_Object_ptr     theGeom,
6505                                            CORBA::Double             theTolerance )
6506 {
6507   SMESH::long_array_var aResult = new SMESH::long_array();
6508   if( meshPart->_is_nil() || theGeom->_is_nil() )
6509     return aResult._retn();
6510
6511   TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6512
6513   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6514
6515   if( lst.size() > 0 ) {
6516     aResult->length( lst.size() );
6517     for ( size_t i = 0; i < lst.size(); i++ ) {
6518       aResult[i] = lst[i];
6519     }
6520   }
6521   return aResult._retn();
6522 }
6523
6524 //================================================================================
6525 /*!
6526  * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6527  */
6528 //================================================================================
6529
6530 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6531                                            SMESH::ElementType        theElemType,
6532                                            const TopoDS_Shape&       theShape,
6533                                            double*                   theTolerance) {
6534
6535   std::vector<long> res;
6536   SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6537
6538   if ( mesh->_is_nil() )
6539     return res;
6540
6541   SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6542   if ( !anImpl )
6543     return res;
6544
6545   const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6546
6547   if ( !meshDS )
6548     return res;
6549
6550   SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6551   SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6552   anElementsOnShape->SetAllNodes( true );
6553   anElementsOnShape->SetMesh( meshDS );
6554   anElementsOnShape->SetShape( theShape, aType );
6555
6556   if(theTolerance)
6557     anElementsOnShape->SetTolerance(*theTolerance);
6558
6559   SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6560   if ( !msource->_is_nil() ) { // Mesh case
6561     SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6562     if ( elemIt ) {
6563       while ( elemIt->more() ) {
6564         const SMDS_MeshElement* anElem = elemIt->next();
6565         long anId = anElem->GetID();
6566         if ( anElementsOnShape->IsSatisfy( anId ) )
6567           res.push_back( anId );
6568       }
6569     }
6570   }
6571   SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6572   if ( !gsource->_is_nil() ) {
6573     if(theElemType == SMESH::NODE) {
6574       SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6575       for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6576         if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6577           long anId = node->GetID();
6578           if ( anElementsOnShape->IsSatisfy( anId ) )
6579             res.push_back( anId );
6580         }
6581       }
6582     } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6583       SMESH::smIdType_array_var elems = gsource->GetListOfID();
6584       for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6585         if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6586           long anId = elem->GetID();
6587           if ( anElementsOnShape->IsSatisfy( anId ) )
6588             res.push_back( anId );
6589         }
6590       }
6591     }
6592   }
6593   SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6594   if ( !smsource->_is_nil() ) {
6595     SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6596     for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6597       const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6598       if (elem) {
6599         long anId = elem->GetID();
6600         if ( anElementsOnShape->IsSatisfy( anId ) )
6601           res.push_back( anId );
6602       }
6603     }
6604   }
6605   return res;
6606 }
6607
6608 //================================================================================
6609 /*!
6610  * \brief Returns true if algorithm can be used to mesh a given geometry
6611  *  \param [in] theAlgoType - the algorithm type
6612  *  \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6613  *  \param [in] theGeomObject - the geometry to mesh
6614  *  \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6615  *         else, returns \c True if at least one shape is meshable
6616  *  \return CORBA::Boolean - can or can't
6617  */
6618 //================================================================================
6619
6620 #undef SMY_OWN_CATCH
6621 #define SMY_OWN_CATCH // prevent re-throwing SALOME::SALOME_Exception in IsApplicable()
6622
6623 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char*           theAlgoType,
6624                                            const char*           theLibName,
6625                                            GEOM::GEOM_Object_ptr theGeomObject,
6626                                            CORBA::Boolean        toCheckAll)
6627 {
6628   SMESH_TRY;
6629
6630   std::string aPlatformLibName;
6631   GenericHypothesisCreator_i* aCreator =
6632     getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6633   if (aCreator)
6634   {
6635     TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6636     const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6637     return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6638   }
6639   else
6640   {
6641     return false;
6642   }
6643
6644   SMESH_CATCH( SMESH::doNothing );
6645
6646   MESSAGE("SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : ""));
6647   return true;
6648 }