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