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