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