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