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