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