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