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