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