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