Salome HOME
regression with bos #24400 [CEA] Option in SALOME for not storing in med files the...
[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
2711       // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2712       static_assert( sizeof(typeNames) / sizeof(const char*) ==SMESH::NB_ELEMENT_TYPES,
2713                      "Update names of ElementType's!!!" );
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 writer;
4210   writer.SetFile( meshfile.ToCString() );
4211   //writer.SetSaveNumbers( false ); // bos #24400 -- it leads to change of element IDs
4212
4213   // IMP issue 20918
4214   // SetStoreName() to groups before storing hypotheses to let them refer to
4215   // groups using "store name", which is "Group <group_persistent_id>"
4216   {
4217     SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4218     for ( ; itBig->More(); itBig->Next() ) {
4219       SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4220       if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4221         CORBA::Object_var anObject = SObjectToObject( gotBranch );
4222         if ( !CORBA::is_nil( anObject ) ) {
4223           SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4224           if ( !myMesh->_is_nil() ) {
4225             myMesh->Load(); // load from study file if not yet done
4226             TPythonDump pd(this); // not to dump GetGroups()
4227             SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4228             for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4229             {
4230               SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4231               if ( grImpl )
4232               {
4233                 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4234                 int anId = myStudyContext->findId( string( objStr.in() ) );
4235                 char grpName[ 30 ];
4236                 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4237                 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4238                 aGrpBaseDS->SetStoreName( grpName );
4239               }
4240             }
4241           }
4242         }
4243       }
4244     }
4245   }
4246
4247   // Write data
4248   // ---> create HDF file
4249   aFile = new HDFfile( (char*) filename.ToCString() );
4250   aFile->CreateOnDisk();
4251
4252   // --> iterator for top-level objects
4253   SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4254   for ( ; itBig->More(); itBig->Next() ) {
4255     SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4256
4257     // --> hypotheses root branch (only one for the study)
4258     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4259       // create hypotheses root HDF group
4260       aTopGroup = new HDFgroup( "Hypotheses", aFile );
4261       aTopGroup->CreateOnDisk();
4262
4263       // iterator for all hypotheses
4264       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4265       for ( ; it->More(); it->Next() ) {
4266         SALOMEDS::SObject_wrap mySObject = it->Value();
4267         CORBA::Object_var anObject = SObjectToObject( mySObject );
4268         if ( !CORBA::is_nil( anObject ) ) {
4269           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4270           if ( !myHyp->_is_nil() ) {
4271             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4272             if ( myImpl ) {
4273               CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4274               std::string hypname = hn.in();
4275               std::string libname = ln.in();
4276               // BUG SWP13062
4277               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4278               // WIN32 and ".so" for X-system) must be deleted
4279               int libname_len = libname.length();
4280 #ifdef WIN32
4281               if( libname_len > 4 )
4282                 libname.resize( libname_len - 4 );
4283 #else
4284               // PAL17753 (Regression: missing hypothesis in restored study)
4285               // "lib" also should be removed from the beginning
4286               if( libname_len > 6 )
4287                 libname = libname.substr( 3, libname_len - 3 - 3 );
4288 #endif
4289               CORBA::String_var  objStr = GetORB()->object_to_string( anObject );
4290               CORBA::String_var hypdata = myImpl->SaveTo();
4291               int                    id = myStudyContext->findId( string( objStr.in() ));
4292
4293               // for each hypothesis create HDF group basing on its id
4294               char hypGrpName[30];
4295               sprintf( hypGrpName, "Hypothesis %d", id );
4296               aGroup = new HDFgroup( hypGrpName, aTopGroup );
4297               aGroup->CreateOnDisk();
4298               // --> type name of hypothesis
4299               aSize[ 0 ] = hypname.length() + 1;
4300               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4301               aDataset->CreateOnDisk();
4302               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4303               aDataset->CloseOnDisk();
4304               // --> server plugin library name of hypothesis
4305               aSize[ 0 ] = libname.length() + 1;
4306               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4307               aDataset->CreateOnDisk();
4308               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4309               aDataset->CloseOnDisk();
4310               // --> persistent data of hypothesis
4311               aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4312               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4313               aDataset->CreateOnDisk();
4314               aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4315               aDataset->CloseOnDisk();
4316               // close hypothesis HDF group
4317               aGroup->CloseOnDisk();
4318             }
4319           }
4320         }
4321       }
4322       // close hypotheses root HDF group
4323       aTopGroup->CloseOnDisk();
4324     }
4325     // --> algorithms root branch (only one for the study)
4326     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4327       // create algorithms root HDF group
4328       aTopGroup = new HDFgroup( "Algorithms", aFile );
4329       aTopGroup->CreateOnDisk();
4330
4331       // iterator for all algorithms
4332       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4333       for ( ; it->More(); it->Next() ) {
4334         SALOMEDS::SObject_wrap mySObject = it->Value();
4335         CORBA::Object_var anObject = SObjectToObject( mySObject );
4336         if ( !CORBA::is_nil( anObject ) ) {
4337           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4338           if ( !myHyp->_is_nil() ) {
4339             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4340             if ( myImpl ) {
4341               CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4342               std::string hypname = hn.in();
4343               std::string libname = ln.in();
4344               // BUG SWP13062
4345               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4346               // WIN32 and ".so" for X-system) must be deleted
4347               int libname_len = libname.length();
4348 #ifdef WIN32
4349               if( libname_len > 4 )
4350                 libname.resize( libname_len - 4 );
4351 #else
4352               // PAL17753 (Regression: missing hypothesis in restored study)
4353               // "lib" also should be removed from the beginning
4354               if( libname_len > 6 )
4355                 libname = libname.substr( 3, libname_len - 3 - 3 );
4356 #endif
4357               CORBA::String_var  objStr = GetORB()->object_to_string( anObject );
4358               CORBA::String_var hypdata = myImpl->SaveTo();
4359               int                    id = myStudyContext->findId( string( objStr.in() ) );
4360
4361               // for each algorithm create HDF group basing on its id
4362               char hypGrpName[30];
4363               sprintf( hypGrpName, "Algorithm %d", id );
4364               aGroup = new HDFgroup( hypGrpName, aTopGroup );
4365               aGroup->CreateOnDisk();
4366               // --> type name of algorithm
4367               aSize[0] = hypname.length() + 1;
4368               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4369               aDataset->CreateOnDisk();
4370               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4371               aDataset->CloseOnDisk();
4372               // --> server plugin library name of hypothesis
4373               aSize[0] = libname.length() + 1;
4374               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4375               aDataset->CreateOnDisk();
4376               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4377               aDataset->CloseOnDisk();
4378               // --> persistent data of algorithm
4379               aSize[0] = strlen( hypdata.in() ) + 1;
4380               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4381               aDataset->CreateOnDisk();
4382               aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4383               aDataset->CloseOnDisk();
4384               // close algorithm HDF group
4385               aGroup->CloseOnDisk();
4386             }
4387           }
4388         }
4389       }
4390       // close algorithms root HDF group
4391       aTopGroup->CloseOnDisk();
4392     }
4393     // --> mesh objects roots branches
4394     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4395       CORBA::Object_var anObject = SObjectToObject( gotBranch );
4396       if ( !CORBA::is_nil( anObject ) ) {
4397         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4398         if ( !myMesh->_is_nil() ) {
4399           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4400           if ( myImpl ) {
4401             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4402             int id = myStudyContext->findId( string( objStr.in() ) );
4403             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4404             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4405             bool hasShape = myLocMesh.HasShapeToMesh();
4406
4407             // for each mesh open the HDF group basing on its id
4408             char meshGrpName[ 30 ];
4409             sprintf( meshGrpName, "Mesh %d", id );
4410             aTopGroup = new HDFgroup( meshGrpName, aFile );
4411             aTopGroup->CreateOnDisk();
4412
4413             // --> put dataset to hdf file which is a flag that mesh has data
4414             string strHasData = "0";
4415             // check if the mesh is not empty
4416             if ( mySMESHDSMesh->NbNodes() > 0 ) {
4417               // write mesh data to med file
4418               writer.SetMesh( mySMESHDSMesh );
4419               writer.SetMeshId( id );
4420               strHasData = "1";
4421             }
4422             aSize[ 0 ] = strHasData.length() + 1;
4423             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4424             aDataset->CreateOnDisk();
4425             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4426             aDataset->CloseOnDisk();
4427
4428             // ouv : NPAL12872
4429             // for each mesh open the HDF group basing on its auto color parameter
4430             char meshAutoColorName[ 30 ];
4431             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4432             int anAutoColor[1];
4433             anAutoColor[0] = myImpl->GetAutoColor();
4434             aSize[ 0 ] = 1;
4435             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4436             aDataset->CreateOnDisk();
4437             aDataset->WriteOnDisk( anAutoColor );
4438             aDataset->CloseOnDisk();
4439
4440             // issue 0020693. Store _isModified flag
4441             int isModified = myLocMesh.GetIsModified();
4442             aSize[ 0 ] = 1;
4443             aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4444             aDataset->CreateOnDisk();
4445             aDataset->WriteOnDisk( &isModified );
4446             aDataset->CloseOnDisk();
4447
4448             // issue 20918. Store Persistent Id of SMESHDS_Mesh
4449             int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4450             aSize[ 0 ] = 1;
4451             aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4452             aDataset->CreateOnDisk();
4453             aDataset->WriteOnDisk( &meshPersistentId );
4454             aDataset->CloseOnDisk();
4455
4456             // Store SMESH_Mesh_i::_mainShapeTick
4457             int shapeTick = myImpl->MainShapeTick();
4458             aSize[ 0 ] = 1;
4459             aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4460             aDataset->CreateOnDisk();
4461             aDataset->WriteOnDisk( &shapeTick );
4462             aDataset->CloseOnDisk();
4463
4464             // write reference on a shape if exists
4465             SALOMEDS::SObject_wrap myRef;
4466             bool shapeRefFound = false;
4467             bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4468             if ( found ) {
4469               SALOMEDS::SObject_wrap myShape;
4470               bool ok = myRef->ReferencedObject( myShape.inout() );
4471               if ( ok ) {
4472                 CORBA::Object_var shapeObj = myShape->GetObject();
4473                 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4474                 CORBA::String_var myRefOnObject = myShape->GetID();
4475                 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4476                   aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4477                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4478                   aDataset->CreateOnDisk();
4479                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4480                   aDataset->CloseOnDisk();
4481                 }
4482               }
4483             }
4484
4485             // Store file info
4486             std::string info = myImpl->FileInfoToString();
4487             if ( !info.empty() )
4488             {
4489               aSize[ 0 ] = info.size();
4490               aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4491               aDataset->CreateOnDisk();
4492               aDataset->WriteOnDisk( (char*) info.data() );
4493               aDataset->CloseOnDisk();
4494             }
4495
4496             // write applied hypotheses if exist
4497             SALOMEDS::SObject_wrap myHypBranch;
4498             found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4499             if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4500               aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4501             }
4502             if ( found && (shapeRefFound || !hasShape) ) {
4503               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4504               aGroup->CreateOnDisk();
4505
4506               SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4507               int hypNb = 0;
4508               for ( ; it->More(); it->Next() ) {
4509                 SALOMEDS::SObject_wrap mySObject = it->Value();
4510                 SALOMEDS::SObject_wrap myRefOnHyp;
4511                 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4512                 if ( ok ) {
4513                   // san - it is impossible to recover applied hypotheses
4514                   //       using their entries within Load() method,
4515                   // for there are no AttributeIORs in the study when Load() is working.
4516                   // Hence, it is better to store persistent IDs of hypotheses as references to them
4517
4518                   //string myRefOnObject = myRefOnHyp->GetID();
4519                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4520                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4521                   int id = myStudyContext->findId( string( objStr.in() ) );
4522                   //if ( myRefOnObject.length() > 0 ) {
4523                   //aSize[ 0 ] = myRefOnObject.length() + 1;
4524                   char hypName[ 30 ], hypId[ 30 ];
4525                   sprintf( hypName, "Hyp %d", ++hypNb );
4526                   sprintf( hypId, "%d", id );
4527                   aSize[ 0 ] = strlen( hypId ) + 1;
4528                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4529                   aDataset->CreateOnDisk();
4530                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4531                   aDataset->WriteOnDisk( hypId );
4532                   aDataset->CloseOnDisk();
4533                   //}
4534                 }
4535               }
4536               aGroup->CloseOnDisk();
4537             }
4538
4539             // write applied algorithms if exist
4540             SALOMEDS::SObject_wrap myAlgoBranch;
4541             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4542                                               myAlgoBranch.inout() );
4543             if ( found && !shapeRefFound && hasShape) { // remove applied algos
4544               aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4545             }
4546             if ( found && (shapeRefFound || !hasShape)) {
4547               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4548               aGroup->CreateOnDisk();
4549
4550               SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4551               int algoNb = 0;
4552               for ( ; it->More(); it->Next() ) {
4553                 SALOMEDS::SObject_wrap mySObject = it->Value();
4554                 SALOMEDS::SObject_wrap myRefOnAlgo;
4555                 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4556                 if ( ok ) {
4557                   // san - it is impossible to recover applied algorithms
4558                   //       using their entries within Load() method,
4559                   // for there are no AttributeIORs in the study when Load() is working.
4560                   // Hence, it is better to store persistent IDs of algorithms as references to them
4561
4562                   //string myRefOnObject = myRefOnAlgo->GetID();
4563                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4564                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4565                   int id = myStudyContext->findId( string( objStr.in() ) );
4566                   //if ( myRefOnObject.length() > 0 ) {
4567                   //aSize[ 0 ] = myRefOnObject.length() + 1;
4568                   char algoName[ 30 ], algoId[ 30 ];
4569                   sprintf( algoName, "Algo %d", ++algoNb );
4570                   sprintf( algoId, "%d", id );
4571                   aSize[ 0 ] = strlen( algoId ) + 1;
4572                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4573                   aDataset->CreateOnDisk();
4574                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4575                   aDataset->WriteOnDisk( algoId );
4576                   aDataset->CloseOnDisk();
4577                   //}
4578                 }
4579               }
4580               aGroup->CloseOnDisk();
4581             }
4582
4583             // --> submesh objects sub-branches
4584
4585             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4586               SALOMEDS::SObject_wrap mySubmeshBranch;
4587               found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4588
4589               if ( found ) // check if there is shape reference in submeshes
4590               {
4591                 bool hasShapeRef = false;
4592                 SALOMEDS::ChildIterator_wrap itSM =
4593                   aStudy->NewChildIterator( mySubmeshBranch );
4594                 for ( ; itSM->More(); itSM->Next() ) {
4595                   SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4596                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4597                     mySubRef->ReferencedObject( myShape.inout() );
4598                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4599                     hasShapeRef = true;
4600                   else
4601                   { // remove one submesh
4602                     if ( shapeRefFound )
4603                     { // unassign hypothesis
4604                       SMESH::SMESH_subMesh_var mySubMesh =
4605                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4606                       if ( !mySubMesh->_is_nil() ) {
4607                         int shapeID = mySubMesh->GetId();
4608                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4609                         const list<const SMESHDS_Hypothesis*>& hypList =
4610                           mySMESHDSMesh->GetHypothesis( S );
4611                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4612                         while ( hyp != hypList.end() ) {
4613                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
4614                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4615                         }
4616                       }
4617                     }
4618                     aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4619                   }
4620                 } // loop on submeshes of a type
4621                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4622                   aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4623                   found = false;
4624                 }
4625               }  // end check if there is shape reference in submeshes
4626               if ( found ) {
4627                 char name_meshgroup[ 30 ];
4628                 if ( i == GetSubMeshOnVertexTag() )
4629                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
4630                 else if ( i == GetSubMeshOnEdgeTag() )
4631                   strcpy( name_meshgroup, "SubMeshes On Edge" );
4632                 else if ( i == GetSubMeshOnWireTag() )
4633                   strcpy( name_meshgroup, "SubMeshes On Wire" );
4634                 else if ( i == GetSubMeshOnFaceTag() )
4635                   strcpy( name_meshgroup, "SubMeshes On Face" );
4636                 else if ( i == GetSubMeshOnShellTag() )
4637                   strcpy( name_meshgroup, "SubMeshes On Shell" );
4638                 else if ( i == GetSubMeshOnSolidTag() )
4639                   strcpy( name_meshgroup, "SubMeshes On Solid" );
4640                 else if ( i == GetSubMeshOnCompoundTag() )
4641                   strcpy( name_meshgroup, "SubMeshes On Compound" );
4642
4643                 // for each type of submeshes create container HDF group
4644                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4645                 aGroup->CreateOnDisk();
4646
4647                 // iterator for all submeshes of given type
4648                 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4649                 for ( ; itSM->More(); itSM->Next() ) {
4650                   SALOMEDS::SObject_wrap mySObject = itSM->Value();
4651                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4652                   if ( !CORBA::is_nil( anSubObject ))
4653                   {
4654                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4655                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4656                     int subid = myStudyContext->findId( string( objStr.in() ) );
4657
4658                     // for each mesh open the HDF group basing on its id
4659                     char submeshGrpName[ 30 ];
4660                     sprintf( submeshGrpName, "SubMesh %d", subid );
4661                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4662                     aSubGroup->CreateOnDisk();
4663
4664                     // write reference on a shape, already checked if it exists
4665                     SALOMEDS::SObject_wrap mySubRef, myShape;
4666                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4667                       mySubRef->ReferencedObject( myShape.inout() );
4668                     string myRefOnObject = myShape->GetID();
4669                     if ( myRefOnObject.length() > 0 ) {
4670                       aSize[ 0 ] = myRefOnObject.length() + 1;
4671                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4672                       aDataset->CreateOnDisk();
4673                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4674                       aDataset->CloseOnDisk();
4675                     }
4676
4677                     // write applied hypotheses if exist
4678                     SALOMEDS::SObject_wrap mySubHypBranch;
4679                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4680                                                       mySubHypBranch.inout() );
4681                     if ( found ) {
4682                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4683                       aSubSubGroup->CreateOnDisk();
4684
4685                       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4686                       int hypNb = 0;
4687                       for ( ; it->More(); it->Next() ) {
4688                         SALOMEDS::SObject_wrap mySubSObject = it->Value();
4689                         SALOMEDS::SObject_wrap myRefOnHyp;
4690                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4691                         if ( ok ) {
4692                           //string myRefOnObject = myRefOnHyp->GetID();
4693                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4694                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4695                           int id = myStudyContext->findId( string( objStr.in() ) );
4696                           //if ( myRefOnObject.length() > 0 ) {
4697                           //aSize[ 0 ] = myRefOnObject.length() + 1;
4698                           char hypName[ 30 ], hypId[ 30 ];
4699                           sprintf( hypName, "Hyp %d", ++hypNb );
4700                           sprintf( hypId, "%d", id );
4701                           aSize[ 0 ] = strlen( hypId ) + 1;
4702                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4703                           aDataset->CreateOnDisk();
4704                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4705                           aDataset->WriteOnDisk( hypId );
4706                           aDataset->CloseOnDisk();
4707                           //}
4708                         }
4709                       }
4710                       aSubSubGroup->CloseOnDisk();
4711                     }
4712
4713                     // write applied algorithms if exist
4714                     SALOMEDS::SObject_wrap mySubAlgoBranch;
4715                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4716                                                       mySubAlgoBranch.inout() );
4717                     if ( found ) {
4718                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4719                       aSubSubGroup->CreateOnDisk();
4720
4721                       SALOMEDS::ChildIterator_wrap it =
4722                         aStudy->NewChildIterator( mySubAlgoBranch );
4723                       int algoNb = 0;
4724                       for ( ; it->More(); it->Next() ) {
4725                         SALOMEDS::SObject_wrap mySubSObject = it->Value();
4726                         SALOMEDS::SObject_wrap myRefOnAlgo;
4727                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4728                         if ( ok ) {
4729                           //string myRefOnObject = myRefOnAlgo->GetID();
4730                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4731                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4732                           int id = myStudyContext->findId( string( objStr.in() ) );
4733                           //if ( myRefOnObject.length() > 0 ) {
4734                           //aSize[ 0 ] = myRefOnObject.length() + 1;
4735                           char algoName[ 30 ], algoId[ 30 ];
4736                           sprintf( algoName, "Algo %d", ++algoNb );
4737                           sprintf( algoId, "%d", id );
4738                           aSize[ 0 ] = strlen( algoId ) + 1;
4739                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4740                           aDataset->CreateOnDisk();
4741                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4742                           aDataset->WriteOnDisk( algoId );
4743                           aDataset->CloseOnDisk();
4744                           //}
4745                         }
4746                       }
4747                       aSubSubGroup->CloseOnDisk();
4748                     }
4749                     // close submesh HDF group
4750                     aSubGroup->CloseOnDisk();
4751                   }
4752                 }
4753                 // close container of submeshes by type HDF group
4754                 aGroup->CloseOnDisk();
4755               }
4756             }
4757
4758             // store submesh order if any
4759             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4760             const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4761             if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4762               char order_list[ 30 ];
4763               strcpy( order_list, "Mesh Order" );
4764               // count number of submesh ids
4765               int nbIDs = 0;
4766               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4767               for ( ; idIt != theOrderIds.end(); idIt++ )
4768                 nbIDs += (*idIt).size();
4769               // number of values = number of IDs +
4770               //                    number of lists (for separators) - 1
4771               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4772               idIt = theOrderIds.begin();
4773               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4774                 const TListOfInt& idList = *idIt;
4775                 if (idIt != theOrderIds.begin()) // not first list
4776                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4777                 // dump submesh ids from current list
4778                 TListOfInt::const_iterator id_smId = idList.begin();
4779                 for( ; id_smId != idList.end(); id_smId++ )
4780                   smIDs[ i++ ] = *id_smId;
4781               }
4782               // write HDF group
4783               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4784
4785               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4786               aDataset->CreateOnDisk();
4787               aDataset->WriteOnDisk( smIDs );
4788               aDataset->CloseOnDisk();
4789               //
4790               delete[] smIDs;
4791             }
4792             if ( !theOrderIds.empty() && isNewOrederVersion )
4793             {
4794               // convert ids to entries
4795               std::list< std::list< std::string > > orderEntryLists;
4796               for ( const TListOfInt& idList : theOrderIds )
4797               {
4798                 orderEntryLists.emplace_back();
4799                 std::list< std::string > & entryList = orderEntryLists.back();
4800                 for ( const int& id : idList )
4801                 {
4802                   const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4803                   GEOM::GEOM_Object_var  go = ShapeToGeomObject( shape );
4804                   SALOMEDS::SObject_var  so = ObjectToSObject( go );
4805                   if ( !so->_is_nil() )
4806                   {
4807                     CORBA::String_var entry = so->GetID();
4808                     entryList.emplace_back( entry.in() );
4809                   }
4810                 }
4811               }
4812               // convert orderEntryLists to string
4813               std::ostringstream ostream;
4814               boost::archive::text_oarchive( ostream ) << orderEntryLists;
4815               std::string orderEntryString = ostream.str();
4816
4817               // write HDF group
4818               aSize[ 0 ] = orderEntryString.size() + 1;
4819               aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4820               aDataset->CreateOnDisk();
4821               aDataset->WriteOnDisk((char*) orderEntryString.data() );
4822               aDataset->CloseOnDisk();
4823             }
4824
4825             // groups root sub-branch
4826             SALOMEDS::SObject_wrap myGroupsBranch;
4827             for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4828               found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4829               if ( found ) {
4830                 char name_group[ 30 ];
4831                 if ( i == GetNodeGroupsTag() )
4832                   strcpy( name_group, "Groups of Nodes" );
4833                 else if ( i == GetEdgeGroupsTag() )
4834                   strcpy( name_group, "Groups of Edges" );
4835                 else if ( i == GetFaceGroupsTag() )
4836                   strcpy( name_group, "Groups of Faces" );
4837                 else if ( i == GetVolumeGroupsTag() )
4838                   strcpy( name_group, "Groups of Volumes" );
4839                 else if ( i == Get0DElementsGroupsTag() )
4840                   strcpy( name_group, "Groups of 0D Elements" );
4841                 else if ( i == GetBallElementsGroupsTag() )
4842                   strcpy( name_group, "Groups of Balls" );
4843
4844                 aGroup = new HDFgroup( name_group, aTopGroup );
4845                 aGroup->CreateOnDisk();
4846
4847                 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4848                 for ( ; it->More(); it->Next() ) {
4849                   SALOMEDS::SObject_wrap mySObject = it->Value();
4850                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4851                   if ( !CORBA::is_nil( aSubObject ) ) {
4852                     SMESH_GroupBase_i* myGroupImpl =
4853                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4854                     if ( !myGroupImpl )
4855                       continue;
4856                     SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4857                     if ( !aGrpBaseDS )
4858                       continue;
4859
4860                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4861                     int anId = myStudyContext->findId( string( objStr.in() ) );
4862
4863                     // For each group, create a dataset named "Group <group_persistent_id>"
4864                     // and store the group's user name into it
4865                     const char*         grpName = aGrpBaseDS->GetStoreName();
4866                     CORBA::String_var aUserName = myGroupImpl->GetName();
4867                     aSize[ 0 ] = strlen( aUserName ) + 1;
4868
4869                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4870                     aDataset->CreateOnDisk();
4871                     aDataset->WriteOnDisk( aUserName );
4872                     aDataset->CloseOnDisk();
4873
4874                     // ouv : NPAL12872
4875                     // For each group, create a dataset named "Group <group_persistent_id> Color"
4876                     // and store the group's color into it
4877                     char grpColorName[ 30 ];
4878                     sprintf( grpColorName, "ColorGroup %d", anId );
4879                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
4880                     double anRGB[3];
4881                     anRGB[ 0 ] = aColor.R;
4882                     anRGB[ 1 ] = aColor.G;
4883                     anRGB[ 2 ] = aColor.B;
4884                     aSize[ 0 ] = 3;
4885                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4886                     aDataset->CreateOnDisk();
4887                     aDataset->WriteOnDisk( anRGB );
4888                     aDataset->CloseOnDisk();
4889
4890                     // Pass SMESHDS_Group to MED writer
4891                     SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4892                     if ( aGrpDS )
4893                       writer.AddGroup( aGrpDS );
4894
4895                     // write reference on a shape if exists
4896                     SMESHDS_GroupOnGeom* aGeomGrp =
4897                       dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4898                     if ( aGeomGrp ) {
4899                       SALOMEDS::SObject_wrap mySubRef, myShape;
4900                       if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4901                           mySubRef->ReferencedObject( myShape.inout() ) &&
4902                           !CORBA::is_nil( myShape->GetObject() ))
4903                       {
4904                         CORBA::String_var myRefOnObject = myShape->GetID();
4905                         if ( myRefOnObject.in()[0] ) {
4906                           char aRefName[ 30 ];
4907                           sprintf( aRefName, "Ref on shape %d", anId);
4908                           aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4909                           aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4910                           aDataset->CreateOnDisk();
4911                           aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4912                           aDataset->CloseOnDisk();
4913                         }
4914                       }
4915                       else // shape ref is invalid:
4916                       {
4917                         // save a group on geometry as ordinary group
4918                         writer.AddGroup( aGeomGrp );
4919                       }
4920                     }
4921                     else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4922                               dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4923                     {
4924                       std::string str = aFilterGrp_i->FilterToString();
4925                       std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4926                       aSize[ 0 ] = str.length() + 1;
4927                       aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4928                       aDataset->CreateOnDisk();
4929                       aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4930                       aDataset->CloseOnDisk();
4931                     }
4932                   }
4933                 }
4934                 aGroup->CloseOnDisk();
4935               }
4936             } // loop on groups
4937
4938             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4939             {
4940               // Flush current mesh information into MED file
4941               writer.Perform();
4942
4943               // save info on nb of elements
4944               SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4945
4946               // maybe a shape was deleted in the study
4947               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4948                 TopoDS_Shape nullShape;
4949                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4950               }
4951
4952               SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4953               if ( smIt->more() )
4954               {
4955                 // Store submeshes
4956                 // ----------------
4957                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4958                 aGroup->CreateOnDisk();
4959
4960                 // each element belongs to one or none submesh,
4961                 // so for each node/element, we store a submesh ID
4962
4963                 // Store submesh IDs
4964                 for ( int isNode = 0; isNode < 2; ++isNode )
4965                 {
4966                   SMDS_ElemIteratorPtr eIt =
4967                     mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4968                   smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4969                   if ( nbElems < 1 )
4970                     continue;
4971                   std::vector<int> smIDs; smIDs.reserve( nbElems );
4972                   while ( eIt->more() )
4973                     if ( const SMDS_MeshElement* e = eIt->next())
4974                       smIDs.push_back( e->getshapeId() );
4975                   // write HDF group
4976                   aSize[ 0 ] = nbElems;
4977                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4978                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4979                   aDataset->CreateOnDisk();
4980                   aDataset->WriteOnDisk( & smIDs[0] );
4981                   aDataset->CloseOnDisk();
4982                 }
4983
4984                 aGroup->CloseOnDisk();
4985
4986                 // Store node positions on sub-shapes (SMDS_Position):
4987                 // ----------------------------------------------------
4988
4989                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4990                 aGroup->CreateOnDisk();
4991
4992                 // in aGroup, create 5 datasets to contain:
4993                 // "Nodes on Edges" - ID of node on edge
4994                 // "Edge positions" - U parameter on node on edge
4995                 // "Nodes on Faces" - ID of node on face
4996                 // "Face U positions" - U parameter of node on face
4997                 // "Face V positions" - V parameter of node on face
4998
4999                 // Find out nb of nodes on edges and faces
5000                 // Collect corresponding sub-meshes
5001                 int nbEdgeNodes = 0, nbFaceNodes = 0;
5002                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5003                 // loop on SMESHDS_SubMesh'es
5004                 while ( smIt->more() )
5005                 {
5006                   SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5007                   if ( aSubMesh->IsComplexSubmesh() )
5008                     continue; // submesh containing other submeshs
5009                   smIdType nbNodes = aSubMesh->NbNodes();
5010                   if ( nbNodes == 0 ) continue;
5011
5012                   int aShapeID = aSubMesh->GetID();
5013                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5014                     continue;
5015                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5016                   // write only SMDS_FacePosition and SMDS_EdgePosition
5017                   switch ( aShapeType ) {
5018                   case TopAbs_FACE:
5019                     nbFaceNodes += nbNodes;
5020                     aFaceSM.push_back( aSubMesh );
5021                     break;
5022                   case TopAbs_EDGE:
5023                     nbEdgeNodes += nbNodes;
5024                     aEdgeSM.push_back( aSubMesh );
5025                     break;
5026                   default:
5027                     continue;
5028                   }
5029                 }
5030                 // Treat positions on edges or faces
5031                 for ( int onFace = 0; onFace < 2; onFace++ )
5032                 {
5033                   // Create arrays to store in datasets
5034                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5035                   if (!nbNodes) continue;
5036                   int* aNodeIDs = new int [ nbNodes ];
5037                   double* aUPos = new double [ nbNodes ];
5038                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5039
5040                   // Fill arrays
5041                   // loop on sub-meshes
5042                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5043                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5044                   for ( ; itSM != pListSM->end(); itSM++ )
5045                   {
5046                     SMESHDS_SubMesh* aSubMesh = (*itSM);
5047
5048                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5049                     // loop on nodes in aSubMesh
5050                     while ( itNode->more() )
5051                     {
5052                       //node ID
5053                       const SMDS_MeshNode* node = itNode->next();
5054                       aNodeIDs [ iNode ] = node->GetID();
5055
5056                       // Position
5057                       const SMDS_PositionPtr pos = node->GetPosition();
5058                       if ( onFace ) { // on FACE
5059                         SMDS_FacePositionPtr fPos = pos;
5060                         if ( fPos ) {
5061                           aUPos[ iNode ] = fPos->GetUParameter();
5062                           aVPos[ iNode ] = fPos->GetVParameter();
5063                           iNode++;
5064                         }
5065                         else
5066                           nbNodes--;
5067                       }
5068                       else { // on EDGE
5069                         SMDS_EdgePositionPtr ePos = pos;
5070                         if ( ePos ) {
5071                           aUPos[ iNode ] = ePos->GetUParameter();
5072                           iNode++;
5073                         }
5074                         else
5075                           nbNodes--;
5076                       }
5077                     } // loop on nodes in aSubMesh
5078                   } // loop on sub-meshes
5079
5080                   // Write datasets
5081                   if ( nbNodes )
5082                   {
5083                     aSize[ 0 ] = nbNodes;
5084                     // IDS
5085                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5086                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5087                     aDataset->CreateOnDisk();
5088                     aDataset->WriteOnDisk( aNodeIDs );
5089                     aDataset->CloseOnDisk();
5090
5091                     // U Positions
5092                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
5093                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5094                     aDataset->CreateOnDisk();
5095                     aDataset->WriteOnDisk( aUPos );
5096                     aDataset->CloseOnDisk();
5097                     // V Positions
5098                     if ( onFace ) {
5099                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5100                       aDataset->CreateOnDisk();
5101                       aDataset->WriteOnDisk( aVPos );
5102                       aDataset->CloseOnDisk();
5103                     }
5104                   }
5105                   delete [] aNodeIDs;
5106                   delete [] aUPos;
5107                   if ( aVPos ) delete [] aVPos;
5108
5109                 } // treat positions on edges or faces
5110
5111                 // close "Node Positions" group
5112                 aGroup->CloseOnDisk();
5113
5114               } // if ( there are submeshes in SMESHDS_Mesh )
5115             } // if ( hasData )
5116
5117             // close mesh HDF group
5118             aTopGroup->CloseOnDisk();
5119           }
5120         }
5121       }
5122     }
5123   }
5124
5125   // close HDF file
5126   aFile->CloseOnDisk();
5127   delete aFile;
5128
5129   // Convert temporary files to stream
5130   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5131
5132   // Remove temporary files and directory
5133   if ( !isMultiFile )
5134     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5135
5136   return aStreamFile._retn();
5137 }
5138
5139 //=============================================================================
5140 /*!
5141  *  SMESH_Gen_i::SaveASCII
5142  *
5143  *  Save SMESH module's data in ASCII format
5144  */
5145 //=============================================================================
5146
5147 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5148                                            const char*              theURL,
5149                                            bool                     isMultiFile ) {
5150   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5151   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5152   return aStreamFile._retn();
5153
5154   //after usual saving needs to encipher binary to text string
5155   //Any binary symbol will be represent as "|xx" () hexadecimal format number
5156   int size = aStreamFile.in().length();
5157   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5158   for ( int i = 0; i < size; i++ )
5159     sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5160
5161   buffer[size * 3] = '\0';
5162
5163   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5164
5165   return anAsciiStreamFile._retn();
5166 }
5167
5168 //=============================================================================
5169 /*!
5170  *  SMESH_Gen_i::Load
5171  *
5172  *  Load SMESH module's data
5173  */
5174 //=============================================================================
5175
5176 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5177                         const SALOMEDS::TMPFile& theStream,
5178                         const char*              theURL,
5179                         bool                     isMultiFile )
5180 {
5181   UpdateStudy(); // load geom data
5182   Kernel_Utils::Localizer loc;
5183
5184   SALOMEDS::Study_var aStudy = getStudyServant();
5185
5186   // Get temporary files location
5187   TCollection_AsciiString tmpDir =
5188     ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5189
5190   // Convert the stream into sequence of files to process
5191   SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5192                                                                          tmpDir.ToCString(),
5193                                                                          isMultiFile );
5194   TCollection_AsciiString aStudyName( "" );
5195   if ( isMultiFile ) {
5196     CORBA::WString_var url = aStudy->URL();
5197     aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5198   }
5199   // Set names of temporary files
5200   TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5201   TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5202
5203   int size;
5204   HDFfile*    aFile;
5205   HDFdataset* aDataset;
5206   HDFgroup*   aTopGroup;
5207   HDFgroup*   aGroup;
5208   HDFgroup*   aSubGroup;
5209   HDFgroup*   aSubSubGroup;
5210
5211   // Read data
5212   // ---> open HDF file
5213   aFile = new HDFfile( (char*) filename.ToCString() );
5214   try {
5215     aFile->OpenOnDisk( HDF_RDONLY );
5216   }
5217   catch ( HDFexception ) {
5218     INFOS( "Load(): " << filename << " not found!" );
5219     return false;
5220   }
5221
5222   TPythonDump pd(this); // prevent dump during loading
5223
5224   // For PAL13473 ("Repetitive mesh") implementation.
5225   // New dependencies between SMESH objects are established:
5226   // now hypotheses can refer to meshes, shapes and other hypotheses.
5227   // To keep data consistent, the following order of data restoration
5228   // imposed:
5229   // 1. Create hypotheses
5230   // 2. Create all meshes
5231   // 3. Load hypotheses' data
5232   // 4. All the rest
5233
5234   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
5235   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
5236   list< SMESH::Filter_var >                      filters;
5237
5238   // get total number of top-level groups
5239   int aNbGroups = aFile->nInternalObjects();
5240   if ( aNbGroups > 0 ) {
5241     // --> in first turn we should read&create hypotheses
5242     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5243       // open hypotheses root HDF group
5244       aTopGroup = new HDFgroup( "Hypotheses", aFile );
5245       aTopGroup->OpenOnDisk();
5246
5247       // get number of hypotheses
5248       int aNbObjects = aTopGroup->nInternalObjects();
5249       for ( int j = 0; j < aNbObjects; j++ ) {
5250         // try to identify hypothesis
5251         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5252         aTopGroup->InternalObjectIndentify( j, hypGrpName );
5253
5254         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5255           // open hypothesis group
5256           aGroup = new HDFgroup( hypGrpName, aTopGroup );
5257           aGroup->OpenOnDisk();
5258
5259           // --> get hypothesis id
5260           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5261           string hypname;
5262           string libname;
5263           string hypdata;
5264
5265           // get number of datasets
5266           int aNbSubObjects = aGroup->nInternalObjects();
5267           for ( int k = 0; k < aNbSubObjects; k++ ) {
5268             // identify dataset
5269             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5270             aGroup->InternalObjectIndentify( k, name_of_subgroup );
5271             // --> get hypothesis name
5272             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
5273               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5274               aDataset->OpenOnDisk();
5275               size = aDataset->GetSize();
5276               char* hypname_str = new char[ size ];
5277               aDataset->ReadFromDisk( hypname_str );
5278               hypname = string( hypname_str );
5279               delete [] hypname_str;
5280               aDataset->CloseOnDisk();
5281             }
5282             // --> get hypothesis plugin library name
5283             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
5284               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5285               aDataset->OpenOnDisk();
5286               size = aDataset->GetSize();
5287               char* libname_str = new char[ size ];
5288               aDataset->ReadFromDisk( libname_str );
5289               if(MYDEBUG) SCRUTE( libname_str );
5290               libname = string( libname_str );
5291               delete [] libname_str;
5292               aDataset->CloseOnDisk();
5293             }
5294             // --> get hypothesis data
5295             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
5296               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5297               aDataset->OpenOnDisk();
5298               size = aDataset->GetSize();
5299               char* hypdata_str = new char[ size ];
5300               aDataset->ReadFromDisk( hypdata_str );
5301               hypdata = string( hypdata_str );
5302               delete [] hypdata_str;
5303               aDataset->CloseOnDisk();
5304             }
5305           }
5306           // close hypothesis HDF group
5307           aGroup->CloseOnDisk();
5308
5309           // --> restore hypothesis from data
5310           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5311             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5312                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5313             SMESH::SMESH_Hypothesis_var myHyp;
5314
5315             try { // protect persistence mechanism against exceptions
5316               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5317             }
5318             catch (...) {
5319               INFOS( "Exception during hypothesis creation" );
5320             }
5321
5322             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5323             if ( myImpl ) {
5324               // myImpl->LoadFrom( hypdata.c_str() );
5325               hypDataList.push_back( make_pair( myImpl, hypdata ));
5326               CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5327               int newId = myStudyContext->findId( iorString.in() );
5328               myStudyContext->mapOldToNew( id, newId );
5329             }
5330             else
5331               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5332           }
5333         }
5334       }
5335       // close hypotheses root HDF group
5336       aTopGroup->CloseOnDisk();
5337       aTopGroup = 0;
5338     }
5339
5340     // --> then we should read&create algorithms
5341     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5342       // open algorithms root HDF group
5343       aTopGroup = new HDFgroup( "Algorithms", aFile );
5344       aTopGroup->OpenOnDisk();
5345
5346       // get number of algorithms
5347       int aNbObjects = aTopGroup->nInternalObjects();
5348       for ( int j = 0; j < aNbObjects; j++ ) {
5349         // try to identify algorithm
5350         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5351         aTopGroup->InternalObjectIndentify( j, hypGrpName );
5352
5353         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5354           // open algorithm group
5355           aGroup = new HDFgroup( hypGrpName, aTopGroup );
5356           aGroup->OpenOnDisk();
5357
5358           // --> get algorithm id
5359           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5360           string hypname;
5361           string libname;
5362           string hypdata;
5363
5364           // get number of datasets
5365           int aNbSubObjects = aGroup->nInternalObjects();
5366           for ( int k = 0; k < aNbSubObjects; k++ ) {
5367             // identify dataset
5368             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5369             aGroup->InternalObjectIndentify( k, name_of_subgroup );
5370             // --> get algorithm name
5371             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
5372               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5373               aDataset->OpenOnDisk();
5374               size = aDataset->GetSize();
5375               char* hypname_str = new char[ size ];
5376               aDataset->ReadFromDisk( hypname_str );
5377               hypname = string( hypname_str );
5378               delete [] hypname_str;
5379               aDataset->CloseOnDisk();
5380             }
5381             // --> get algorithm plugin library name
5382             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
5383               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5384               aDataset->OpenOnDisk();
5385               size = aDataset->GetSize();
5386               char* libname_str = new char[ size ];
5387               aDataset->ReadFromDisk( libname_str );
5388               if(MYDEBUG) SCRUTE( libname_str );
5389               libname = string( libname_str );
5390               delete [] libname_str;
5391               aDataset->CloseOnDisk();
5392             }
5393             // --> get algorithm data
5394             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
5395               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5396               aDataset->OpenOnDisk();
5397               size = aDataset->GetSize();
5398               char* hypdata_str = new char[ size ];
5399               aDataset->ReadFromDisk( hypdata_str );
5400               if(MYDEBUG) SCRUTE( hypdata_str );
5401               hypdata = string( hypdata_str );
5402               delete [] hypdata_str;
5403               aDataset->CloseOnDisk();
5404             }
5405           }
5406           // close algorithm HDF group
5407           aGroup->CloseOnDisk();
5408
5409           // --> restore algorithm from data
5410           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5411             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5412                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5413             SMESH::SMESH_Hypothesis_var myHyp;
5414
5415             try { // protect persistence mechanism against exceptions
5416               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5417             }
5418             catch( SALOME::SALOME_Exception& ex )
5419             {
5420               INFOS( "Exception during hypothesis creation: " << ex.details.text );
5421             }
5422             catch (...) {
5423               INFOS( "Exception during hypothesis creation" );
5424             }
5425
5426             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5427             if ( myImpl ) {
5428               //myImpl->LoadFrom( hypdata.c_str() );
5429               hypDataList.push_back( make_pair( myImpl, hypdata ));
5430               CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5431               int newId = myStudyContext->findId( iorString.in() );
5432               myStudyContext->mapOldToNew( id, newId );
5433             }
5434             else
5435               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5436           }
5437         }
5438       }
5439       // close algorithms root HDF group
5440       aTopGroup->CloseOnDisk();
5441       aTopGroup = 0;
5442     }
5443
5444     // --> the rest groups should be meshes
5445     for ( int i = 0; i < aNbGroups; i++ ) {
5446       // identify next group
5447       char meshName[ HDF_NAME_MAX_LEN+1 ];
5448       aFile->InternalObjectIndentify( i, meshName );
5449
5450       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5451         // --> get mesh id
5452         int id = atoi( string( meshName ).substr( 4 ).c_str() );
5453         if ( id <= 0 )
5454           continue;
5455
5456         // open mesh HDF group
5457         aTopGroup = new HDFgroup( meshName, aFile );
5458         aTopGroup->OpenOnDisk();
5459
5460         // get number of child HDF objects
5461         int aNbObjects = aTopGroup->nInternalObjects();
5462         if ( aNbObjects > 0 ) {
5463           // create mesh
5464           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5465           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5466           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5467           if ( !myNewMeshImpl )
5468             continue;
5469           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5470
5471           CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5472           int newId = myStudyContext->findId( iorString.in() );
5473           myStudyContext->mapOldToNew( id, newId );
5474
5475           // ouv : NPAL12872
5476           // try to read and set auto color flag
5477           char aMeshAutoColorName[ 30 ];
5478           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5479           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5480           {
5481             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5482             aDataset->OpenOnDisk();
5483             size = aDataset->GetSize();
5484             int* anAutoColor = new int[ size ];
5485             aDataset->ReadFromDisk( anAutoColor );
5486             aDataset->CloseOnDisk();
5487             myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5488             delete [] anAutoColor;
5489           }
5490
5491           // try to read and set reference to shape
5492           GEOM::GEOM_Object_var aShapeObject;
5493           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5494             // load mesh "Ref on shape" - it's an entry to SObject
5495             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5496             aDataset->OpenOnDisk();
5497             size = aDataset->GetSize();
5498             char* refFromFile = new char[ size ];
5499             aDataset->ReadFromDisk( refFromFile );
5500             aDataset->CloseOnDisk();
5501             if ( strlen( refFromFile ) > 0 ) {
5502               SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5503               CORBA::Object_var  shapeObject = SObjectToObject( shapeSO );
5504               if ( !CORBA::is_nil( shapeObject ) ) {
5505                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5506                 if ( !aShapeObject->_is_nil() )
5507                   myNewMeshImpl->SetShape( aShapeObject );
5508               }
5509             }
5510             delete [] refFromFile;
5511           }
5512
5513           // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5514           if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5515           {
5516             aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5517             aDataset->OpenOnDisk();
5518             size = aDataset->GetSize();
5519             int* meshPersistentId = new int[ size ];
5520             aDataset->ReadFromDisk( meshPersistentId );
5521             aDataset->CloseOnDisk();
5522             myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5523             delete [] meshPersistentId;
5524           }
5525
5526           // Restore SMESH_Mesh_i::_mainShapeTick
5527           if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5528           {
5529             aDataset = new HDFdataset( "shapeTick", aTopGroup );
5530             aDataset->OpenOnDisk();
5531             int* shapeTick = & myNewMeshImpl->MainShapeTick();
5532             aDataset->ReadFromDisk( shapeTick );
5533             aDataset->CloseOnDisk();
5534           }
5535
5536           // Restore file info
5537           if ( aTopGroup->ExistInternalObject( "file info" ))
5538           {
5539             aDataset = new HDFdataset( "file info", aTopGroup );
5540             aDataset->OpenOnDisk();
5541             size = aDataset->GetSize();
5542             std::string info( size, ' ');
5543             aDataset->ReadFromDisk( (char*) info.data() );
5544             aDataset->CloseOnDisk();
5545             myNewMeshImpl->FileInfoFromString( info );
5546           }
5547         }
5548       }
5549     } // reading MESHes
5550
5551     // As all objects that can be referred by hypothesis are created,
5552     // we can restore hypothesis data
5553
5554     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5555     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5556     {
5557       SMESH_Hypothesis_i* hyp  = hyp_data->first;
5558       string &            data = hyp_data->second;
5559       hyp->LoadFrom( data.c_str() );
5560     }
5561
5562     // Restore the rest mesh data
5563
5564     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5565     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5566     {
5567       aTopGroup                   = meshi_group->second;
5568       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5569
5570       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5571       bool hasData = false;
5572
5573       // get mesh old id
5574       CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5575       int newId = myStudyContext->findId( iorString.in() );
5576       int meshOldId = myStudyContext->getOldId( newId );
5577
5578       // try to find mesh data dataset
5579       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5580         // load mesh "has data" flag
5581         aDataset = new HDFdataset( "Has data", aTopGroup );
5582         aDataset->OpenOnDisk();
5583         size = aDataset->GetSize();
5584         char* strHasData = new char[ size ];
5585         aDataset->ReadFromDisk( strHasData );
5586         aDataset->CloseOnDisk();
5587         if ( strcmp( strHasData, "1") == 0 ) {
5588           hasData = true;
5589         }
5590         delete [] strHasData;
5591       }
5592
5593       // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5594       // nodes and elements are not yet put into sub-meshes)
5595       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5596         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5597         aGroup->OpenOnDisk();
5598         // get number of applied algorithms
5599         int aNbSubObjects = aGroup->nInternalObjects();
5600         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5601         for ( int j = 0; j < aNbSubObjects; j++ ) {
5602           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5603           aGroup->InternalObjectIndentify( j, name_dataset );
5604           // check if it is an algorithm
5605           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5606             aDataset = new HDFdataset( name_dataset, aGroup );
5607             aDataset->OpenOnDisk();
5608             size = aDataset->GetSize();
5609             char* refFromFile = new char[ size ];
5610             aDataset->ReadFromDisk( refFromFile );
5611             aDataset->CloseOnDisk();
5612             // san - it is impossible to recover applied algorithms using their entries within Load() method
5613             int id = atoi( refFromFile );
5614             delete [] refFromFile;
5615             string anIOR = myStudyContext->getIORbyOldId( id );
5616             if ( !anIOR.empty() ) {
5617               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5618               if ( !CORBA::is_nil( hypObject ) ) {
5619                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5620                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5621                                            || !myNewMeshImpl->HasShapeToMesh()) )
5622                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5623               }
5624             }
5625           }
5626         }
5627         aGroup->CloseOnDisk();
5628       }
5629
5630       // try to get applied hypotheses
5631       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5632         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5633         aGroup->OpenOnDisk();
5634         // get number of applied hypotheses
5635         int aNbSubObjects = aGroup->nInternalObjects();
5636         for ( int j = 0; j < aNbSubObjects; j++ ) {
5637           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5638           aGroup->InternalObjectIndentify( j, name_dataset );
5639           // check if it is a hypothesis
5640           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5641             aDataset = new HDFdataset( name_dataset, aGroup );
5642             aDataset->OpenOnDisk();
5643             size = aDataset->GetSize();
5644             char* refFromFile = new char[ size ];
5645             aDataset->ReadFromDisk( refFromFile );
5646             aDataset->CloseOnDisk();
5647             // san - it is impossible to recover applied hypotheses using their entries within Load() method
5648             int id = atoi( refFromFile );
5649             delete [] refFromFile;
5650             string anIOR = myStudyContext->getIORbyOldId( id );
5651             if ( !anIOR.empty() ) {
5652               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5653               if ( !CORBA::is_nil( hypObject ) ) {
5654                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5655                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5656                                            || !myNewMeshImpl->HasShapeToMesh()) )
5657                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5658               }
5659             }
5660           }
5661         }
5662         aGroup->CloseOnDisk();
5663       }
5664
5665       // --> try to find SUB-MESHES containers for each type of submesh
5666       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5667         const char* name_meshgroup = 0;
5668         if ( j == GetSubMeshOnVertexTag() )
5669           name_meshgroup = "SubMeshes On Vertex";
5670         else if ( j == GetSubMeshOnEdgeTag() )
5671           name_meshgroup = "SubMeshes On Edge";
5672         else if ( j == GetSubMeshOnWireTag() )
5673           name_meshgroup = "SubMeshes On Wire";
5674         else if ( j == GetSubMeshOnFaceTag() )
5675           name_meshgroup = "SubMeshes On Face";
5676         else if ( j == GetSubMeshOnShellTag() )
5677           name_meshgroup = "SubMeshes On Shell";
5678         else if ( j == GetSubMeshOnSolidTag() )
5679           name_meshgroup = "SubMeshes On Solid";
5680         else if ( j == GetSubMeshOnCompoundTag() )
5681           name_meshgroup = "SubMeshes On Compound";
5682
5683         // try to get submeshes container HDF group
5684         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5685           // open submeshes containers HDF group
5686           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5687           aGroup->OpenOnDisk();
5688
5689           // get number of submeshes
5690           int aNbSubMeshes = aGroup->nInternalObjects();
5691           for ( int k = 0; k < aNbSubMeshes; k++ ) {
5692             // identify submesh
5693             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5694             aGroup->InternalObjectIndentify( k, name_submeshgroup );
5695             if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5696               // --> get submesh id
5697               int subid = atoi( name_submeshgroup + 7 );
5698               if ( subid <= 0 )
5699                 continue;
5700               // open submesh HDF group
5701               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5702               aSubGroup->OpenOnDisk();
5703
5704               // try to read and set reference to subshape
5705               GEOM::GEOM_Object_var aSubShapeObject;
5706               SMESH::SMESH_subMesh_var aSubMesh;
5707
5708               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5709                 // load submesh "Ref on shape" - it's an entry to SObject
5710                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5711                 aDataset->OpenOnDisk();
5712                 size = aDataset->GetSize();
5713                 char* refFromFile = new char[ size ];
5714                 aDataset->ReadFromDisk( refFromFile );
5715                 aDataset->CloseOnDisk();
5716                 if ( strlen( refFromFile ) > 0 ) {
5717                   SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5718                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5719                   if ( !CORBA::is_nil( subShapeObject ) ) {
5720                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5721                     if ( !aSubShapeObject->_is_nil() )
5722                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
5723                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5724                     if ( aSubMesh->_is_nil() )
5725                       continue;
5726                     string iorSubString = GetORB()->object_to_string( aSubMesh );
5727                     int        newSubId = myStudyContext->findId( iorSubString );
5728                     myStudyContext->mapOldToNew( subid, newSubId );
5729                   }
5730                 }
5731                 delete [] refFromFile;
5732               }
5733
5734               if ( aSubMesh->_is_nil() )
5735                 continue;
5736
5737               // try to get applied algorithms
5738               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5739                 // open "applied algorithms" HDF group
5740                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5741                 aSubSubGroup->OpenOnDisk();
5742                 // get number of applied algorithms
5743                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5744                 for ( int l = 0; l < aNbSubObjects; l++ ) {
5745                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5746                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5747                   // check if it is an algorithm
5748                   if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5749                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5750                     aDataset->OpenOnDisk();
5751                     size = aDataset->GetSize();
5752                     char* refFromFile = new char[ size ];
5753                     aDataset->ReadFromDisk( refFromFile );
5754                     aDataset->CloseOnDisk();
5755
5756                     int id = atoi( refFromFile );
5757                     string anIOR = myStudyContext->getIORbyOldId( id );
5758                     if ( !anIOR.empty() ) {
5759                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5760                       if ( !CORBA::is_nil( hypObject ) ) {
5761                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5762                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5763                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5764                       }
5765                     }
5766                     delete [] refFromFile;
5767                   }
5768                 }
5769                 // close "applied algorithms" HDF group
5770                 aSubSubGroup->CloseOnDisk();
5771               }
5772
5773               // try to get applied hypotheses
5774               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5775                 // open "applied hypotheses" HDF group
5776                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5777                 aSubSubGroup->OpenOnDisk();
5778                 // get number of applied hypotheses
5779                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5780                 for ( int l = 0; l < aNbSubObjects; l++ ) {
5781                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5782                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5783                   // check if it is a hypothesis
5784                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5785                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5786                     aDataset->OpenOnDisk();
5787                     size = aDataset->GetSize();
5788                     char* refFromFile = new char[ size ];
5789                     aDataset->ReadFromDisk( refFromFile );
5790                     aDataset->CloseOnDisk();
5791
5792                     int id = atoi( refFromFile );
5793                     string anIOR = myStudyContext->getIORbyOldId( id );
5794                     if ( !anIOR.empty() ) {
5795                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5796                       if ( !CORBA::is_nil( hypObject ) ) {
5797                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5798                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5799                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5800                       }
5801                     }
5802                     delete [] refFromFile;
5803                   }
5804                 }
5805                 // close "APPLIED HYPOTHESES" hdf group
5806                 aSubSubGroup->CloseOnDisk();
5807               }
5808
5809               // close SUB-MESH hdf group
5810               aSubGroup->CloseOnDisk();
5811             }
5812           }
5813           // close SUB-MESHES containers hdf group
5814           aGroup->CloseOnDisk();
5815         }
5816       }
5817
5818       // try to get GROUPS
5819       for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5820         char name_group[ 30 ];
5821         if ( ii == GetNodeGroupsTag() )
5822           strcpy( name_group, "Groups of Nodes" );
5823         else if ( ii == GetEdgeGroupsTag() )
5824           strcpy( name_group, "Groups of Edges" );
5825         else if ( ii == GetFaceGroupsTag() )
5826           strcpy( name_group, "Groups of Faces" );
5827         else if ( ii == GetVolumeGroupsTag() )
5828           strcpy( name_group, "Groups of Volumes" );
5829         else if ( ii == Get0DElementsGroupsTag() )
5830           strcpy( name_group, "Groups of 0D Elements" );
5831         else if ( ii == GetBallElementsGroupsTag() )
5832           strcpy( name_group, "Groups of Balls" );
5833
5834         if ( aTopGroup->ExistInternalObject( name_group ) ) {
5835           aGroup = new HDFgroup( name_group, aTopGroup );
5836           aGroup->OpenOnDisk();
5837           // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5838           // within aGroup->ExistInternalObject( name )
5839           std::vector< std::string > subNames;
5840           TColStd_MapOfAsciiString mapOfNames;
5841           aGroup->GetAllObjects( subNames );
5842           for ( size_t iN = 0; iN < subNames.size(); ++iN )
5843             mapOfNames.Add( subNames[ iN ].c_str() );
5844           // loop on groups
5845           for ( size_t j = 0; j < subNames.size(); j++ ) {
5846             const std::string& name_dataset = subNames[ j ];
5847             // check if it is a group
5848             if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5849               // --> get group id
5850               char * endptr;
5851               int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5852               if ( subid <= 0 )
5853                 continue;
5854               int groupID = -1; // group local ID (also persistent)
5855               if ( *endptr )
5856                 groupID = atoi( endptr + 1 );
5857               aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5858               aDataset->OpenOnDisk();
5859
5860               // Retrieve actual group name
5861               size = aDataset->GetSize();
5862               char* nameFromFile = new char[ size ];
5863               aDataset->ReadFromDisk( nameFromFile );
5864               aDataset->CloseOnDisk();
5865
5866               // Try to find a shape reference
5867               TopoDS_Shape aShape;
5868               char aRefName[ 30 ];
5869               sprintf( aRefName, "Ref on shape %d", subid);
5870               if ( mapOfNames.Contains( aRefName ))
5871               {
5872                 // load mesh "Ref on shape" - it's an entry to SObject
5873                 aDataset = new HDFdataset( aRefName, aGroup );
5874                 aDataset->OpenOnDisk();
5875                 size = aDataset->GetSize();
5876                 char* refFromFile = new char[ size ];
5877                 aDataset->ReadFromDisk( refFromFile );
5878                 aDataset->CloseOnDisk();
5879                 if ( strlen( refFromFile ) > 0 ) {
5880                   SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5881                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5882                   if ( !CORBA::is_nil( shapeObject ) ) {
5883                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5884                     if ( !aShapeObject->_is_nil() )
5885                       aShape = GeomObjectToShape( aShapeObject );
5886                   }
5887                 }
5888                 delete [] refFromFile;
5889               }
5890               // Try to read a filter of SMESH_GroupOnFilter
5891               SMESH::Filter_var filter;
5892               SMESH_PredicatePtr predicate;
5893               std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5894               if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5895               {
5896                 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5897                 aDataset->OpenOnDisk();
5898                 size = aDataset->GetSize();
5899                 char* persistStr = new char[ size ];
5900                 aDataset->ReadFromDisk( persistStr );
5901                 aDataset->CloseOnDisk();
5902                 if ( strlen( persistStr ) > 0 ) {
5903                   filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5904                   predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5905                   filters.push_back( filter );
5906                 }
5907                 delete [] persistStr;
5908               }
5909
5910               // Create group servant
5911               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5912               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5913                 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5914               delete [] nameFromFile;
5915               // Obtain a SMESHDS_Group object
5916               if ( aNewGroup->_is_nil() )
5917                 continue;
5918
5919               string iorSubString = GetORB()->object_to_string( aNewGroup );
5920               int        newSubId = myStudyContext->findId( iorSubString );
5921               myStudyContext->mapOldToNew( subid, newSubId );
5922
5923               SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5924               if ( !aGroupImpl )
5925                 continue;
5926
5927               if ( SMESH_GroupOnFilter_i* aFilterGroup =
5928                    dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5929               {
5930                 aFilterGroup->SetFilter( filter );
5931                 filter->UnRegister();
5932               }
5933               SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5934               if ( !aGroupBaseDS )
5935                 continue;
5936
5937               aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5938
5939               // ouv : NPAL12872
5940               // Read color of the group
5941               char aGroupColorName[ 30 ];
5942               sprintf( aGroupColorName, "ColorGroup %d", subid);
5943               if ( mapOfNames.Contains( aGroupColorName ))
5944               {
5945                 aDataset = new HDFdataset( aGroupColorName, aGroup );
5946                 aDataset->OpenOnDisk();
5947                 size = aDataset->GetSize();
5948                 double* anRGB = new double[ size ];
5949                 aDataset->ReadFromDisk( anRGB );
5950                 aDataset->CloseOnDisk();
5951                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5952                 aGroupBaseDS->SetColor( aColor );
5953                 delete [] anRGB;
5954               }
5955             }
5956           }
5957           aGroup->CloseOnDisk();
5958         }
5959       } // reading GROUPs
5960
5961       // instead of reading mesh data, we read only brief information of all
5962       // objects: mesh, groups, sub-meshes (issue 0021208)
5963       if ( hasData )
5964       {
5965         SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5966                                          meshfile.ToCString(), filename.ToCString(),
5967                                          !isMultiFile );
5968       }
5969
5970       // read Sub-Mesh ORDER if any
5971       if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
5972         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5973         aDataset->OpenOnDisk();
5974         size = aDataset->GetSize();
5975         int* smIDs = new int[ size ];
5976         aDataset->ReadFromDisk( smIDs );
5977         aDataset->CloseOnDisk();
5978         TListOfListOfInt anOrderIds;
5979         anOrderIds.push_back( TListOfInt() );
5980         for ( int i = 0; i < size; i++ )
5981           if ( smIDs[ i ] < 0 ) // is separator
5982             anOrderIds.push_back( TListOfInt() );
5983           else
5984             anOrderIds.back().push_back(smIDs[ i ]);
5985
5986         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5987         delete [] smIDs;
5988       }
5989       if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
5990       {
5991         aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
5992         aDataset->OpenOnDisk();
5993         size = aDataset->GetSize();
5994         std::string dataString; dataString.resize( size );
5995         aDataset->ReadFromDisk((char*) dataString.data() );
5996         aDataset->CloseOnDisk();
5997
5998         std::istringstream istream( dataString.data() );
5999         boost::archive::text_iarchive archive( istream );
6000         std::list< std::list< std::string > > orderEntryLists;
6001         try {
6002           archive >> orderEntryLists;
6003         }
6004         catch (...) {}
6005
6006         TListOfListOfInt anOrderIds;
6007         for ( const std::list< std::string >& entryList : orderEntryLists )
6008         {
6009           anOrderIds.emplace_back();
6010           for ( const std::string & entry : entryList )
6011           {
6012             GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6013             TopoDS_Shape       shape = GeomObjectToShape( go );
6014             if ( SMESH_subMesh*   sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6015               anOrderIds.back().emplace_back( sm->GetId() );
6016           }
6017         }
6018         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6019       }
6020     } // loop on meshes
6021
6022     // update hyps needing full mesh data restored (issue 20918)
6023     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6024     {
6025       SMESH_Hypothesis_i* hyp  = hyp_data->first;
6026       hyp->UpdateAsMeshesRestored();
6027     }
6028
6029     // notify algos on completed restoration to set sub-mesh event listeners
6030     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6031     {
6032       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6033       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
6034
6035       TopoDS_Shape myLocShape;
6036       if(myLocMesh.HasShapeToMesh())
6037         myLocShape = myLocMesh.GetShapeToMesh();
6038       else
6039         myLocShape = SMESH_Mesh::PseudoShape();
6040
6041       myLocMesh.GetSubMesh(myLocShape)->
6042         ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6043     }
6044
6045     // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6046     list< SMESH::Filter_var >::iterator f = filters.begin();
6047     for ( ; f != filters.end(); ++f )
6048       if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6049         fi->FindBaseObjects();
6050
6051
6052     // close mesh group
6053     if(aTopGroup)
6054       aTopGroup->CloseOnDisk();
6055   }
6056   // close HDF file
6057   aFile->CloseOnDisk();
6058   delete aFile;
6059
6060   // Remove temporary files created from the stream
6061   if ( !isMultiFile )
6062   {
6063     SMESH_File meshFile( meshfile.ToCString() );
6064     if ( !meshFile ) // no meshfile exists
6065     {
6066       SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6067     }
6068     else
6069     {
6070       Engines::Container_var container = GetContainerRef();
6071       if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6072       {
6073         container_i->registerTemporaryFile( filename.ToCString() );
6074         container_i->registerTemporaryFile( meshfile.ToCString() );
6075         container_i->registerTemporaryFile( tmpDir.ToCString() );
6076       }
6077     }
6078   }
6079
6080   // creation of tree nodes for all data objects in the study
6081   // to support tree representation customization and drag-n-drop:
6082   SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6083   if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6084     useCaseBuilder->SetRootCurrent();
6085     useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6086     SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6087     for (it->InitEx(true); it->More(); it->Next()) {
6088       useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6089     }
6090   }
6091
6092   return true;
6093 }
6094
6095 //=============================================================================
6096 /*!
6097  *  SMESH_Gen_i::LoadASCII
6098  *
6099  *  Load SMESH module's data in ASCII format
6100  */
6101 //=============================================================================
6102
6103 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6104                              const SALOMEDS::TMPFile& theStream,
6105                              const char*              theURL,
6106                              bool                     isMultiFile ) {
6107   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6108   return Load( theComponent, theStream, theURL, isMultiFile );
6109
6110   //before call main ::Load method it's need for decipher text format to
6111   //binary ( "|xx" => x' )
6112   int size = theStream.length();
6113   if ( int((size / 3 )*3) != size ) //error size of buffer
6114     return false;
6115
6116   int real_size = int(size / 3);
6117
6118   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6119   char tmp[3];
6120   tmp[2]='\0';
6121   unsigned int c = -1;
6122   for ( int i = 0; i < real_size; i++ )
6123   {
6124     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6125     sscanf( tmp, "%x", &c );
6126     sprintf( (char*)&(buffer[i]), "%c", (char)c );
6127   }
6128
6129   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6130
6131   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6132 }
6133
6134 //=============================================================================
6135 /*!
6136  *  SMESH_Gen_i::Close
6137  *
6138  *  Clears study-connected data when it is closed
6139  */
6140 //=============================================================================
6141
6142 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6143 {
6144   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6145
6146   // Clear study contexts data
6147   myStudyContext->Clear();
6148
6149   // remove the tmp files meshes are loaded from
6150   SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6151
6152   // Clean trace of API methods calls
6153   CleanPythonTrace();
6154
6155   return;
6156 }
6157
6158 //=============================================================================
6159 /*!
6160  *  SMESH_Gen_i::ComponentDataType
6161  *
6162  *  Get component data type
6163  */
6164 //=============================================================================
6165
6166 char* SMESH_Gen_i::ComponentDataType()
6167 {
6168   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6169   return CORBA::string_dup( "SMESH" );
6170 }
6171
6172
6173 //=============================================================================
6174 /*!
6175  *  SMESH_Gen_i::IORToLocalPersistentID
6176  *
6177  *  Transform data from transient form to persistent
6178  */
6179 //=============================================================================
6180
6181 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6182                                            const char*           IORString,
6183                                            CORBA::Boolean        /*isMultiFile*/,
6184                                            CORBA::Boolean        /*isASCII*/ )
6185 {
6186   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6187
6188   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6189     int anId = myStudyContext->findId( IORString );
6190     if ( anId ) {
6191       if(MYDEBUG) MESSAGE( "VSR " << anId )
6192       char strId[ 20 ];
6193       sprintf( strId, "%d", anId );
6194       return  CORBA::string_dup( strId );
6195     }
6196   }
6197   return CORBA::string_dup( "" );
6198 }
6199
6200 //=============================================================================
6201 /*!
6202  *  SMESH_Gen_i::LocalPersistentIDToIOR
6203  *
6204  *  Transform data from persistent form to transient
6205  */
6206 //=============================================================================
6207
6208 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6209                                            const char*           aLocalPersistentID,
6210                                            CORBA::Boolean        /*isMultiFile*/,
6211                                            CORBA::Boolean        /*isASCII*/ )
6212 {
6213   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6214
6215   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6216     int anId = atoi( aLocalPersistentID );
6217     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6218   }
6219   return CORBA::string_dup( "" );
6220 }
6221
6222 //=======================================================================
6223 //function : RegisterObject
6224 //purpose  :
6225 //=======================================================================
6226
6227 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6228 {
6229   if ( myStudyContext && !CORBA::is_nil( theObject )) {
6230     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6231     return myStudyContext->addObject( string( iorString.in() ) );
6232   }
6233   return 0;
6234 }
6235
6236 //================================================================================
6237 /*!
6238  * \brief Return id of registered object
6239   * \param theObject - the Object
6240   * \retval int - Object id
6241  */
6242 //================================================================================
6243
6244 CORBA::Long  SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6245 {
6246   if ( myStudyContext && !CORBA::is_nil( theObject )) {
6247     string iorString = GetORB()->object_to_string( theObject );
6248     return myStudyContext->findId( iorString );
6249   }
6250   return 0;
6251 }
6252
6253 //=============================================================================
6254 /*!
6255  *  SMESH_Gen_i::SetName
6256  *
6257  *  Set a new object name
6258  */
6259 //=============================================================================
6260
6261 void SMESH_Gen_i::SetName(const char* theIOR,
6262                           const char* theName)
6263 {
6264   if ( theIOR && strcmp( theIOR, "" ) ) {
6265     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6266     SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6267     if ( !aSO->_is_nil() ) {
6268       SetName( aSO, theName );
6269     }
6270   }
6271 }
6272
6273 // Version information
6274 char* SMESH_Gen_i::getVersion()
6275 {
6276 #if SMESH_DEVELOPMENT
6277   return CORBA::string_dup(SMESH_VERSION_STR"dev");
6278 #else
6279   return CORBA::string_dup(SMESH_VERSION_STR);
6280 #endif
6281 }
6282
6283 //=================================================================================
6284 // function : Move()
6285 // purpose  : Moves objects to the specified position.
6286 //            Is used in the drag-n-drop functionality.
6287 //=================================================================================
6288
6289 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6290                         SALOMEDS::SObject_ptr      where,
6291                         CORBA::Long                row )
6292 {
6293   if ( CORBA::is_nil( where ) ) return;
6294
6295   SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6296   SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6297   SALOMEDS::SComponent_var father = where->GetFatherComponent();
6298   std::string dataType = father->ComponentDataType();
6299   if ( dataType != "SMESH" ) return; // not a SMESH component
6300
6301   SALOMEDS::SObject_var objAfter;
6302   if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6303     // insert at given row -> find insertion position
6304     SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6305     int i;
6306     for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6307     if ( i == row && useCaseIt->More() ) {
6308       objAfter = useCaseIt->Value();
6309     }
6310   }
6311
6312   for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6313     SALOMEDS::SObject_var sobj = what[i];
6314     if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6315     // insert the object to the use case tree
6316     if ( !CORBA::is_nil( objAfter ) )
6317       useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6318     else
6319       useCaseBuilder->AppendTo( where, sobj );        // append to the end of list
6320   }
6321 }
6322 //================================================================================
6323 /*!
6324  * \brief Returns true if algorithm can be used to mesh a given geometry
6325  *  \param [in] theAlgoType - the algorithm type
6326  *  \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6327  *  \param [in] theGeomObject - the geometry to mesh
6328  *  \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6329  *         else, returns \c True if at least one shape is meshable
6330  *  \return CORBA::Boolean - can or can't
6331  */
6332 //================================================================================
6333
6334 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char*           theAlgoType,
6335                                            const char*           theLibName,
6336                                            GEOM::GEOM_Object_ptr theGeomObject,
6337                                            CORBA::Boolean        toCheckAll)
6338 {
6339   SMESH_TRY;
6340
6341   std::string aPlatformLibName;
6342   GenericHypothesisCreator_i* aCreator =
6343     getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6344   if (aCreator)
6345   {
6346     TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6347     const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6348     return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6349   }
6350   else
6351   {
6352     return false;
6353   }
6354
6355   SMESH_CATCH( SMESH::doNothing );
6356
6357 #ifdef _DEBUG_
6358   cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6359 #endif
6360   return true;
6361 }
6362
6363 //================================================================================
6364 /*!
6365  * \brief Collect indices of elements, which are located inside the sphere
6366  */
6367 //================================================================================
6368
6369 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6370                                                  SMESH::ElementType     theElemType,
6371                                                  CORBA::Double         theX,
6372                                                  CORBA::Double         theY,
6373                                                  CORBA::Double         theZ,
6374                                                  CORBA::Double         theR)
6375 {
6376   SMESH::long_array_var aResult = new SMESH::long_array();
6377   if ( meshPart->_is_nil() )
6378     return aResult._retn();
6379
6380   // 1. Create geometrical object
6381   gp_Pnt aP( theX, theY, theZ );
6382   TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6383
6384   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6385
6386   if ( lst.size() > 0 ) {
6387     aResult->length( lst.size() );
6388     for ( size_t i = 0; i < lst.size(); i++ ) {
6389       aResult[i] = lst[i];
6390     }
6391   }
6392   return aResult._retn();
6393 }
6394
6395 //================================================================================
6396 /*!
6397  * \brief Collect indices of elements, which are located inside the box
6398  */
6399 //================================================================================
6400
6401 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6402                                               SMESH::ElementType        theElemType,
6403                                               CORBA::Double             theX1,
6404                                               CORBA::Double             theY1,
6405                                               CORBA::Double             theZ1,
6406                                               CORBA::Double             theX2,
6407                                               CORBA::Double             theY2,
6408                                               CORBA::Double             theZ2)
6409 {
6410   SMESH::long_array_var aResult = new SMESH::long_array();
6411   if( meshPart->_is_nil() )
6412     return aResult._retn();
6413
6414   TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6415                                              gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6416
6417   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6418
6419   if( lst.size() > 0 ) {
6420     aResult->length( lst.size() );
6421     for ( size_t i = 0; i < lst.size(); i++ ) {
6422       aResult[i] = lst[i];
6423     }
6424   }
6425   return aResult._retn();
6426 }
6427
6428 //================================================================================
6429 /*!
6430  * \brief Collect indices of elements, which are located inside the cylinder
6431  */
6432 //================================================================================
6433
6434 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6435                                                    SMESH::ElementType        theElemType,
6436                                                    CORBA::Double             theX,
6437                                                    CORBA::Double             theY,
6438                                                    CORBA::Double             theZ,
6439                                                    CORBA::Double             theDX,
6440                                                    CORBA::Double             theDY,
6441                                                    CORBA::Double             theDZ,
6442                                                    CORBA::Double             theH,
6443                                                    CORBA::Double             theR )
6444 {
6445   SMESH::long_array_var aResult = new SMESH::long_array();
6446   if( meshPart->_is_nil() )
6447     return aResult._retn();
6448
6449   gp_Pnt aP( theX, theY, theZ );
6450   gp_Vec aV( theDX, theDY, theDZ );
6451   gp_Ax2 anAxes (aP, aV);
6452
6453   TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6454
6455   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6456
6457   if( lst.size() > 0 ) {
6458     aResult->length( lst.size() );
6459     for ( size_t i = 0; i < lst.size(); i++ ) {
6460       aResult[i] = lst[i];
6461     }
6462   }
6463   return aResult._retn();
6464 }
6465
6466 //================================================================================
6467 /*!
6468  * \brief Collect indices of elements, which are located inside the geom object
6469  */
6470 //================================================================================
6471
6472 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6473                                            SMESH::ElementType        theElemType,
6474                                            GEOM::GEOM_Object_ptr     theGeom,
6475                                            CORBA::Double             theTolerance )
6476 {
6477   SMESH::long_array_var aResult = new SMESH::long_array();
6478   if( meshPart->_is_nil() || theGeom->_is_nil() )
6479     return aResult._retn();
6480
6481   TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6482
6483   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6484
6485   if( lst.size() > 0 ) {
6486     aResult->length( lst.size() );
6487     for ( size_t i = 0; i < lst.size(); i++ ) {
6488       aResult[i] = lst[i];
6489     }
6490   }
6491   return aResult._retn();
6492 }
6493
6494 //================================================================================
6495 /*!
6496  * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6497  */
6498 //================================================================================
6499
6500 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6501                                            SMESH::ElementType        theElemType,
6502                                            const TopoDS_Shape&       theShape,
6503                                            double*                   theTolerance) {
6504
6505   std::vector<long> res;
6506   SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6507
6508   if ( mesh->_is_nil() )
6509     return res;
6510
6511   SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6512   if ( !anImpl )
6513     return res;
6514
6515   const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6516
6517   if ( !meshDS )
6518     return res;
6519
6520   SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6521   SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6522   anElementsOnShape->SetAllNodes( true );
6523   anElementsOnShape->SetMesh( meshDS );
6524   anElementsOnShape->SetShape( theShape, aType );
6525
6526   if(theTolerance)
6527     anElementsOnShape->SetTolerance(*theTolerance);
6528
6529   SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6530   if ( !msource->_is_nil() ) { // Mesh case
6531     SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6532     if ( elemIt ) {
6533       while ( elemIt->more() ) {
6534         const SMDS_MeshElement* anElem = elemIt->next();
6535         long anId = anElem->GetID();
6536         if ( anElementsOnShape->IsSatisfy( anId ) )
6537           res.push_back( anId );
6538       }
6539     }
6540   }
6541   SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6542   if ( !gsource->_is_nil() ) {
6543     if(theElemType == SMESH::NODE) {
6544       SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6545       for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6546         if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6547           long anId = node->GetID();
6548           if ( anElementsOnShape->IsSatisfy( anId ) )
6549             res.push_back( anId );
6550         }
6551       }
6552     } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6553       SMESH::smIdType_array_var elems = gsource->GetListOfID();
6554       for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6555         if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6556           long anId = elem->GetID();
6557           if ( anElementsOnShape->IsSatisfy( anId ) )
6558             res.push_back( anId );
6559         }
6560       }
6561     }
6562   }
6563   SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6564   if ( !smsource->_is_nil() ) {
6565     SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6566     for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6567       const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6568       if (elem) {
6569         long anId = elem->GetID();
6570         if ( anElementsOnShape->IsSatisfy( anId ) )
6571           res.push_back( anId );
6572       }
6573     }
6574   }
6575   return res;
6576 }