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