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