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