Salome HOME
Fix for the "0021861: EDF 2226 : Documentation of numeric functor option in split...
[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                                   SMESH::ComputeError_out theError)
1236     throw ( SALOME::SALOME_Exception )
1237 {
1238   Unexpect aCatch(SALOME_SalomeException);
1239
1240   SMESH::SMESH_Mesh_var aMesh = createMesh();
1241 #ifdef WIN32
1242   char bname[ _MAX_FNAME ];
1243   _splitpath( theFileName, NULL, NULL, bname, NULL );
1244   string aFileName = bname;
1245 #else
1246   string aFileName = basename( theFileName );
1247 #endif
1248   // publish mesh in the study
1249   if ( CanPublishInStudy( aMesh ) ) {
1250     SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1251     aStudyBuilder->NewCommand();  // There is a transaction
1252     SALOMEDS::SObject_var aSO = PublishInStudy
1253       ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1254     aStudyBuilder->CommitCommand();
1255     if ( !aSO->_is_nil() ) {
1256       // Update Python script
1257       TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'" << theFileName << "')";
1258     }
1259   }
1260   SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1261   ASSERT( aServant );
1262   theError = aServant->ImportGMFFile( theFileName );
1263   aServant->GetImpl().GetMeshDS()->Modified();
1264   return aMesh._retn();
1265 }
1266
1267
1268 //=============================================================================
1269 /*!
1270  *  SMESH_Gen_i::IsReadyToCompute
1271  *
1272  *  Returns true if mesh contains enough data to be computed
1273  */
1274 //=============================================================================
1275
1276 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1277                                               GEOM::GEOM_Object_ptr theShapeObject )
1278   throw ( SALOME::SALOME_Exception )
1279 {
1280   Unexpect aCatch(SALOME_SalomeException);
1281   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1282
1283   if ( CORBA::is_nil( theShapeObject ) )
1284     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1285                                   SALOME::BAD_PARAM );
1286
1287   if ( CORBA::is_nil( theMesh ) )
1288     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1289                                   SALOME::BAD_PARAM );
1290
1291   try {
1292     // get mesh servant
1293     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1294     ASSERT( meshServant );
1295     if ( meshServant ) {
1296       // get local TopoDS_Shape
1297       TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1298       // call implementation
1299       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1300       return myGen.CheckAlgoState( myLocMesh, myLocShape );
1301     }
1302   }
1303   catch ( SALOME_Exception& S_ex ) {
1304     INFOS( "catch exception "<< S_ex.what() );
1305   }
1306   return false;
1307 }
1308
1309 //================================================================================
1310 /*!
1311  * \brief  Find SObject for an algo
1312  */
1313 //================================================================================
1314
1315 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1316 {
1317   if ( algo ) {
1318     if ( !myCurrentStudy->_is_nil() ) {
1319       // find algo in the study
1320       SALOMEDS::SComponent_var father = SALOMEDS::SComponent::_narrow
1321         ( myCurrentStudy->FindComponent( ComponentDataType() ) );
1322       if ( !father->_is_nil() ) {
1323         SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( father );
1324         for ( ; itBig->More(); itBig->Next() ) {
1325           SALOMEDS::SObject_var gotBranch = itBig->Value();
1326           if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1327             SALOMEDS::ChildIterator_var algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1328             for ( ; algoIt->More(); algoIt->Next() ) {
1329               SALOMEDS::SObject_var algoSO = algoIt->Value();
1330               CORBA::Object_var     algoIOR = SObjectToObject( algoSO );
1331               if ( !CORBA::is_nil( algoIOR )) {
1332                 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1333                 if ( impl && impl->GetImpl() == algo )
1334                   return algoSO._retn();
1335               }
1336             } // loop on algo SO's
1337             break;
1338           } // if algo tag
1339         } // SMESH component iterator
1340       }
1341     }
1342   }
1343   return SALOMEDS::SObject::_nil();
1344 }
1345
1346 //================================================================================
1347 /*!
1348  * \brief Return errors of mesh computation
1349  */
1350 //================================================================================
1351
1352 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1353                                                            GEOM::GEOM_Object_ptr theSubObject )
1354   throw ( SALOME::SALOME_Exception )
1355 {
1356   Unexpect aCatch(SALOME_SalomeException);
1357   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1358
1359   if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1360     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1361
1362   if ( CORBA::is_nil( theMesh ) )
1363     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1364
1365   SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1366   try {
1367     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1368     {
1369       TopoDS_Shape shape;
1370       if(theMesh->HasShapeToMesh())
1371         shape = GeomObjectToShape( theSubObject );
1372       else
1373         shape = SMESH_Mesh::PseudoShape();
1374
1375       ::SMESH_Mesh& mesh = meshServant->GetImpl();
1376
1377       error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1378       int nbErr = 0;
1379
1380       SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1381       const bool includeSelf = true, complexShapeFirst = true;
1382       SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1383                                                                complexShapeFirst);
1384       while ( smIt->more() )
1385       {
1386         sm = smIt->next();
1387         // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1388         //   break;
1389         SMESH_ComputeErrorPtr error = sm->GetComputeError();
1390         if ( error && !error->IsOK() && error->myAlgo )
1391         {
1392           SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1393           errStruct.code       = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1394           errStruct.comment    = error->myComment.c_str();
1395           errStruct.subShapeID = sm->GetId();
1396           SALOMEDS::SObject_var algoSO = GetAlgoSO( error->myAlgo );
1397           if ( !algoSO->_is_nil() )
1398             errStruct.algoName = algoSO->GetName();
1399           else
1400             errStruct.algoName = error->myAlgo->GetName();
1401           errStruct.hasBadMesh = !error->myBadElements.empty();
1402         }
1403       }
1404       error_array->length( nbErr );
1405     }
1406   }
1407   catch ( SALOME_Exception& S_ex ) {
1408     INFOS( "catch exception "<< S_ex.what() );
1409   }
1410
1411   return error_array._retn();
1412 }
1413
1414 //
1415 //================================================================================
1416 /*!
1417  * \brief Return mesh elements preventing computation of a subshape
1418  */
1419 //================================================================================
1420
1421 SMESH::MeshPreviewStruct*
1422 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1423                                   CORBA::Short          theSubShapeID )
1424   throw ( SALOME::SALOME_Exception )
1425 {
1426   Unexpect aCatch(SALOME_SalomeException);
1427   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1428
1429   if ( CORBA::is_nil( theMesh ) )
1430     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1431
1432   SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1433   try {
1434     // mesh servant
1435     if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1436     {
1437       // mesh implementation
1438       ::SMESH_Mesh& mesh = meshServant->GetImpl();
1439       // submesh by subshape id
1440       if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1441       {
1442         // compute error
1443         SMESH_ComputeErrorPtr error = sm->GetComputeError();
1444         if ( error && !error->myBadElements.empty())
1445         {
1446           typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1447           typedef TNode2LocalIDMap::iterator         TNodeLocalID;
1448
1449           // get nodes of elements and count elements
1450           TNode2LocalIDMap mapNode2LocalID;
1451           list< TNodeLocalID > connectivity;
1452           int i, nbElements = 0, nbConnNodes = 0;
1453
1454           list<const SMDS_MeshElement*>::iterator elemIt  = error->myBadElements.begin();
1455           list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1456           for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1457           {
1458             SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1459             while ( nIt->more() )
1460               connectivity.push_back
1461                 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1462           }
1463           // fill node coords and assign local ids to the nodes
1464           int nbNodes = mapNode2LocalID.size();
1465           result->nodesXYZ.length( nbNodes );
1466           TNodeLocalID node2ID = mapNode2LocalID.begin();
1467           for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1468             node2ID->second = i;
1469             const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1470             result->nodesXYZ[i].x = node->X();
1471             result->nodesXYZ[i].y = node->Y();
1472             result->nodesXYZ[i].z = node->Z();
1473           }
1474           // fill connectivity
1475           result->elementConnectivities.length( nbConnNodes );
1476           list< TNodeLocalID >::iterator connIt = connectivity.begin();
1477           for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1478             result->elementConnectivities[i] = (*connIt)->second;
1479           }
1480           // fill element types
1481           result->elementTypes.length( nbElements );
1482           for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1483           {
1484             const SMDS_MeshElement* elem = *elemIt;
1485             result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1486             result->elementTypes[i].isPoly           = elem->IsPoly();
1487             result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1488           }
1489         }
1490       }
1491     }
1492   }
1493   catch ( SALOME_Exception& S_ex ) {
1494     INFOS( "catch exception "<< S_ex.what() );
1495   }
1496
1497   return result._retn();
1498 }
1499
1500 //================================================================================
1501 /*!
1502  * \brief Returns errors of hypotheses definintion
1503  * \param theMesh - the mesh
1504  * \param theSubObject - the main or sub- shape
1505  * \retval SMESH::algo_error_array* - sequence of errors
1506  */
1507 //================================================================================
1508
1509 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1510                                                     GEOM::GEOM_Object_ptr theSubObject )
1511       throw ( SALOME::SALOME_Exception )
1512 {
1513   Unexpect aCatch(SALOME_SalomeException);
1514   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1515
1516   if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1517     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1518
1519   if ( CORBA::is_nil( theMesh ) )
1520     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1521
1522   SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1523   try {
1524     SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1525     ASSERT( meshServant );
1526     if ( meshServant ) {
1527       TopoDS_Shape myLocShape;
1528       if(theMesh->HasShapeToMesh())
1529         myLocShape = GeomObjectToShape( theSubObject );
1530       else
1531         myLocShape = SMESH_Mesh::PseudoShape();
1532
1533       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1534       list< ::SMESH_Gen::TAlgoStateError > error_list;
1535       list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1536       // call ::SMESH_Gen::GetAlgoState()
1537       myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1538       error_array->length( error_list.size() );
1539       int i = 0;
1540       for ( error = error_list.begin(); error != error_list.end(); ++error )
1541       {
1542         // fill AlgoStateError structure
1543         SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1544         errStruct.state        = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1545         errStruct.algoDim      = error->_algoDim;
1546         errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1547         errStruct.algoName     = "";
1548         SALOMEDS::SObject_var algoSO = GetAlgoSO( error->_algo );
1549         if ( !algoSO->_is_nil() )
1550           errStruct.algoName   = algoSO->GetName();
1551       }
1552     }
1553   }
1554   catch ( SALOME_Exception& S_ex ) {
1555     INFOS( "catch exception "<< S_ex.what() );
1556   }
1557   return error_array._retn();
1558 }
1559
1560 //=============================================================================
1561 /*!
1562  *  SMESH_Gen_i::GetSubShapesId
1563  *
1564  *  Get sub-shapes unique ID's list
1565  */
1566 //=============================================================================
1567
1568 SMESH::long_array* SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1569                                             const SMESH::object_array& theListOfSubShapeObject )
1570      throw ( SALOME::SALOME_Exception )
1571 {
1572   Unexpect aCatch(SALOME_SalomeException);
1573   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1574
1575   SMESH::long_array_var shapesId = new SMESH::long_array;
1576   set<int> setId;
1577
1578   if ( CORBA::is_nil( theMainShapeObject ) )
1579     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1580                                   SALOME::BAD_PARAM );
1581
1582   try
1583     {
1584       TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1585       TopTools_IndexedMapOfShape myIndexToShape;
1586       TopExp::MapShapes(myMainShape,myIndexToShape);
1587
1588       for ( int i = 0; i < theListOfSubShapeObject.length(); i++ )
1589         {
1590           GEOM::GEOM_Object_var aShapeObject
1591             = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1592           if ( CORBA::is_nil( aShapeObject ) )
1593             THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1594                                         SALOME::BAD_PARAM );
1595
1596           TopoDS_Shape locShape  = GeomObjectToShape(aShapeObject);
1597           for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1598             {
1599               const TopoDS_Face& F = TopoDS::Face(exp.Current());
1600               setId.insert(myIndexToShape.FindIndex(F));
1601               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1602             }
1603           for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1604             {
1605               const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1606               setId.insert(myIndexToShape.FindIndex(E));
1607               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1608             }
1609           for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1610             {
1611               const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1612               setId.insert(myIndexToShape.FindIndex(V));
1613               if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1614             }
1615         }
1616       shapesId->length(setId.size());
1617       set<int>::iterator iind;
1618       int i=0;
1619       for (iind = setId.begin(); iind != setId.end(); iind++)
1620         {
1621           if(MYDEBUG) SCRUTE((*iind));
1622           shapesId[i] = (*iind);
1623           if(MYDEBUG) SCRUTE(shapesId[i]);
1624           i++;
1625         }
1626     }
1627   catch (SALOME_Exception& S_ex)
1628     {
1629       THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1630     }
1631
1632   return shapesId._retn();
1633 }
1634
1635 //=============================================================================
1636 /*!
1637  *  SMESH_Gen_i::Compute
1638  *
1639  *  Compute mesh on a shape
1640  */
1641 //=============================================================================
1642
1643 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1644                                      GEOM::GEOM_Object_ptr theShapeObject )
1645      throw ( SALOME::SALOME_Exception )
1646 {
1647   MEMOSTAT;
1648   Unexpect aCatch(SALOME_SalomeException);
1649   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1650
1651   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1652     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1653                                   SALOME::BAD_PARAM );
1654
1655   if ( CORBA::is_nil( theMesh ) )
1656     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1657                                   SALOME::BAD_PARAM );
1658
1659   // Update Python script
1660   TPythonDump() << "isDone = " << this << ".Compute( "
1661                 << theMesh << ", " << theShapeObject << ")";
1662
1663   try {
1664     // get mesh servant
1665     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1666     meshServant->Load();
1667     ASSERT( meshServant );
1668     if ( meshServant ) {
1669       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1670       meshServant->CheckGeomGroupModif();
1671       // get local TopoDS_Shape
1672       TopoDS_Shape myLocShape;
1673       if(theMesh->HasShapeToMesh())
1674         myLocShape = GeomObjectToShape( theShapeObject );
1675       else
1676         myLocShape = SMESH_Mesh::PseudoShape();
1677       // call implementation compute
1678       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1679 #ifdef WITH_SMESH_CANCEL_COMPUTE
1680       myGen.PrepareCompute( myLocMesh, myLocShape);
1681 #endif
1682       bool ok = myGen.Compute( myLocMesh, myLocShape);
1683       meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1684       myLocMesh.GetMeshDS()->Modified();
1685       return ok;
1686     }
1687   }
1688   catch ( std::bad_alloc ) {
1689     INFOS( "Compute(): lack of memory" );
1690   }
1691   catch ( SALOME_Exception& S_ex ) {
1692     INFOS( "Compute(): catch exception "<< S_ex.what() );
1693   }
1694   catch ( ... ) {
1695     INFOS( "Compute(): unknown exception " );
1696   }
1697   return false;
1698 }
1699
1700 //=============================================================================
1701 /*!
1702  *  SMESH_Gen_i::CancelCompute
1703  *
1704  *  Cancel Compute mesh on a shape
1705  */
1706 //=============================================================================
1707
1708 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1709                                  GEOM::GEOM_Object_ptr theShapeObject )
1710 {
1711 #ifdef WITH_SMESH_CANCEL_COMPUTE
1712   SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1713   ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1714   TopoDS_Shape myLocShape;
1715   if(theMesh->HasShapeToMesh())
1716     myLocShape = GeomObjectToShape( theShapeObject );
1717   else
1718     myLocShape = SMESH_Mesh::PseudoShape();
1719   myGen.CancelCompute( myLocMesh, myLocShape);
1720 #endif
1721 }
1722
1723 //=============================================================================
1724 /*!
1725  *  SMESH_Gen_i::Precompute
1726  *
1727  *  Compute mesh as preview till indicated dimension on shape
1728  */
1729 //=============================================================================
1730
1731 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1732                                                    GEOM::GEOM_Object_ptr theShapeObject,
1733                                                    SMESH::Dimension      theDimension,
1734                                                    SMESH::long_array&    theShapesId)
1735      throw ( SALOME::SALOME_Exception )
1736 {
1737   Unexpect aCatch(SALOME_SalomeException);
1738   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
1739
1740   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1741     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1742                                   SALOME::BAD_PARAM );
1743
1744   if ( CORBA::is_nil( theMesh ) )
1745     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1746                                   SALOME::BAD_PARAM );
1747
1748   SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1749   try {
1750     // get mesh servant
1751     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1752     meshServant->Load();
1753     ASSERT( meshServant );
1754     if ( meshServant ) {
1755       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1756       meshServant->CheckGeomGroupModif();
1757       // get local TopoDS_Shape
1758       TopoDS_Shape myLocShape;
1759       if(theMesh->HasShapeToMesh())
1760         myLocShape = GeomObjectToShape( theShapeObject );
1761       else
1762         return result._retn();;
1763
1764       // call implementation compute
1765       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1766       TSetOfInt shapeIds;
1767       ::MeshDimension aDim = (MeshDimension)theDimension;
1768       if ( myGen.Compute( myLocMesh, myLocShape, false, aDim, &shapeIds ) )
1769       {
1770         int nbShapeId = shapeIds.size();
1771         theShapesId.length( nbShapeId );
1772         // iterates on shapes and collect mesh entities into mesh preview
1773         TSetOfInt::const_iterator idIt = shapeIds.begin();
1774         TSetOfInt::const_iterator idEnd = shapeIds.end();
1775         std::map< int, int > mapOfShIdNb;
1776         std::set< SMESH_TLink > setOfEdge;
1777         std::list< SMDSAbs_ElementType > listOfElemType;
1778         typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1779         typedef TNode2LocalIDMap::iterator         TNodeLocalID;
1780         TNode2LocalIDMap mapNode2LocalID;
1781         list< TNodeLocalID > connectivity;
1782         int i, nbConnNodes = 0;
1783         std::set< const SMESH_subMesh* > setOfVSubMesh;
1784         // iterates on shapes
1785         for ( ; idIt != idEnd; idIt++ )
1786         {
1787           if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
1788             continue;
1789           SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
1790           if ( !sm || !sm->IsMeshComputed() )
1791             continue;
1792
1793           const TopoDS_Shape& aSh = sm->GetSubShape();
1794           const int shDim = myGen.GetShapeDim( aSh );
1795           if ( shDim < 1 || shDim > theDimension )
1796             continue;
1797
1798           mapOfShIdNb[ *idIt ] = 0;
1799           theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
1800
1801           SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
1802           if ( !smDS ) continue;
1803
1804           if ( theDimension == SMESH::DIM_2D )
1805           {
1806             SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
1807             while ( faceIt->more() )
1808             {
1809               const SMDS_MeshElement* face = faceIt->next();
1810               int aNbNode = face->NbNodes();
1811               if ( aNbNode > 4 )
1812                 aNbNode /= 2; // do not take into account additional middle nodes
1813
1814               SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
1815               for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
1816               {
1817                 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
1818                 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
1819                 {
1820                   listOfElemType.push_back( SMDSAbs_Edge );
1821                   connectivity.push_back
1822                     ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
1823                   connectivity.push_back
1824                     ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
1825                 }
1826                 node1 = node2;
1827               }
1828             }
1829           }
1830           else if ( theDimension == SMESH::DIM_1D )
1831           {
1832             SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
1833             while ( nodeIt->more() )
1834             {
1835               listOfElemType.push_back( SMDSAbs_Node );
1836               connectivity.push_back
1837                 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
1838             }
1839             // add corner nodes by first vertex from edge
1840             SMESH_subMeshIteratorPtr edgeSmIt =
1841               sm->getDependsOnIterator(/*includeSelf*/false,
1842                                        /*complexShapeFirst*/false);
1843             while ( edgeSmIt->more() )
1844             {
1845               SMESH_subMesh* vertexSM = edgeSmIt->next();
1846               // check that vertex is not already treated
1847               if ( !setOfVSubMesh.insert( vertexSM ).second )
1848                 continue;
1849               if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
1850                 continue;
1851
1852               const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
1853               SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
1854               while ( nodeIt->more() )
1855               {
1856                 listOfElemType.push_back( SMDSAbs_Node );
1857                 connectivity.push_back
1858                   ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
1859               }
1860             }
1861           }
1862         }
1863
1864         // fill node coords and assign local ids to the nodes
1865         int nbNodes = mapNode2LocalID.size();
1866         result->nodesXYZ.length( nbNodes );
1867         TNodeLocalID node2ID = mapNode2LocalID.begin();
1868         for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1869           node2ID->second = i;
1870           const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1871           result->nodesXYZ[i].x = node->X();
1872           result->nodesXYZ[i].y = node->Y();
1873           result->nodesXYZ[i].z = node->Z();
1874         }
1875         // fill connectivity
1876         result->elementConnectivities.length( nbConnNodes );
1877         list< TNodeLocalID >::iterator connIt = connectivity.begin();
1878         for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1879           result->elementConnectivities[i] = (*connIt)->second;
1880         }
1881
1882         // fill element types
1883         result->elementTypes.length( listOfElemType.size() );
1884         std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
1885         std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
1886         for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
1887         {
1888           SMDSAbs_ElementType elemType = *typeIt;
1889           result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
1890           result->elementTypes[i].isPoly           = false;
1891           result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
1892         }
1893
1894         // correct number of shapes
1895         theShapesId.length( mapOfShIdNb.size() );
1896       }
1897     }
1898   }
1899   catch ( std::bad_alloc ) {
1900     INFOS( "Precompute(): lack of memory" );
1901   }
1902   catch ( SALOME_Exception& S_ex ) {
1903     INFOS( "Precompute(): catch exception "<< S_ex.what() );
1904   }
1905   catch ( ... ) {
1906     INFOS( "Precompute(): unknown exception " );
1907   }
1908   return result._retn();
1909 }
1910
1911
1912 //=============================================================================
1913 /*!
1914  *  SMESH_Gen_i::Evaluate
1915  *
1916  *  Evaluate mesh on a shape
1917  */
1918 //=============================================================================
1919
1920 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
1921                                          GEOM::GEOM_Object_ptr theShapeObject)
1922 //                                     SMESH::long_array& theNbElems)
1923      throw ( SALOME::SALOME_Exception )
1924 {
1925   Unexpect aCatch(SALOME_SalomeException);
1926   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
1927
1928   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1929     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1930                                   SALOME::BAD_PARAM );
1931
1932   if ( CORBA::is_nil( theMesh ) )
1933     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1934                                   SALOME::BAD_PARAM );
1935
1936   SMESH::long_array_var nbels = new SMESH::long_array;
1937   nbels->length(SMESH::Entity_Last);
1938   int i = SMESH::Entity_Node;
1939   for (; i < SMESH::Entity_Last; i++)
1940     nbels[i] = 0;
1941
1942   // Update Python script
1943   TPythonDump() << "theNbElems = " << this << ".Evaluate( "
1944                 << theMesh << ", " << theShapeObject << ")";
1945
1946   try {
1947     // get mesh servant
1948     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1949     ASSERT( meshServant );
1950     if ( meshServant ) {
1951       // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1952       meshServant->CheckGeomGroupModif();
1953       // get local TopoDS_Shape
1954       TopoDS_Shape myLocShape;
1955       if(theMesh->HasShapeToMesh())
1956         myLocShape = GeomObjectToShape( theShapeObject );
1957       else
1958         myLocShape = SMESH_Mesh::PseudoShape();
1959       // call implementation compute
1960       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1961       MapShapeNbElems aResMap;
1962       /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
1963       MapShapeNbElemsItr anIt = aResMap.begin();
1964       for(; anIt!=aResMap.end(); anIt++) {
1965         const vector<int>& aVec = (*anIt).second;
1966         for(i = SMESH::Entity_Node; i < aVec.size(); i++) {
1967           int nbElem = aVec[i];
1968           if ( nbElem < 0 ) // algo failed, check that it has reported a message
1969           {
1970             SMESH_subMesh* sm = anIt->first;
1971             SMESH_ComputeErrorPtr& error = sm->GetComputeError();
1972             const SMESH_Algo* algo = myGen.GetAlgo( myLocMesh, sm->GetSubShape());
1973             if ( (algo && !error.get()) || error->IsOK() )
1974               error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
1975           }
1976           else
1977           {
1978             nbels[i] += aVec[i];
1979           }
1980         }
1981       }
1982       return nbels._retn();
1983     }
1984   }
1985   catch ( std::bad_alloc ) {
1986     INFOS( "Evaluate(): lack of memory" );
1987   }
1988   catch ( SALOME_Exception& S_ex ) {
1989     INFOS( "Evaluate(): catch exception "<< S_ex.what() );
1990   }
1991   catch ( ... ) {
1992     INFOS( "Evaluate(): unknown exception " );
1993   }
1994
1995   return nbels._retn();
1996 }
1997
1998 //================================================================================
1999 /*!
2000  * \brief Return geometrical object the given element is built on
2001  *  \param theMesh - the mesh the element is in
2002  *  \param theElementID - the element ID
2003  *  \param theGeomName - the name of the result geom object if it is not yet published
2004  *  \retval GEOM::GEOM_Object_ptr - the found or just published geom object
2005  */
2006 //================================================================================
2007
2008 GEOM::GEOM_Object_ptr
2009 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
2010                                        CORBA::Long            theElementID,
2011                                        const char*            theGeomName)
2012   throw ( SALOME::SALOME_Exception )
2013 {
2014   Unexpect aCatch(SALOME_SalomeException);
2015
2016   GEOM::GEOM_Object_var geom = FindGeometryByMeshElement(theMesh, theElementID);
2017   if ( !geom->_is_nil() ) {
2018     GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2019     GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
2020
2021     // try to find the corresponding SObject
2022     SALOMEDS::SObject_var SObj = ObjectToSObject( myCurrentStudy, geom.in() );
2023     if ( SObj->_is_nil() ) // submesh can be not found even if published
2024     {
2025       // try to find published submesh
2026       GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2027       if ( !geom->IsMainShape() && list->length() == 1 ) {
2028         SALOMEDS::SObject_var mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2029         SALOMEDS::ChildIterator_var it;
2030         if ( !mainSO->_is_nil() )
2031           it = myCurrentStudy->NewChildIterator( mainSO );
2032         if ( !it->_is_nil() ) {
2033           for ( it->InitEx(true); SObj->_is_nil() && it->More(); it->Next() ) {
2034             GEOM::GEOM_Object_var subGeom =
2035               GEOM::GEOM_Object::_narrow( SObjectToObject( it->Value() ));
2036             if ( !subGeom->_is_nil() ) {
2037               GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2038               if ( subList->length() == 1 && list[0] == subList[0] ) {
2039                 SObj = it->Value();
2040                 geom = subGeom;
2041               }
2042             }
2043           }
2044         }
2045       }
2046     }
2047     if ( SObj->_is_nil() ) // publish a new subshape
2048       SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
2049
2050     // return only published geometry
2051     if ( !SObj->_is_nil() )
2052       return geom._retn();
2053   }
2054   return GEOM::GEOM_Object::_nil();
2055 }
2056
2057 //================================================================================
2058 /*!
2059  * \brief Return geometrical object the given element is built on.
2060  *  \param theMesh - the mesh the element is in
2061  *  \param theElementID - the element ID
2062  *  \retval GEOM::GEOM_Object_ptr - the found geom object
2063  */
2064 //================================================================================
2065
2066 GEOM::GEOM_Object_ptr
2067 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
2068                                         CORBA::Long            theElementID)
2069   throw ( SALOME::SALOME_Exception )
2070 {
2071   Unexpect aCatch(SALOME_SalomeException);
2072   if ( CORBA::is_nil( theMesh ) )
2073     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2074
2075   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2076   GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
2077
2078   // get a core mesh DS
2079   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2080   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2081   {
2082     ::SMESH_Mesh & mesh = meshServant->GetImpl();
2083     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2084     // find the element in mesh
2085     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2086       // find a shape id by the element
2087       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2088         // get a geom object by the shape id
2089         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2090         if ( geom->_is_nil() ) {
2091           // try to find a published sub-shape
2092           SALOMEDS::SObject_var mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2093           SALOMEDS::ChildIterator_var it;
2094           if ( !mainSO->_is_nil() )
2095             it = myCurrentStudy->NewChildIterator( mainSO );
2096           if ( !it->_is_nil() ) {
2097             for ( it->InitEx(true); it->More(); it->Next() ) {
2098               GEOM::GEOM_Object_var subGeom =
2099                 GEOM::GEOM_Object::_narrow( SObjectToObject( it->Value() ));
2100               if ( !subGeom->_is_nil() ) {
2101                 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2102                 if ( subList->length() == 1 && shapeID == subList[0] ) {
2103                   geom = subGeom;
2104                   break;
2105                 }
2106               }
2107             }
2108           }
2109         }
2110         if ( geom->_is_nil() ) {
2111           // explode
2112           GEOM::GEOM_IShapesOperations_var op =
2113             geomGen->GetIShapesOperations( GetCurrentStudyID() );
2114           if ( !op->_is_nil() )
2115             geom = op->GetSubShape( mainShape, shapeID );
2116         }
2117         if ( !geom->_is_nil() ) {
2118           GeomObjectToShape( geom ); // let geom client remember the found shape
2119           return geom._retn();
2120         }
2121       }
2122     }
2123   }
2124   return GEOM::GEOM_Object::_nil();
2125 }
2126
2127 //================================================================================
2128 /*!
2129  *  SMESH_Gen_i::Concatenate
2130  *
2131  *  Concatenate the given meshes into one mesh
2132  */
2133 //================================================================================
2134
2135 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::Concatenate(const SMESH::mesh_array& theMeshesArray,
2136                                                CORBA::Boolean           theUniteIdenticalGroups,
2137                                                CORBA::Boolean           theMergeNodesAndElements,
2138                                                CORBA::Double            theMergeTolerance)
2139   throw ( SALOME::SALOME_Exception )
2140 {
2141   return ConcatenateCommon(theMeshesArray,
2142                            theUniteIdenticalGroups,
2143                            theMergeNodesAndElements,
2144                            theMergeTolerance,
2145                            false);
2146 }
2147
2148 //================================================================================
2149 /*!
2150  *  SMESH_Gen_i::ConcatenateWithGroups
2151  *
2152  *  Concatenate the given meshes into one mesh
2153  *  Create the groups of all elements from initial meshes
2154  */
2155 //================================================================================
2156
2157 SMESH::SMESH_Mesh_ptr
2158 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::mesh_array& theMeshesArray,
2159                                    CORBA::Boolean           theUniteIdenticalGroups,
2160                                    CORBA::Boolean           theMergeNodesAndElements,
2161                                    CORBA::Double            theMergeTolerance)
2162   throw ( SALOME::SALOME_Exception )
2163 {
2164   return ConcatenateCommon(theMeshesArray,
2165                            theUniteIdenticalGroups,
2166                            theMergeNodesAndElements,
2167                            theMergeTolerance,
2168                            true);
2169 }
2170
2171 //================================================================================
2172 /*!
2173  *  SMESH_Gen_i::ConcatenateCommon
2174  *
2175  *  Concatenate the given meshes into one mesh
2176  */
2177 //================================================================================
2178
2179 SMESH::SMESH_Mesh_ptr
2180 SMESH_Gen_i::ConcatenateCommon(const SMESH::mesh_array& theMeshesArray,
2181                                CORBA::Boolean           theUniteIdenticalGroups,
2182                                CORBA::Boolean           theMergeNodesAndElements,
2183                                CORBA::Double            theMergeTolerance,
2184                                CORBA::Boolean           theCommonGroups)
2185   throw ( SALOME::SALOME_Exception )
2186 {
2187   typedef map<int, int> TIDsMap;
2188   typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
2189   typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
2190   typedef std::set<SMESHDS_GroupBase*> TGroups;
2191
2192   TPythonDump* pPythonDump = new TPythonDump;
2193   TPythonDump& aPythonDump = *pPythonDump; // prevent dump of called methods
2194
2195   // create mesh
2196   SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
2197
2198   SMESHDS_Mesh* aNewMeshDS = 0;
2199   if ( !aNewMesh->_is_nil() ) {
2200     SMESH_Mesh_i* aNewImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( aNewMesh ).in() );
2201     if ( aNewImpl ) {
2202       ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
2203       aNewMeshDS = aLocMesh.GetMeshDS();
2204
2205       TGroupsMap aGroupsMap;
2206       TListOfNewGroups aListOfNewGroups;
2207       SMESH_MeshEditor aNewEditor = ::SMESH_MeshEditor(&aLocMesh);
2208       SMESH::ListOfGroups_var aListOfGroups = new SMESH::ListOfGroups();
2209
2210       // loop on meshes
2211       for ( int i = 0; i < theMeshesArray.length(); i++) {
2212         SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i];
2213         if ( !anInitMesh->_is_nil() ) {
2214           SMESH_Mesh_i* anInitImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( anInitMesh ).in() );
2215           if ( anInitImpl ) {
2216             ::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
2217             aInitLocMesh.Load();
2218             SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
2219
2220             TIDsMap nodesMap;
2221             TIDsMap elemsMap;
2222
2223             // loop on elements of mesh
2224             SMDS_ElemIteratorPtr itElems = anInitMeshDS->elementsIterator();
2225             const SMDS_MeshElement* anElem = 0;
2226             const SMDS_MeshElement* aNewElem = 0;
2227             int anElemNbNodes = 0;
2228
2229             int anNbNodes   = 0;
2230             int anNbEdges   = 0;
2231             int anNbFaces   = 0;
2232             int anNbVolumes = 0;
2233             int aNbBalls    = 0;
2234
2235             SMESH::long_array_var anIDsNodes   = new SMESH::long_array();
2236             SMESH::long_array_var anIDsEdges   = new SMESH::long_array();
2237             SMESH::long_array_var anIDsFaces   = new SMESH::long_array();
2238             SMESH::long_array_var anIDsVolumes = new SMESH::long_array();
2239             SMESH::long_array_var anIDsBalls   = new SMESH::long_array();
2240
2241             if( theCommonGroups ) {
2242               anIDsNodes->length(   anInitMeshDS->NbNodes()   );
2243               anIDsEdges->length(   anInitMeshDS->NbEdges()   );
2244               anIDsFaces->length(   anInitMeshDS->NbFaces()   );
2245               anIDsVolumes->length( anInitMeshDS->NbVolumes() );
2246               anIDsBalls->length(   anInitMeshDS->NbBalls() );
2247             }
2248
2249             for ( int j = 0; itElems->more(); j++) {
2250               anElem = itElems->next();
2251               SMDSAbs_ElementType anElemType = anElem->GetType();
2252               anElemNbNodes = anElem->NbNodes();
2253               std::vector<const SMDS_MeshNode*> aNodesArray (anElemNbNodes);
2254
2255               // loop on nodes of element
2256               const SMDS_MeshNode* aNode = 0;
2257               const SMDS_MeshNode* aNewNode = 0;
2258               SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
2259
2260               for ( int k = 0; itNodes->more(); k++) {
2261                 aNode = static_cast<const SMDS_MeshNode*>(itNodes->next());
2262                 if ( nodesMap.find(aNode->GetID()) == nodesMap.end() ) {
2263                   aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2264                   nodesMap.insert( make_pair(aNode->GetID(), aNewNode->GetID()) );
2265                   if( theCommonGroups )
2266                     anIDsNodes[anNbNodes++] = aNewNode->GetID();
2267                 }
2268                 else
2269                   aNewNode = aNewMeshDS->FindNode( nodesMap.find(aNode->GetID())->second );
2270                 aNodesArray[k] = aNewNode;
2271               }//nodes loop
2272
2273               // creates a corresponding element on existent nodes in new mesh
2274               switch ( anElem->GetEntityType() ) {
2275               case SMDSEntity_Polyhedra:
2276                 if ( const SMDS_VtkVolume* aVolume =
2277                      dynamic_cast<const SMDS_VtkVolume*> (anElem))
2278                 {
2279                   aNewElem = aNewMeshDS->AddPolyhedralVolume(aNodesArray,
2280                                                              aVolume->GetQuantities());
2281                   elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
2282                   if( theCommonGroups )
2283                     anIDsVolumes[anNbVolumes++] = aNewElem->GetID();
2284                 }
2285                 break;
2286               case SMDSEntity_Ball:
2287                 if ( const SMDS_BallElement* aBall =
2288                      dynamic_cast<const SMDS_BallElement*> (anElem))
2289                 {
2290                   aNewElem = aNewEditor.AddElement(aNodesArray, SMDSAbs_Ball,
2291                                                    /*isPoly=*/false, /*id=*/0,
2292                                                    aBall->GetDiameter() );
2293                   elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
2294                   if( theCommonGroups )
2295                     anIDsBalls[aNbBalls++] = aNewElem->GetID();
2296                 }
2297                 break;
2298               default:
2299                 {
2300                   aNewElem = aNewEditor.AddElement(aNodesArray,
2301                                                    anElemType,
2302                                                    anElem->IsPoly());
2303                   elemsMap.insert(make_pair(anElem->GetID(), aNewElem->GetID()));
2304                   if( theCommonGroups ) {
2305                     if( anElemType == SMDSAbs_Edge )
2306                       anIDsEdges[anNbEdges++] = aNewElem->GetID();
2307                     else if( anElemType == SMDSAbs_Face )
2308                       anIDsFaces[anNbFaces++] = aNewElem->GetID();
2309                     else if( anElemType == SMDSAbs_Volume )
2310                       anIDsVolumes[anNbVolumes++] = aNewElem->GetID();
2311                   }
2312                 }
2313               }
2314             } //elems loop
2315
2316             // copy orphan nodes
2317             SMDS_NodeIteratorPtr  itNodes = anInitMeshDS->nodesIterator();
2318             while ( itNodes->more() )
2319             {
2320               const SMDS_MeshNode* aNode = itNodes->next();
2321               if ( aNode->NbInverseElements() == 0 )
2322               {
2323                 const SMDS_MeshNode* aNewNode =
2324                   aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2325                 nodesMap.insert( make_pair(aNode->GetID(), aNewNode->GetID()) );
2326                 if( theCommonGroups )
2327                   anIDsNodes[anNbNodes++] = aNewNode->GetID();
2328               }
2329             }
2330
2331
2332             aListOfGroups = anInitImpl->GetGroups();
2333             SMESH::SMESH_GroupBase_ptr aGroup;
2334
2335             // loop on groups of mesh
2336             SMESH::long_array_var anInitIDs = new SMESH::long_array();
2337             SMESH::long_array_var anNewIDs = new SMESH::long_array();
2338             SMESH::SMESH_Group_var aNewGroup;
2339
2340             SMESH::ElementType aGroupType;
2341             CORBA::String_var aGroupName;
2342             if ( theCommonGroups ) {
2343               for(aGroupType=SMESH::NODE;aGroupType<=SMESH::BALL;aGroupType=(SMESH::ElementType)(aGroupType+1)) {
2344                 string str = "Gr";
2345                 SALOMEDS::SObject_var aMeshSObj = ObjectToSObject( myCurrentStudy, anInitMesh );
2346                 if(aMeshSObj)
2347                   str += aMeshSObj->GetName();
2348                 str += "_";
2349
2350                 int anLen = 0;
2351
2352                 switch(aGroupType) {
2353                 case SMESH::NODE:
2354                   str += "Nodes";
2355                   anIDsNodes->length(anNbNodes);
2356                   anLen = anNbNodes;
2357                   break;
2358                 case SMESH::EDGE:
2359                   str += "Edges";
2360                   anIDsEdges->length(anNbEdges);
2361                   anLen = anNbEdges;
2362                   break;
2363                 case SMESH::FACE:
2364                   str += "Faces";
2365                   anIDsFaces->length(anNbFaces);
2366                   anLen = anNbFaces;
2367                   break;
2368                 case SMESH::VOLUME:
2369                   str += "Volumes";
2370                   anIDsVolumes->length(anNbVolumes);
2371                   anLen = anNbVolumes;
2372                   break;
2373                 case SMESH::BALL:
2374                   str += "Balls";
2375                   anIDsBalls->length(aNbBalls);
2376                   anLen = aNbBalls;
2377                   break;
2378                 default:
2379                   break;
2380                 }
2381
2382                 if(anLen) {
2383                   aGroupName = str.c_str();
2384
2385                   // add a new group in the mesh
2386                   aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2387
2388                   switch(aGroupType) {
2389                   case SMESH::NODE:
2390                     aNewGroup->Add( anIDsNodes );
2391                     break;
2392                   case SMESH::EDGE:
2393                     aNewGroup->Add( anIDsEdges );
2394                     break;
2395                   case SMESH::FACE:
2396                     aNewGroup->Add( anIDsFaces );
2397                     break;
2398                   case SMESH::VOLUME:
2399                     aNewGroup->Add( anIDsVolumes );
2400                     break;
2401                   case SMESH::BALL:
2402                     aNewGroup->Add( anIDsBalls );
2403                     break;
2404                   default:
2405                     break;
2406                   }
2407
2408                   aListOfNewGroups.clear();
2409                   aListOfNewGroups.push_back(aNewGroup);
2410                   aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
2411                 }
2412               }
2413             }
2414
2415             // check that current group name and type don't have identical ones in union mesh
2416             for (int iG = 0; iG < aListOfGroups->length(); iG++) {
2417               aGroup = aListOfGroups[iG];
2418               aListOfNewGroups.clear();
2419               aGroupType = aGroup->GetType();
2420               aGroupName = aGroup->GetName();
2421
2422               TGroupsMap::iterator anIter = aGroupsMap.find(make_pair(aGroupName, aGroupType));
2423
2424               // convert a list of IDs
2425               anInitIDs = aGroup->GetListOfID();
2426               anNewIDs->length(anInitIDs->length());
2427               if ( aGroupType == SMESH::NODE )
2428                 for (int j = 0; j < anInitIDs->length(); j++) {
2429                   anNewIDs[j] = nodesMap.find(anInitIDs[j])->second;
2430                 }
2431               else
2432                 for (int j = 0; j < anInitIDs->length(); j++) {
2433                   anNewIDs[j] = elemsMap.find(anInitIDs[j])->second;
2434                 }
2435
2436               // check that current group name and type don't have identical ones in union mesh
2437               if ( anIter == aGroupsMap.end() ) {
2438                 // add a new group in the mesh
2439                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2440                 // add elements into new group
2441                 aNewGroup->Add( anNewIDs );
2442
2443                 aListOfNewGroups.push_back(aNewGroup);
2444                 aGroupsMap.insert(make_pair( make_pair(aGroupName, aGroupType), aListOfNewGroups ));
2445               }
2446
2447               else if ( theUniteIdenticalGroups ) {
2448                 // unite identical groups
2449                 TListOfNewGroups& aNewGroups = anIter->second;
2450                 aNewGroups.front()->Add( anNewIDs );
2451               }
2452
2453               else {
2454                 // rename identical groups
2455                 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName);
2456                 aNewGroup->Add( anNewIDs );
2457
2458                 TListOfNewGroups& aNewGroups = anIter->second;
2459                 string aNewGroupName;
2460                 if (aNewGroups.size() == 1) {
2461                   aNewGroupName = string(aGroupName) + "_1";
2462                   aNewGroups.front()->SetName(aNewGroupName.c_str());
2463                 }
2464                 char aGroupNum[128];
2465                 sprintf(aGroupNum, "%u", aNewGroups.size()+1);
2466                 aNewGroupName = string(aGroupName) + "_" + string(aGroupNum);
2467                 aNewGroup->SetName(aNewGroupName.c_str());
2468                 aNewGroups.push_back(aNewGroup);
2469               }
2470             }//groups loop
2471           }
2472         }
2473       }//meshes loop
2474
2475       if (theMergeNodesAndElements) {
2476         // merge nodes
2477         TIDSortedNodeSet aMeshNodes; // no input nodes
2478         SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
2479         aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes );
2480         aNewEditor.MergeNodes( aGroupsOfNodes );
2481         // merge elements
2482         aNewEditor.MergeEqualElements();
2483       }
2484     }
2485   }
2486
2487   // Update Python script
2488   aPythonDump << aNewMesh << " = " << this;
2489   if( !theCommonGroups )
2490     aPythonDump << ".Concatenate(";
2491   else
2492     aPythonDump << ".ConcatenateWithGroups(";
2493   aPythonDump << "[";
2494   for ( int i = 0; i < theMeshesArray.length(); i++) {
2495     if (i > 0) aPythonDump << ", ";
2496     aPythonDump << theMeshesArray[i];
2497   }
2498   aPythonDump << "], ";
2499   aPythonDump << theUniteIdenticalGroups << ", "
2500               << theMergeNodesAndElements << ", "
2501               << TVar( theMergeTolerance ) << ")";
2502
2503   delete pPythonDump; // enable python dump from GetGroups()
2504
2505   // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2506   if ( !aNewMesh->_is_nil() )
2507   {
2508     SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
2509   }
2510
2511   // IPAL21468 Change icon of compound because it need not be computed.
2512   SALOMEDS::SObject_var aMeshSObj = ObjectToSObject( myCurrentStudy, aNewMesh );
2513   SetPixMap( aMeshSObj, "ICON_SMESH_TREE_MESH" );
2514
2515   if (aNewMeshDS)
2516     aNewMeshDS->Modified();
2517   return aNewMesh._retn();
2518 }
2519
2520 //================================================================================
2521 /*!
2522  * \brief Create a mesh by copying a part of another mesh
2523  *  \param meshPart - a part of mesh to copy
2524  *  \param toCopyGroups - to create in the new mesh groups
2525  *                        the copied elements belongs to
2526  *  \param toKeepIDs - to preserve IDs of the copied elements or not
2527  *  \retval SMESH::SMESH_Mesh_ptr - the new mesh
2528  */
2529 //================================================================================
2530
2531 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2532                                             const char*               meshName,
2533                                             CORBA::Boolean            toCopyGroups,
2534                                             CORBA::Boolean            toKeepIDs)
2535 {
2536   Unexpect aCatch(SALOME_SalomeException);
2537
2538   TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2539
2540   // 1. Get source mesh
2541
2542   if ( CORBA::is_nil( meshPart ))
2543     THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2544
2545   SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2546   SMESH_Mesh_i*       srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2547   if ( !srcMesh_i )
2548     THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2549
2550   SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2551
2552   // 2. Make a new mesh
2553
2554   SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2555   SMESH_Mesh_i*       newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2556   if ( !newMesh_i )
2557     THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2558   SALOMEDS::SObject_var meshSO = ObjectToSObject(myCurrentStudy, newMesh );
2559   if ( !meshSO->_is_nil() )
2560   {
2561     SetName( meshSO, meshName, "Mesh" );
2562     SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2563   }
2564   SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2565   ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2566
2567   // 3. Get elements to copy
2568
2569   SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2570   TIDSortedElemSet srcElems;
2571   SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2572   if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2573   {
2574     srcElemIt = srcMeshDS->elementsIterator();
2575     srcNodeIt = srcMeshDS->nodesIterator();
2576   }
2577   else
2578   {
2579     SMESH::long_array_var ids = meshPart->GetIDs();
2580     if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2581     {
2582       for (int i=0; i < ids->length(); i++)
2583         if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2584           srcElems.insert( elem );
2585     }
2586     else
2587     {
2588       for (int i=0; i < ids->length(); i++)
2589         if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2590           srcElems.insert( elem );
2591     }
2592     if ( srcElems.empty() )
2593       return newMesh._retn();
2594
2595     typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2596     srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2597   }
2598
2599   // 4. Copy elements
2600
2601   typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2602   TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2603   TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2604   int iN;
2605   const SMDS_MeshNode *nSrc, *nTgt;
2606   vector< const SMDS_MeshNode* > nodes;
2607   while ( srcElemIt->more() )
2608   {
2609     const SMDS_MeshElement * elem = srcElemIt->next();
2610     // find / add nodes
2611     nodes.resize( elem->NbNodes());
2612     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2613     if ( toKeepIDs ) {
2614       for ( iN = 0; nIt->more(); ++iN )
2615       {
2616         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2617         nTgt = newMeshDS->FindNode( nSrc->GetID());
2618         if ( !nTgt )
2619           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2620         nodes[ iN ] = nTgt;
2621       }
2622     }
2623     else {
2624       for ( iN = 0; nIt->more(); ++iN )
2625       {
2626         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2627         TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2628         if ( !n2n->second )
2629           n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2630         nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2631       }
2632     }
2633     // add elements
2634     if ( elem->GetType() != SMDSAbs_Node )
2635     {
2636       int ID = toKeepIDs ? elem->GetID() : 0;
2637       const SMDS_MeshElement * newElem;
2638       switch ( elem->GetEntityType() ) {
2639       case SMDSEntity_Polyhedra:
2640         newElem = editor.GetMeshDS()->
2641           AddPolyhedralVolumeWithID( nodes,
2642                                      static_cast<const SMDS_VtkVolume*>(elem)->GetQuantities(),
2643                                      ID);
2644         break;
2645       case SMDSEntity_Ball:
2646         newElem = editor.AddElement( nodes, SMDSAbs_Ball, false, ID,
2647                                      static_cast<const SMDS_BallElement*>(elem)->GetDiameter());
2648         break;
2649       default:
2650         newElem = editor.AddElement( nodes,elem->GetType(),elem->IsPoly(),ID);
2651
2652       if ( toCopyGroups && !toKeepIDs )
2653         e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2654       }
2655     }
2656   } // while ( srcElemIt->more() )
2657
2658   // 4(b). Copy free nodes
2659
2660   if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2661   {
2662     while ( srcNodeIt->more() )
2663     {
2664       nSrc = srcNodeIt->next();
2665       if ( nSrc->NbInverseElements() == 0 )
2666       {
2667         if ( toKeepIDs )
2668           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2669         else
2670           n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2671       }
2672     }
2673   }
2674
2675   // 5. Copy groups
2676
2677   int nbNewGroups = 0;
2678   if ( toCopyGroups )
2679   {
2680     SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2681     while ( gIt->more() )
2682     {
2683       SMESH_Group* group = gIt->next();
2684       const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2685
2686       // Check group type. We copy nodal groups containing nodes of copied element
2687       SMDSAbs_ElementType groupType = groupDS->GetType();
2688       if ( groupType != SMDSAbs_Node &&
2689            newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2690         continue; // group type differs from types of meshPart
2691
2692       // Find copied elements in the group
2693       vector< const SMDS_MeshElement* > groupElems;
2694       SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2695       if ( toKeepIDs )
2696       {
2697         const SMDS_MeshElement* foundElem;
2698         if ( groupType == SMDSAbs_Node )
2699         {
2700           while ( eIt->more() )
2701             if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2702               groupElems.push_back( foundElem );
2703         }
2704         else
2705         {
2706           while ( eIt->more() )
2707             if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2708               groupElems.push_back( foundElem );
2709         }
2710       }
2711       else
2712       {
2713         TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2714         if ( e2eMap.empty() ) continue;
2715         int minID = e2eMap.begin()->first->GetID();
2716         int maxID = e2eMap.rbegin()->first->GetID();
2717         TE2EMap::iterator e2e;
2718         while ( eIt->more() && groupElems.size() < e2eMap.size())
2719         {
2720           const SMDS_MeshElement* e = eIt->next();
2721           if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2722           if ((e2e = e2eMap.find( e )) != e2eMap.end())
2723             groupElems.push_back( e2e->second );
2724         }
2725       }
2726       // Make a new group
2727       if ( !groupElems.empty() )
2728       {
2729         SMESH::SMESH_Group_var newGroupObj =
2730           newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2731         if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2732         {
2733           SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2734           SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2735           for ( unsigned i = 0; i < groupElems.size(); ++i )
2736             smdsGroup.Add( groupElems[i] );
2737
2738           nbNewGroups++;
2739         }
2740       }
2741     }
2742   }
2743
2744   newMeshDS->Modified();
2745
2746   *pyDump << newMesh << " = " << this
2747           << ".CopyMesh( " << meshPart << ", "
2748           << "'" << meshName << "', "
2749           << toCopyGroups << ", "
2750           << toKeepIDs << ")";
2751
2752   delete pyDump; pyDump = 0; // allow dump in GetGroups()
2753
2754   if ( nbNewGroups > 0 ) // dump created groups
2755     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2756
2757   return newMesh._retn();
2758 }
2759
2760 //================================================================================
2761 /*!
2762  *  SMESH_Gen_i::GetMEDVersion
2763  *
2764  *  Get MED version of the file by its name
2765  */
2766 //================================================================================
2767 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2768                                           SMESH::MED_VERSION& theVersion)
2769 {
2770   theVersion = SMESH::MED_V2_1;
2771   MED::EVersion aVersion = MED::GetVersionId( theFileName );
2772   switch( aVersion ) {
2773     case MED::eV2_1     : theVersion = SMESH::MED_V2_1; return true;
2774     case MED::eV2_2     : theVersion = SMESH::MED_V2_2; return true;
2775     case MED::eVUnknown : return false;
2776   }
2777   return false;
2778 }
2779
2780 //================================================================================
2781 /*!
2782  *  SMESH_Gen_i::GetMeshNames
2783  *
2784  *  Get names of meshes defined in file with the specified name
2785  */
2786 //================================================================================
2787 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2788 {
2789   SMESH::string_array_var aResult = new SMESH::string_array();
2790   MED::PWrapper aMed = MED::CrWrapper( theFileName );
2791   MED::TErr anErr;
2792   MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2793   if( anErr >= 0 ) {
2794     aResult->length( aNbMeshes );
2795     for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2796       MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2797       aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2798     }
2799   }
2800   return aResult._retn();
2801 }
2802
2803 //=============================================================================
2804 /*!
2805  *  SMESH_Gen_i::Save
2806  *
2807  *  Save SMESH module's data
2808  */
2809 //=============================================================================
2810 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
2811                                       const char*              theURL,
2812                                       bool                     isMultiFile )
2813 {
2814   INFOS( "SMESH_Gen_i::Save" );
2815
2816   //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
2817   // san -- in case <myCurrentStudy> differs from theComponent's study,
2818   // use that of the component
2819   if ( myCurrentStudy->_is_nil() ||
2820     theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
2821     SetCurrentStudy( theComponent->GetStudy() );
2822
2823   // Store study contents as a set of python commands
2824   SavePython(myCurrentStudy);
2825
2826   StudyContext* myStudyContext = GetCurrentStudyContext();
2827
2828   // Declare a byte stream
2829   SALOMEDS::TMPFile_var aStreamFile;
2830
2831   // Obtain a temporary dir
2832   TCollection_AsciiString tmpDir =
2833     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2834
2835   // Create a sequence of files processed
2836   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
2837   aFileSeq->length( NUM_TMP_FILES );
2838
2839   TCollection_AsciiString aStudyName( "" );
2840   if ( isMultiFile )
2841     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2842
2843   // Set names of temporary files
2844   TCollection_AsciiString filename =
2845     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
2846   TCollection_AsciiString meshfile =
2847     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
2848   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
2849   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
2850   filename = tmpDir + filename;
2851   meshfile = tmpDir + meshfile;
2852
2853   HDFfile*    aFile;
2854   HDFdataset* aDataset;
2855   HDFgroup*   aTopGroup;
2856   HDFgroup*   aGroup;
2857   HDFgroup*   aSubGroup;
2858   HDFgroup*   aSubSubGroup;
2859   hdf_size    aSize[ 1 ];
2860
2861
2862   //Remove the files if they exist: BugID: 11225
2863 #ifndef WNT /* unix functionality */
2864   TCollection_AsciiString cmd("rm -f \"");
2865 #else /* windows */
2866   TCollection_AsciiString cmd("del /F \"");
2867 #endif
2868
2869   cmd+=filename;
2870   cmd+="\" \"";
2871   cmd+=meshfile;
2872   cmd+="\"";
2873   system(cmd.ToCString());
2874
2875   // MED writer to be used by storage process
2876   DriverMED_W_SMESHDS_Mesh myWriter;
2877   myWriter.SetFile( meshfile.ToCString() );
2878
2879   // IMP issue 20918
2880   // SetStoreName() to groups before storing hypotheses to let them refer to
2881   // groups using "store name", which is "Group <group_persistent_id>"
2882   {
2883     SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
2884     for ( ; itBig->More(); itBig->Next() ) {
2885       SALOMEDS::SObject_var gotBranch = itBig->Value();
2886       if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
2887         CORBA::Object_var anObject = SObjectToObject( gotBranch );
2888         if ( !CORBA::is_nil( anObject ) ) {
2889           SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
2890           if ( !myMesh->_is_nil() ) {
2891             myMesh->Load(); // load from study file if not yet done
2892             TPythonDump pd; // not to dump GetGroups()
2893             SMESH::ListOfGroups_var groups = myMesh->GetGroups();
2894             pd << ""; // to avoid optimizing pd out
2895             for ( int i = 0; i < groups->length(); ++i )
2896             {
2897               SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
2898               if ( grImpl )
2899               {
2900                 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
2901                 int anId = myStudyContext->findId( string( objStr.in() ) );
2902                 char grpName[ 30 ];
2903                 sprintf( grpName, "Group %d", anId );
2904                 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
2905                 aGrpBaseDS->SetStoreName( grpName );
2906               }
2907             }
2908           }
2909         }
2910       }
2911     }
2912   }
2913
2914   // Write data
2915   // ---> create HDF file
2916   aFile = new HDFfile( (char*) filename.ToCString() );
2917   aFile->CreateOnDisk();
2918
2919   // --> iterator for top-level objects
2920   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
2921   for ( ; itBig->More(); itBig->Next() ) {
2922     SALOMEDS::SObject_var gotBranch = itBig->Value();
2923
2924     // --> hypotheses root branch (only one for the study)
2925     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
2926       // create hypotheses root HDF group
2927       aTopGroup = new HDFgroup( "Hypotheses", aFile );
2928       aTopGroup->CreateOnDisk();
2929
2930       // iterator for all hypotheses
2931       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
2932       for ( ; it->More(); it->Next() ) {
2933         SALOMEDS::SObject_var mySObject = it->Value();
2934         CORBA::Object_var anObject = SObjectToObject( mySObject );
2935         if ( !CORBA::is_nil( anObject ) ) {
2936           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
2937           if ( !myHyp->_is_nil() ) {
2938             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2939             if ( myImpl ) {
2940               string hypname = string( myHyp->GetName() );
2941               string libname = string( myHyp->GetLibName() );
2942               // BUG SWP13062
2943               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
2944               // WNT and ".so" for X-system) must be deleted
2945               int libname_len = libname.length();
2946 #ifdef WNT
2947               if( libname_len > 4 )
2948                 libname.resize( libname_len - 4 );
2949 #else
2950               // PAL17753 (Regresion: missing hypothesis in restored study)
2951               // "lib" also should be removed from the beginning
2952               //if( libname_len > 3 )
2953                 //libname.resize( libname_len - 3 );
2954               if( libname_len > 6 )
2955                 libname = libname.substr( 3, libname_len - 3 - 3 );
2956 #endif
2957               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2958               int    id      = myStudyContext->findId( string( objStr.in() ) );
2959               string hypdata = string( myImpl->SaveTo() );
2960
2961               // for each hypothesis create HDF group basing on its id
2962               char hypGrpName[30];
2963               sprintf( hypGrpName, "Hypothesis %d", id );
2964               aGroup = new HDFgroup( hypGrpName, aTopGroup );
2965               aGroup->CreateOnDisk();
2966               // --> type name of hypothesis
2967               aSize[ 0 ] = hypname.length() + 1;
2968               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
2969               aDataset->CreateOnDisk();
2970               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
2971               aDataset->CloseOnDisk();
2972               // --> server plugin library name of hypothesis
2973               aSize[ 0 ] = libname.length() + 1;
2974               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
2975               aDataset->CreateOnDisk();
2976               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
2977               aDataset->CloseOnDisk();
2978               // --> persistent data of hypothesis
2979               aSize[ 0 ] = hypdata.length() + 1;
2980               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
2981               aDataset->CreateOnDisk();
2982               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
2983               aDataset->CloseOnDisk();
2984               // close hypothesis HDF group
2985               aGroup->CloseOnDisk();
2986             }
2987           }
2988         }
2989       }
2990       // close hypotheses root HDF group
2991       aTopGroup->CloseOnDisk();
2992     }
2993     // --> algorithms root branch (only one for the study)
2994     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
2995       // create algorithms root HDF group
2996       aTopGroup = new HDFgroup( "Algorithms", aFile );
2997       aTopGroup->CreateOnDisk();
2998
2999       // iterator for all algorithms
3000       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
3001       for ( ; it->More(); it->Next() ) {
3002         SALOMEDS::SObject_var mySObject = it->Value();
3003         CORBA::Object_var anObject = SObjectToObject( mySObject );
3004         if ( !CORBA::is_nil( anObject ) ) {
3005           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3006           if ( !myHyp->_is_nil() ) {
3007             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3008             if ( myImpl ) {
3009               string hypname = string( myHyp->GetName() );
3010               string libname = string( myHyp->GetLibName() );
3011               // BUG SWP13062
3012               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3013               // WNT and ".so" for X-system) must be deleted
3014               int libname_len = libname.length();
3015 #ifdef WNT
3016               if( libname_len > 4 )
3017                 libname.resize( libname_len - 4 );
3018 #else
3019               // PAL17753 (Regresion: missing hypothesis in restored study)
3020               // "lib" also should be removed from the beginning
3021               //if( libname_len > 3 )
3022                 //libname.resize( libname_len - 3 );
3023               if( libname_len > 6 )
3024                 libname = libname.substr( 3, libname_len - 3 - 3 );
3025 #endif
3026               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3027               int    id      = myStudyContext->findId( string( objStr.in() ) );
3028               string hypdata = string( myImpl->SaveTo() );
3029
3030               // for each algorithm create HDF group basing on its id
3031               char hypGrpName[30];
3032               sprintf( hypGrpName, "Algorithm %d", id );
3033               aGroup = new HDFgroup( hypGrpName, aTopGroup );
3034               aGroup->CreateOnDisk();
3035               // --> type name of algorithm
3036               aSize[0] = hypname.length() + 1;
3037               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3038               aDataset->CreateOnDisk();
3039               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3040               aDataset->CloseOnDisk();
3041               // --> server plugin library name of hypothesis
3042               aSize[0] = libname.length() + 1;
3043               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3044               aDataset->CreateOnDisk();
3045               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3046               aDataset->CloseOnDisk();
3047               // --> persistent data of algorithm
3048               aSize[0] = hypdata.length() + 1;
3049               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3050               aDataset->CreateOnDisk();
3051               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3052               aDataset->CloseOnDisk();
3053               // close algorithm HDF group
3054               aGroup->CloseOnDisk();
3055             }
3056           }
3057         }
3058       }
3059       // close algorithms root HDF group
3060       aTopGroup->CloseOnDisk();
3061     }
3062     // --> mesh objects roots branches
3063     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3064       CORBA::Object_var anObject = SObjectToObject( gotBranch );
3065       if ( !CORBA::is_nil( anObject ) ) {
3066         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3067         if ( !myMesh->_is_nil() ) {
3068           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3069           if ( myImpl ) {
3070             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3071             int id = myStudyContext->findId( string( objStr.in() ) );
3072             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3073             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3074             bool hasShape = myLocMesh.HasShapeToMesh();
3075
3076             // for each mesh open the HDF group basing on its id
3077             char meshGrpName[ 30 ];
3078             sprintf( meshGrpName, "Mesh %d", id );
3079             aTopGroup = new HDFgroup( meshGrpName, aFile );
3080             aTopGroup->CreateOnDisk();
3081
3082             // --> put dataset to hdf file which is a flag that mesh has data
3083             string strHasData = "0";
3084             // check if the mesh is not empty
3085             if ( mySMESHDSMesh->NbNodes() > 0 ) {
3086               // write mesh data to med file
3087               myWriter.SetMesh( mySMESHDSMesh );
3088               myWriter.SetMeshId( id );
3089               strHasData = "1";
3090             }
3091             aSize[ 0 ] = strHasData.length() + 1;
3092             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3093             aDataset->CreateOnDisk();
3094             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3095             aDataset->CloseOnDisk();
3096
3097             // ouv : NPAL12872
3098             // for each mesh open the HDF group basing on its auto color parameter
3099             char meshAutoColorName[ 30 ];
3100             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3101             int anAutoColor[1];
3102             anAutoColor[0] = myImpl->GetAutoColor();
3103             aSize[ 0 ] = 1;
3104             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3105             aDataset->CreateOnDisk();
3106             aDataset->WriteOnDisk( anAutoColor );
3107             aDataset->CloseOnDisk();
3108
3109             // issue 0020693. Store _isModified flag
3110             int isModified = myLocMesh.GetIsModified();
3111             aSize[ 0 ] = 1;
3112             aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3113             aDataset->CreateOnDisk();
3114             aDataset->WriteOnDisk( &isModified );
3115             aDataset->CloseOnDisk();
3116
3117             // issue 20918. Store Persistent Id of SMESHDS_Mesh
3118             int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3119             aSize[ 0 ] = 1;
3120             aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3121             aDataset->CreateOnDisk();
3122             aDataset->WriteOnDisk( &meshPersistentId );
3123             aDataset->CloseOnDisk();
3124
3125             // write reference on a shape if exists
3126             SALOMEDS::SObject_var myRef;
3127             bool shapeRefFound = false;
3128             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
3129             if ( found ) {
3130               SALOMEDS::SObject_var myShape;
3131               bool ok = myRef->ReferencedObject( myShape );
3132               if ( ok ) {
3133                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
3134                 string myRefOnObject = myShape->GetID();
3135                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
3136                   aSize[ 0 ] = myRefOnObject.length() + 1;
3137                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3138                   aDataset->CreateOnDisk();
3139                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3140                   aDataset->CloseOnDisk();
3141                 }
3142               }
3143             }
3144
3145             // write applied hypotheses if exist
3146             SALOMEDS::SObject_var myHypBranch;
3147             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
3148             if ( found && !shapeRefFound && hasShape) { // remove applied hyps
3149               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3150             }
3151             if ( found && (shapeRefFound || !hasShape) ) {
3152               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3153               aGroup->CreateOnDisk();
3154
3155               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
3156               int hypNb = 0;
3157               for ( ; it->More(); it->Next() ) {
3158                 SALOMEDS::SObject_var mySObject = it->Value();
3159                 SALOMEDS::SObject_var myRefOnHyp;
3160                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
3161                 if ( ok ) {
3162                   // san - it is impossible to recover applied hypotheses
3163                   //       using their entries within Load() method,
3164                   // for there are no AttributeIORs in the study when Load() is working.
3165                   // Hence, it is better to store persistent IDs of hypotheses as references to them
3166
3167                   //string myRefOnObject = myRefOnHyp->GetID();
3168                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3169                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3170                   int id = myStudyContext->findId( string( objStr.in() ) );
3171                   //if ( myRefOnObject.length() > 0 ) {
3172                   //aSize[ 0 ] = myRefOnObject.length() + 1;
3173                   char hypName[ 30 ], hypId[ 30 ];
3174                   sprintf( hypName, "Hyp %d", ++hypNb );
3175                   sprintf( hypId, "%d", id );
3176                   aSize[ 0 ] = strlen( hypId ) + 1;
3177                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3178                   aDataset->CreateOnDisk();
3179                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3180                   aDataset->WriteOnDisk( hypId );
3181                   aDataset->CloseOnDisk();
3182                   //}
3183                 }
3184               }
3185               aGroup->CloseOnDisk();
3186             }
3187
3188             // write applied algorithms if exist
3189             SALOMEDS::SObject_var myAlgoBranch;
3190             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
3191             if ( found && !shapeRefFound && hasShape) { // remove applied algos
3192               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3193             }
3194             if ( found && (shapeRefFound || !hasShape)) {
3195               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3196               aGroup->CreateOnDisk();
3197
3198               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
3199               int algoNb = 0;
3200               for ( ; it->More(); it->Next() ) {
3201                 SALOMEDS::SObject_var mySObject = it->Value();
3202                 SALOMEDS::SObject_var myRefOnAlgo;
3203                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
3204                 if ( ok ) {
3205                   // san - it is impossible to recover applied algorithms
3206                   //       using their entries within Load() method,
3207                   // for there are no AttributeIORs in the study when Load() is working.
3208                   // Hence, it is better to store persistent IDs of algorithms as references to them
3209
3210                   //string myRefOnObject = myRefOnAlgo->GetID();
3211                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3212                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3213                   int id = myStudyContext->findId( string( objStr.in() ) );
3214                   //if ( myRefOnObject.length() > 0 ) {
3215                   //aSize[ 0 ] = myRefOnObject.length() + 1;
3216                   char algoName[ 30 ], algoId[ 30 ];
3217                   sprintf( algoName, "Algo %d", ++algoNb );
3218                   sprintf( algoId, "%d", id );
3219                   aSize[ 0 ] = strlen( algoId ) + 1;
3220                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3221                   aDataset->CreateOnDisk();
3222                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3223                   aDataset->WriteOnDisk( algoId );
3224                   aDataset->CloseOnDisk();
3225                   //}
3226                 }
3227               }
3228               aGroup->CloseOnDisk();
3229             }
3230
3231             // --> submesh objects sub-branches
3232
3233             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3234               SALOMEDS::SObject_var mySubmeshBranch;
3235               found = gotBranch->FindSubObject( i, mySubmeshBranch );
3236
3237               if ( found ) // check if there is shape reference in submeshes
3238               {
3239                 bool hasShapeRef = false;
3240                 SALOMEDS::ChildIterator_var itSM =
3241                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
3242                 for ( ; itSM->More(); itSM->Next() ) {
3243                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
3244                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
3245                     mySubRef->ReferencedObject( myShape );
3246                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3247                     hasShapeRef = true;
3248                   else
3249                   { // remove one submesh
3250                     if ( shapeRefFound )
3251                     { // unassign hypothesis
3252                       SMESH::SMESH_subMesh_var mySubMesh =
3253                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3254                       if ( !mySubMesh->_is_nil() ) {
3255                         int shapeID = mySubMesh->GetId();
3256                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3257                         const list<const SMESHDS_Hypothesis*>& hypList =
3258                           mySMESHDSMesh->GetHypothesis( S );
3259                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3260                         while ( hyp != hypList.end() ) {
3261                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
3262                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3263                         }
3264                       }
3265                     }
3266                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3267                   }
3268                 } // loop on submeshes of a type
3269                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3270                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3271                   found = false;
3272                 }
3273               }  // end check if there is shape reference in submeshes
3274               if ( found ) {
3275                 char name_meshgroup[ 30 ];
3276                 if ( i == GetSubMeshOnVertexTag() )
3277                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
3278                 else if ( i == GetSubMeshOnEdgeTag() )
3279                   strcpy( name_meshgroup, "SubMeshes On Edge" );
3280                 else if ( i == GetSubMeshOnWireTag() )
3281                   strcpy( name_meshgroup, "SubMeshes On Wire" );
3282                 else if ( i == GetSubMeshOnFaceTag() )
3283                   strcpy( name_meshgroup, "SubMeshes On Face" );
3284                 else if ( i == GetSubMeshOnShellTag() )
3285                   strcpy( name_meshgroup, "SubMeshes On Shell" );
3286                 else if ( i == GetSubMeshOnSolidTag() )
3287                   strcpy( name_meshgroup, "SubMeshes On Solid" );
3288                 else if ( i == GetSubMeshOnCompoundTag() )
3289                   strcpy( name_meshgroup, "SubMeshes On Compound" );
3290
3291                 // for each type of submeshes create container HDF group
3292                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3293                 aGroup->CreateOnDisk();
3294
3295                 // iterator for all submeshes of given type
3296                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
3297                 for ( ; itSM->More(); itSM->Next() ) {
3298                   SALOMEDS::SObject_var mySObject = itSM->Value();
3299                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3300                   if ( !CORBA::is_nil( anSubObject ))
3301                   {
3302                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3303                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3304                     int subid = myStudyContext->findId( string( objStr.in() ) );
3305
3306                     // for each mesh open the HDF group basing on its id
3307                     char submeshGrpName[ 30 ];
3308                     sprintf( submeshGrpName, "SubMesh %d", subid );
3309                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3310                     aSubGroup->CreateOnDisk();
3311
3312                     // write reference on a shape, already checked if it exists
3313                     SALOMEDS::SObject_var mySubRef, myShape;
3314                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
3315                       mySubRef->ReferencedObject( myShape );
3316                     string myRefOnObject = myShape->GetID();
3317                     if ( myRefOnObject.length() > 0 ) {
3318                       aSize[ 0 ] = myRefOnObject.length() + 1;
3319                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3320                       aDataset->CreateOnDisk();
3321                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3322                       aDataset->CloseOnDisk();
3323                     }
3324
3325                     // write applied hypotheses if exist
3326                     SALOMEDS::SObject_var mySubHypBranch;
3327                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
3328                     if ( found ) {
3329                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3330                       aSubSubGroup->CreateOnDisk();
3331
3332                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
3333                       int hypNb = 0;
3334                       for ( ; it->More(); it->Next() ) {
3335                         SALOMEDS::SObject_var mySubSObject = it->Value();
3336                         SALOMEDS::SObject_var myRefOnHyp;
3337                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
3338                         if ( ok ) {
3339                           //string myRefOnObject = myRefOnHyp->GetID();
3340                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3341                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3342                           int id = myStudyContext->findId( string( objStr.in() ) );
3343                           //if ( myRefOnObject.length() > 0 ) {
3344                           //aSize[ 0 ] = myRefOnObject.length() + 1;
3345                           char hypName[ 30 ], hypId[ 30 ];
3346                           sprintf( hypName, "Hyp %d", ++hypNb );
3347                           sprintf( hypId, "%d", id );
3348                           aSize[ 0 ] = strlen( hypId ) + 1;
3349                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3350                           aDataset->CreateOnDisk();
3351                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3352                           aDataset->WriteOnDisk( hypId );
3353                           aDataset->CloseOnDisk();
3354                           //}
3355                         }
3356                       }
3357                       aSubSubGroup->CloseOnDisk();
3358                     }
3359
3360                     // write applied algorithms if exist
3361                     SALOMEDS::SObject_var mySubAlgoBranch;
3362                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
3363                     if ( found ) {
3364                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3365                       aSubSubGroup->CreateOnDisk();
3366
3367                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
3368                       int algoNb = 0;
3369                       for ( ; it->More(); it->Next() ) {
3370                         SALOMEDS::SObject_var mySubSObject = it->Value();
3371                         SALOMEDS::SObject_var myRefOnAlgo;
3372                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
3373                         if ( ok ) {
3374                           //string myRefOnObject = myRefOnAlgo->GetID();
3375                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3376                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3377                           int id = myStudyContext->findId( string( objStr.in() ) );
3378                           //if ( myRefOnObject.length() > 0 ) {
3379                           //aSize[ 0 ] = myRefOnObject.length() + 1;
3380                           char algoName[ 30 ], algoId[ 30 ];
3381                           sprintf( algoName, "Algo %d", ++algoNb );
3382                           sprintf( algoId, "%d", id );
3383                           aSize[ 0 ] = strlen( algoId ) + 1;
3384                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3385                           aDataset->CreateOnDisk();
3386                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3387                           aDataset->WriteOnDisk( algoId );
3388                           aDataset->CloseOnDisk();
3389                           //}
3390                         }
3391                       }
3392                       aSubSubGroup->CloseOnDisk();
3393                     }
3394                     // close submesh HDF group
3395                     aSubGroup->CloseOnDisk();
3396                   }
3397                 }
3398                 // close container of submeshes by type HDF group
3399                 aGroup->CloseOnDisk();
3400               }
3401             }
3402             // All sub-meshes will be stored in MED file
3403             // .. will NOT (PAL 12992)
3404             //if ( shapeRefFound )
3405             //myWriter.AddAllSubMeshes();
3406
3407             // store submesh order if any
3408             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3409             if ( theOrderIds.size() ) {
3410               char order_list[ 30 ];
3411               strcpy( order_list, "Mesh Order" );
3412               // count number of submesh ids
3413               int nbIDs = 0;
3414               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3415               for ( ; idIt != theOrderIds.end(); idIt++ )
3416                 nbIDs += (*idIt).size();
3417               // number of values = number of IDs +
3418               //                    number of lists (for separators) - 1
3419               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3420               idIt = theOrderIds.begin();
3421               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3422                 const TListOfInt& idList = *idIt;
3423                 if (idIt != theOrderIds.begin()) // not first list
3424                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3425                 // dump submesh ids from current list
3426                 TListOfInt::const_iterator id_smId = idList.begin();
3427                 for( ; id_smId != idList.end(); id_smId++ )
3428                   smIDs[ i++ ] = *id_smId;
3429               }
3430               // write HDF group
3431               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3432
3433               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3434               aDataset->CreateOnDisk();
3435               aDataset->WriteOnDisk( smIDs );
3436               aDataset->CloseOnDisk();
3437               //
3438               delete[] smIDs;
3439             }
3440
3441             // groups root sub-branch
3442             SALOMEDS::SObject_var myGroupsBranch;
3443             for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
3444               found = gotBranch->FindSubObject( i, myGroupsBranch );
3445               if ( found ) {
3446                 char name_group[ 30 ];
3447                 if ( i == GetNodeGroupsTag() )
3448                   strcpy( name_group, "Groups of Nodes" );
3449                 else if ( i == GetEdgeGroupsTag() )
3450                   strcpy( name_group, "Groups of Edges" );
3451                 else if ( i == GetFaceGroupsTag() )
3452                   strcpy( name_group, "Groups of Faces" );
3453                 else if ( i == GetVolumeGroupsTag() )
3454                   strcpy( name_group, "Groups of Volumes" );
3455                 else if ( i == Get0DElementsGroupsTag() )
3456                   strcpy( name_group, "Groups of 0D Elements" );
3457                 else if ( i == GetBallElementsGroupsTag() )
3458                   strcpy( name_group, "Groups of Balls" );
3459
3460                 aGroup = new HDFgroup( name_group, aTopGroup );
3461                 aGroup->CreateOnDisk();
3462
3463                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
3464                 for ( ; it->More(); it->Next() ) {
3465                   SALOMEDS::SObject_var mySObject = it->Value();
3466                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3467                   if ( !CORBA::is_nil( aSubObject ) ) {
3468                     SMESH_GroupBase_i* myGroupImpl =
3469                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3470                     if ( !myGroupImpl )
3471                       continue;
3472                     SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3473                     if ( !aGrpBaseDS )
3474                       continue;
3475
3476                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3477                     int anId = myStudyContext->findId( string( objStr.in() ) );
3478
3479                     // For each group, create a dataset named "Group <group_persistent_id>"
3480                     // and store the group's user name into it
3481                     const char* grpName = aGrpBaseDS->GetStoreName();
3482                     char* aUserName = myGroupImpl->GetName();
3483                     aSize[ 0 ] = strlen( aUserName ) + 1;
3484
3485                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3486                     aDataset->CreateOnDisk();
3487                     aDataset->WriteOnDisk( aUserName );
3488                     aDataset->CloseOnDisk();
3489
3490                     // ouv : NPAL12872
3491                     // For each group, create a dataset named "Group <group_persistent_id> Color"
3492                     // and store the group's color into it
3493                     char grpColorName[ 30 ];
3494                     sprintf( grpColorName, "ColorGroup %d", anId );
3495                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
3496                     double anRGB[3];
3497                     anRGB[ 0 ] = aColor.R;
3498                     anRGB[ 1 ] = aColor.G;
3499                     anRGB[ 2 ] = aColor.B;
3500                     aSize[ 0 ] = 3;
3501                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3502                     aDataset->CreateOnDisk();
3503                     aDataset->WriteOnDisk( anRGB );
3504                     aDataset->CloseOnDisk();
3505
3506                     // Pass SMESHDS_Group to MED writer
3507                     SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3508                     if ( aGrpDS )
3509                       myWriter.AddGroup( aGrpDS );
3510
3511                     // write reference on a shape if exists
3512                     SMESHDS_GroupOnGeom* aGeomGrp =
3513                       dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3514                     if ( aGeomGrp ) {
3515                       SALOMEDS::SObject_var mySubRef, myShape;
3516                       if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
3517                           mySubRef->ReferencedObject( myShape ) &&
3518                           !CORBA::is_nil( myShape->GetObject() ))
3519                       {
3520                         string myRefOnObject = myShape->GetID();
3521                         if ( myRefOnObject.length() > 0 ) {
3522                           char aRefName[ 30 ];
3523                           sprintf( aRefName, "Ref on shape %d", anId);
3524                           aSize[ 0 ] = myRefOnObject.length() + 1;
3525                           aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3526                           aDataset->CreateOnDisk();
3527                           aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3528                           aDataset->CloseOnDisk();
3529                         }
3530                       }
3531                       else // shape ref is invalid:
3532                       {
3533                         // save a group on geometry as ordinary group
3534                         myWriter.AddGroup( aGeomGrp );
3535                       }
3536                     }
3537                     else if ( SMESH_GroupOnFilter_i* aFilterGrp_i = 
3538                               dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3539                     {
3540                       std::string str = aFilterGrp_i->FilterToString();
3541                       std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3542                       aSize[ 0 ] = str.length() + 1;
3543                       aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3544                       aDataset->CreateOnDisk();
3545                       aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3546                       aDataset->CloseOnDisk();
3547                     }
3548                   }
3549                 }
3550                 aGroup->CloseOnDisk();
3551               }
3552             } // loop on groups
3553
3554             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3555             {
3556               // Flush current mesh information into MED file
3557               myWriter.Perform();
3558
3559               // save info on nb of elements
3560               SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
3561
3562               // maybe a shape was deleted in the study
3563               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3564                 TopoDS_Shape nullShape;
3565                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3566               }
3567
3568               if ( !mySMESHDSMesh->SubMeshes().empty() )
3569               {
3570                 // Store submeshes
3571                 // ----------------
3572                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3573                 aGroup->CreateOnDisk();
3574
3575                 // each element belongs to one or none submesh,
3576                 // so for each node/element, we store a submesh ID
3577
3578                 // Make maps of submesh IDs of elements sorted by element IDs
3579                 typedef int TElemID;
3580                 typedef int TSubMID;
3581                 map< TElemID, TSubMID > eId2smId, nId2smId;
3582                 map< TElemID, TSubMID >::iterator hint; // insertion to map is done before hint
3583                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
3584                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
3585                 SMDS_NodeIteratorPtr itNode;
3586                 SMDS_ElemIteratorPtr itElem;
3587                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
3588                 {
3589                   TSubMID          aSubMeID = itSubM->first;
3590                   SMESHDS_SubMesh* aSubMesh = itSubM->second;
3591                   if ( aSubMesh->IsComplexSubmesh() )
3592                     continue; // submesh containing other submeshs
3593                   // nodes
3594                   hint = nId2smId.begin(); // optimize insertion basing on increasing order of elem Ids in submesh
3595                   for ( itNode = aSubMesh->GetNodes(); itNode->more(); ++hint)
3596                     hint = nId2smId.insert( hint, make_pair( itNode->next()->GetID(), aSubMeID ));
3597                   // elements
3598                   hint = eId2smId.begin();
3599                   for ( itElem = aSubMesh->GetElements(); itElem->more(); ++hint)
3600                     hint = eId2smId.insert( hint, make_pair( itElem->next()->GetID(), aSubMeID ));
3601                 }
3602
3603                 // Care of elements that are not on submeshes
3604                 if ( mySMESHDSMesh->NbNodes() != nId2smId.size() ) {
3605                   for ( itNode = mySMESHDSMesh->nodesIterator(); itNode->more(); )
3606                     /*  --- stl_map.h says : */
3607                     /*  A %map relies on unique keys and thus a %pair is only inserted if its */
3608                     /*  first element (the key) is not already present in the %map.           */
3609                     nId2smId.insert( make_pair( itNode->next()->GetID(), 0 ));
3610                 }
3611                 int nbElems = mySMESHDSMesh->NbEdges() + mySMESHDSMesh->NbFaces() + mySMESHDSMesh->NbVolumes();
3612                 if ( nbElems != eId2smId.size() ) {
3613                   for ( itElem = mySMESHDSMesh->elementsIterator(); itElem->more(); )
3614                     eId2smId.insert( make_pair( itElem->next()->GetID(), 0 ));
3615                 }
3616
3617                 // Store submesh IDs
3618                 for ( int isNode = 0; isNode < 2; ++isNode )
3619                 {
3620                   map< TElemID, TSubMID >& id2smId = isNode ? nId2smId : eId2smId;
3621                   if ( id2smId.empty() ) continue;
3622                   map< TElemID, TSubMID >::const_iterator id_smId = id2smId.begin();
3623                   // make and fill array of submesh IDs
3624                   int* smIDs = new int [ id2smId.size() ];
3625                   for ( int i = 0; id_smId != id2smId.end(); ++id_smId, ++i )
3626                     smIDs[ i ] = id_smId->second;
3627                   // write HDF group
3628                   aSize[ 0 ] = id2smId.size();
3629                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3630                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3631                   aDataset->CreateOnDisk();
3632                   aDataset->WriteOnDisk( smIDs );
3633                   aDataset->CloseOnDisk();
3634                   //
3635                   delete[] smIDs;
3636                 }
3637
3638                 aGroup->CloseOnDisk();
3639
3640                 // Store node positions on sub-shapes (SMDS_Position):
3641                 // ----------------------------------------------------
3642
3643                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3644                 aGroup->CreateOnDisk();
3645
3646                 // in aGroup, create 5 datasets to contain:
3647                 // "Nodes on Edges" - ID of node on edge
3648                 // "Edge positions" - U parameter on node on edge
3649                 // "Nodes on Faces" - ID of node on face
3650                 // "Face U positions" - U parameter of node on face
3651                 // "Face V positions" - V parameter of node on face
3652
3653                 // Find out nb of nodes on edges and faces
3654                 // Collect corresponing sub-meshes
3655                 int nbEdgeNodes = 0, nbFaceNodes = 0;
3656                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3657                 // loop on SMESHDS_SubMesh'es
3658                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
3659                 {
3660                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
3661                   if ( aSubMesh->IsComplexSubmesh() )
3662                     continue; // submesh containing other submeshs
3663                   int nbNodes = aSubMesh->NbNodes();
3664                   if ( nbNodes == 0 ) continue;
3665
3666                   int aShapeID = (*itSubM).first;
3667                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3668                     continue;
3669                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3670                   // write only SMDS_FacePosition and SMDS_EdgePosition
3671                   switch ( aShapeType ) {
3672                   case TopAbs_FACE:
3673                     nbFaceNodes += nbNodes;
3674                     aFaceSM.push_back( aSubMesh );
3675                     break;
3676                   case TopAbs_EDGE:
3677                     nbEdgeNodes += nbNodes;
3678                     aEdgeSM.push_back( aSubMesh );
3679                     break;
3680                   default:
3681                     continue;
3682                   }
3683                 }
3684                 // Treat positions on edges or faces
3685                 for ( int onFace = 0; onFace < 2; onFace++ )
3686                 {
3687                   // Create arrays to store in datasets
3688                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3689                   if (!nbNodes) continue;
3690                   int* aNodeIDs = new int [ nbNodes ];
3691                   double* aUPos = new double [ nbNodes ];
3692                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3693
3694                   // Fill arrays
3695                   // loop on sub-meshes
3696                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3697                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3698                   for ( ; itSM != pListSM->end(); itSM++ )
3699                   {
3700                     SMESHDS_SubMesh* aSubMesh = (*itSM);
3701
3702                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3703                     // loop on nodes in aSubMesh
3704                     while ( itNode->more() )
3705                     {
3706                       //node ID
3707                       const SMDS_MeshNode* node = itNode->next();
3708                       aNodeIDs [ iNode ] = node->GetID();
3709
3710                       // Position
3711                       const SMDS_PositionPtr pos = node->GetPosition();
3712                       if ( onFace ) { // on FACE
3713                         const SMDS_FacePosition* fPos =
3714                           dynamic_cast<const SMDS_FacePosition*>( pos );
3715                         if ( fPos ) {
3716                           aUPos[ iNode ] = fPos->GetUParameter();
3717                           aVPos[ iNode ] = fPos->GetVParameter();
3718                           iNode++;
3719                         }
3720                         else
3721                           nbNodes--;
3722                       }
3723                       else { // on EDGE
3724                         const SMDS_EdgePosition* ePos =
3725                           dynamic_cast<const SMDS_EdgePosition*>( pos );
3726                         if ( ePos ) {
3727                           aUPos[ iNode ] = ePos->GetUParameter();
3728                           iNode++;
3729                         }
3730                         else
3731                           nbNodes--;
3732                       }
3733                     } // loop on nodes in aSubMesh
3734                   } // loop on sub-meshes
3735
3736                   // Write datasets
3737                   if ( nbNodes )
3738                   {
3739                     aSize[ 0 ] = nbNodes;
3740                     // IDS
3741                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3742                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3743                     aDataset->CreateOnDisk();
3744                     aDataset->WriteOnDisk( aNodeIDs );
3745                     aDataset->CloseOnDisk();
3746
3747                     // U Positions
3748                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
3749                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3750                     aDataset->CreateOnDisk();
3751                     aDataset->WriteOnDisk( aUPos );
3752                     aDataset->CloseOnDisk();
3753                     // V Positions
3754                     if ( onFace ) {
3755                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3756                       aDataset->CreateOnDisk();
3757                       aDataset->WriteOnDisk( aVPos );
3758                       aDataset->CloseOnDisk();
3759                     }
3760                   }
3761                   delete [] aNodeIDs;
3762                   delete [] aUPos;
3763                   if ( aVPos ) delete [] aVPos;
3764
3765                 } // treat positions on edges or faces
3766
3767                 // close "Node Positions" group
3768                 aGroup->CloseOnDisk();
3769
3770               } // if ( there are submeshes in SMESHDS_Mesh )
3771             } // if ( hasData )
3772
3773             // close mesh HDF group
3774             aTopGroup->CloseOnDisk();
3775           }
3776         }
3777       }
3778     }
3779   }
3780
3781   // close HDF file
3782   aFile->CloseOnDisk();
3783   delete aFile;
3784
3785   // Convert temporary files to stream
3786   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
3787
3788   // Remove temporary files and directory
3789   if ( !isMultiFile )
3790     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3791
3792   INFOS( "SMESH_Gen_i::Save() completed" );
3793   return aStreamFile._retn();
3794 }
3795
3796 //=============================================================================
3797 /*!
3798  *  SMESH_Gen_i::SaveASCII
3799  *
3800  *  Save SMESH module's data in ASCII format
3801  */
3802 //=============================================================================
3803
3804 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3805                                            const char*              theURL,
3806                                            bool                     isMultiFile ) {
3807   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3808   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3809   return aStreamFile._retn();
3810
3811   //after usual saving needs to encipher binary to text string
3812   //Any binary symbol will be represent as "|xx" () hexadecimal format number
3813   int size = aStreamFile.in().length();
3814   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3815   for ( int i = 0; i < size; i++ )
3816     sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
3817
3818   buffer[size * 3] = '\0';
3819
3820   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3821
3822   return anAsciiStreamFile._retn();
3823 }
3824
3825 //=============================================================================
3826 /*!
3827  *  SMESH_Gen_i::loadGeomData
3828  *
3829  *  Load GEOM module data
3830  */
3831 //=============================================================================
3832
3833 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3834 {
3835   if ( theCompRoot->_is_nil() )
3836     return;
3837
3838   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
3839   if ( aStudy->_is_nil() )
3840     return;
3841
3842   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
3843   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3844 }
3845
3846 //=============================================================================
3847 /*!
3848  *  SMESH_Gen_i::Load
3849  *
3850  *  Load SMESH module's data
3851  */
3852 //=============================================================================
3853
3854 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
3855                         const SALOMEDS::TMPFile& theStream,
3856                         const char*              theURL,
3857                         bool                     isMultiFile )
3858 {
3859   INFOS( "SMESH_Gen_i::Load" );
3860
3861   if ( myCurrentStudy->_is_nil() ||
3862        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
3863     SetCurrentStudy( theComponent->GetStudy() );
3864
3865   /*  if( !theComponent->_is_nil() )
3866       {
3867       //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
3868       if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
3869       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
3870       }*/
3871
3872   StudyContext* myStudyContext = GetCurrentStudyContext();
3873
3874   // Get temporary files location
3875   TCollection_AsciiString tmpDir =
3876     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3877
3878     INFOS( "THE URL++++++++++++++" )
3879     INFOS( theURL );
3880     INFOS( "THE TMP PATH+++++++++" );
3881     INFOS( tmpDir );
3882
3883   // Convert the stream into sequence of files to process
3884   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
3885                                                                             tmpDir.ToCString(),
3886                                                                             isMultiFile );
3887   TCollection_AsciiString aStudyName( "" );
3888   if ( isMultiFile )
3889     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
3890
3891   // Set names of temporary files
3892   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
3893   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
3894
3895   int size;
3896   HDFfile*    aFile;
3897   HDFdataset* aDataset;
3898   HDFgroup*   aTopGroup;
3899   HDFgroup*   aGroup;
3900   HDFgroup*   aSubGroup;
3901   HDFgroup*   aSubSubGroup;
3902
3903   // Read data
3904   // ---> open HDF file
3905   aFile = new HDFfile( (char*) filename.ToCString() );
3906   try {
3907     aFile->OpenOnDisk( HDF_RDONLY );
3908   }
3909   catch ( HDFexception ) {
3910     INFOS( "Load(): " << filename << " not found!" );
3911     return false;
3912   }
3913
3914   TPythonDump pd; // prevent dump during loading
3915
3916   // DriverMED_R_SMESHDS_Mesh myReader;
3917   // myReader.SetFile( meshfile.ToCString() );
3918
3919   // For PAL13473 ("Repetitive mesh") implementation.
3920   // New dependencies between SMESH objects are established:
3921   // now hypotheses can refer to meshes, shapes and other hypotheses.
3922   // To keep data consistent, the following order of data restoration
3923   // imposed:
3924   // 1. Create hypotheses
3925   // 2. Create all meshes
3926   // 3. Load hypotheses' data
3927   // 4. All the rest
3928
3929   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
3930   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
3931
3932   // get total number of top-level groups
3933   int aNbGroups = aFile->nInternalObjects();
3934   if ( aNbGroups > 0 ) {
3935     // --> in first turn we should read&create hypotheses
3936     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
3937       // open hypotheses root HDF group
3938       aTopGroup = new HDFgroup( "Hypotheses", aFile );
3939       aTopGroup->OpenOnDisk();
3940
3941       // get number of hypotheses
3942       int aNbObjects = aTopGroup->nInternalObjects();
3943       for ( int j = 0; j < aNbObjects; j++ ) {
3944         // try to identify hypothesis
3945         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
3946         aTopGroup->InternalObjectIndentify( j, hypGrpName );
3947
3948         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
3949           // open hypothesis group
3950           aGroup = new HDFgroup( hypGrpName, aTopGroup );
3951           aGroup->OpenOnDisk();
3952
3953           // --> get hypothesis id
3954           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
3955           string hypname;
3956           string libname;
3957           string hypdata;
3958
3959           // get number of datasets
3960           int aNbSubObjects = aGroup->nInternalObjects();
3961           for ( int k = 0; k < aNbSubObjects; k++ ) {
3962             // identify dataset
3963             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
3964             aGroup->InternalObjectIndentify( k, name_of_subgroup );
3965             // --> get hypothesis name
3966             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
3967               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3968               aDataset->OpenOnDisk();
3969               size = aDataset->GetSize();
3970               char* hypname_str = new char[ size ];
3971               aDataset->ReadFromDisk( hypname_str );
3972               hypname = string( hypname_str );
3973               delete [] hypname_str;
3974               aDataset->CloseOnDisk();
3975             }
3976             // --> get hypothesis plugin library name
3977             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
3978               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3979               aDataset->OpenOnDisk();
3980               size = aDataset->GetSize();
3981               char* libname_str = new char[ size ];
3982               aDataset->ReadFromDisk( libname_str );
3983               if(MYDEBUG) SCRUTE( libname_str );
3984               libname = string( libname_str );
3985               delete [] libname_str;
3986               aDataset->CloseOnDisk();
3987             }
3988             // --> get hypothesis data
3989             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
3990               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3991               aDataset->OpenOnDisk();
3992               size = aDataset->GetSize();
3993               char* hypdata_str = new char[ size ];
3994               aDataset->ReadFromDisk( hypdata_str );
3995               hypdata = string( hypdata_str );
3996               delete [] hypdata_str;
3997               aDataset->CloseOnDisk();
3998             }
3999           }
4000           // close hypothesis HDF group
4001           aGroup->CloseOnDisk();
4002
4003           // --> restore hypothesis from data
4004           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4005             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
4006                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4007             SMESH::SMESH_Hypothesis_var myHyp;
4008
4009             try { // protect persistence mechanism against exceptions
4010               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4011             }
4012             catch (...) {
4013               INFOS( "Exception during hypothesis creation" );
4014             }
4015
4016             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4017             if ( myImpl ) {
4018               // myImpl->LoadFrom( hypdata.c_str() );
4019               hypDataList.push_back( make_pair( myImpl, hypdata ));
4020               string iorString = GetORB()->object_to_string( myHyp );
4021               int newId = myStudyContext->findId( iorString );
4022               myStudyContext->mapOldToNew( id, newId );
4023             }
4024             else
4025               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4026           }
4027         }
4028       }
4029       // close hypotheses root HDF group
4030       aTopGroup->CloseOnDisk();
4031       aTopGroup = 0;
4032     }
4033
4034     // --> then we should read&create algorithms
4035     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
4036       // open algorithms root HDF group
4037       aTopGroup = new HDFgroup( "Algorithms", aFile );
4038       aTopGroup->OpenOnDisk();
4039
4040       // get number of algorithms
4041       int aNbObjects = aTopGroup->nInternalObjects();
4042       for ( int j = 0; j < aNbObjects; j++ ) {
4043         // try to identify algorithm
4044         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4045         aTopGroup->InternalObjectIndentify( j, hypGrpName );
4046
4047         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
4048           // open algorithm group
4049           aGroup = new HDFgroup( hypGrpName, aTopGroup );
4050           aGroup->OpenOnDisk();
4051
4052           // --> get algorithm id
4053           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
4054           string hypname;
4055           string libname;
4056           string hypdata;
4057
4058           // get number of datasets
4059           int aNbSubObjects = aGroup->nInternalObjects();
4060           for ( int k = 0; k < aNbSubObjects; k++ ) {
4061             // identify dataset
4062             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4063             aGroup->InternalObjectIndentify( k, name_of_subgroup );
4064             // --> get algorithm name
4065             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
4066               aDataset = new HDFdataset( name_of_subgroup, aGroup );
4067               aDataset->OpenOnDisk();
4068               size = aDataset->GetSize();
4069               char* hypname_str = new char[ size ];
4070               aDataset->ReadFromDisk( hypname_str );
4071               hypname = string( hypname_str );
4072               delete [] hypname_str;
4073               aDataset->CloseOnDisk();
4074             }
4075             // --> get algorithm plugin library name
4076             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
4077               aDataset = new HDFdataset( name_of_subgroup, aGroup );
4078               aDataset->OpenOnDisk();
4079               size = aDataset->GetSize();
4080               char* libname_str = new char[ size ];
4081               aDataset->ReadFromDisk( libname_str );
4082               if(MYDEBUG) SCRUTE( libname_str );
4083               libname = string( libname_str );
4084               delete [] libname_str;
4085               aDataset->CloseOnDisk();
4086             }
4087             // --> get algorithm data
4088             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
4089               aDataset = new HDFdataset( name_of_subgroup, aGroup );
4090               aDataset->OpenOnDisk();
4091               size = aDataset->GetSize();
4092               char* hypdata_str = new char[ size ];
4093               aDataset->ReadFromDisk( hypdata_str );
4094               if(MYDEBUG) SCRUTE( hypdata_str );
4095               hypdata = string( hypdata_str );
4096               delete [] hypdata_str;
4097               aDataset->CloseOnDisk();
4098             }
4099           }
4100           // close algorithm HDF group
4101           aGroup->CloseOnDisk();
4102
4103           // --> restore algorithm from data
4104           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4105             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
4106                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4107             SMESH::SMESH_Hypothesis_var myHyp;
4108
4109             try { // protect persistence mechanism against exceptions
4110               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4111             }
4112             catch (...) {
4113               INFOS( "Exception during hypothesis creation" );
4114             }
4115
4116             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4117             if ( myImpl ) {
4118               //myImpl->LoadFrom( hypdata.c_str() );
4119               hypDataList.push_back( make_pair( myImpl, hypdata ));
4120               string iorString = GetORB()->object_to_string( myHyp );
4121               int newId = myStudyContext->findId( iorString );
4122               myStudyContext->mapOldToNew( id, newId );
4123             }
4124             else
4125               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4126           }
4127         }
4128       }
4129       // close algorithms root HDF group
4130       aTopGroup->CloseOnDisk();
4131       aTopGroup = 0;
4132     }
4133
4134     // --> the rest groups should be meshes
4135     for ( int i = 0; i < aNbGroups; i++ ) {
4136       // identify next group
4137       char meshName[ HDF_NAME_MAX_LEN+1 ];
4138       aFile->InternalObjectIndentify( i, meshName );
4139
4140       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4141         // --> get mesh id
4142         int id = atoi( string( meshName ).substr( 4 ).c_str() );
4143         if ( id <= 0 )
4144           continue;
4145
4146         // open mesh HDF group
4147         aTopGroup = new HDFgroup( meshName, aFile );
4148         aTopGroup->OpenOnDisk();
4149
4150         // get number of child HDF objects
4151         int aNbObjects = aTopGroup->nInternalObjects();
4152         if ( aNbObjects > 0 ) {
4153           // create mesh
4154           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4155           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4156           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4157           if ( !myNewMeshImpl )
4158             continue;
4159           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4160
4161           string iorString = GetORB()->object_to_string( myNewMesh );
4162           int newId = myStudyContext->findId( iorString );
4163           myStudyContext->mapOldToNew( id, newId );
4164
4165           // ouv : NPAL12872
4166           // try to read and set auto color flag
4167           char aMeshAutoColorName[ 30 ];
4168           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4169           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4170           {
4171             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4172             aDataset->OpenOnDisk();
4173             size = aDataset->GetSize();
4174             int* anAutoColor = new int[ size ];
4175             aDataset->ReadFromDisk( anAutoColor );
4176             aDataset->CloseOnDisk();
4177             myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4178           }
4179
4180           // try to read and set reference to shape
4181           GEOM::GEOM_Object_var aShapeObject;
4182           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4183             // load mesh "Ref on shape" - it's an entry to SObject
4184             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4185             aDataset->OpenOnDisk();
4186             size = aDataset->GetSize();
4187             char* refFromFile = new char[ size ];
4188             aDataset->ReadFromDisk( refFromFile );
4189             aDataset->CloseOnDisk();
4190             if ( strlen( refFromFile ) > 0 ) {
4191               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4192
4193               // Make sure GEOM data are loaded first
4194               //loadGeomData( shapeSO->GetFatherComponent() );
4195
4196               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4197               if ( !CORBA::is_nil( shapeObject ) ) {
4198                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4199                 if ( !aShapeObject->_is_nil() )
4200                   myNewMeshImpl->SetShape( aShapeObject );
4201               }
4202             }
4203           }
4204
4205           // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4206           if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4207           {
4208             aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4209             aDataset->OpenOnDisk();
4210             size = aDataset->GetSize();
4211             int* meshPersistentId = new int[ size ];
4212             aDataset->ReadFromDisk( meshPersistentId );
4213             aDataset->CloseOnDisk();
4214             myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4215           }
4216         }
4217       }
4218     } // reading MESHes
4219
4220     // As all object that can be referred by hypothesis are created,
4221     // we can restore hypothesis data
4222
4223     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4224     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4225     {
4226       SMESH_Hypothesis_i* hyp  = hyp_data->first;
4227       string &            data = hyp_data->second;
4228       hyp->LoadFrom( data.c_str() );
4229     }
4230
4231     // Restore the rest mesh data
4232
4233     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4234     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4235     {
4236       aTopGroup                   = meshi_group->second;
4237       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4238       //::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
4239       //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4240
4241       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4242       bool hasData = false;
4243
4244       // get mesh old id
4245       string iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4246       int newId = myStudyContext->findId( iorString );
4247       int id = myStudyContext->getOldId( newId );
4248
4249       // try to find mesh data dataset
4250       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4251         // load mesh "has data" flag
4252         aDataset = new HDFdataset( "Has data", aTopGroup );
4253         aDataset->OpenOnDisk();
4254         size = aDataset->GetSize();
4255         char* strHasData = new char[ size ];
4256         aDataset->ReadFromDisk( strHasData );
4257         aDataset->CloseOnDisk();
4258         if ( strcmp( strHasData, "1") == 0 ) {
4259           // read mesh data from MED file
4260           // myReader.SetMesh( mySMESHDSMesh );
4261           // myReader.SetMeshId( id );
4262           // myReader.Perform();
4263           hasData = true;
4264         }
4265       }
4266
4267       // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4268       // nodes and elements are not yet put into sub-meshes)
4269       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4270         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4271         aGroup->OpenOnDisk();
4272         // get number of applied algorithms
4273         int aNbSubObjects = aGroup->nInternalObjects();
4274         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4275         for ( int j = 0; j < aNbSubObjects; j++ ) {
4276           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4277           aGroup->InternalObjectIndentify( j, name_dataset );
4278           // check if it is an algorithm
4279           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4280             aDataset = new HDFdataset( name_dataset, aGroup );
4281             aDataset->OpenOnDisk();
4282             size = aDataset->GetSize();
4283             char* refFromFile = new char[ size ];
4284             aDataset->ReadFromDisk( refFromFile );
4285             aDataset->CloseOnDisk();
4286             // san - it is impossible to recover applied algorithms using their entries within Load() method
4287             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
4288             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4289             int id = atoi( refFromFile );
4290             string anIOR = myStudyContext->getIORbyOldId( id );
4291             if ( !anIOR.empty() ) {
4292               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4293               if ( !CORBA::is_nil( hypObject ) ) {
4294                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4295                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4296                                            || !myNewMeshImpl->HasShapeToMesh()) )
4297                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4298               }
4299             }
4300           }
4301         }
4302         aGroup->CloseOnDisk();
4303       }
4304
4305       // try to get applied hypotheses
4306       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4307         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4308         aGroup->OpenOnDisk();
4309         // get number of applied hypotheses
4310         int aNbSubObjects = aGroup->nInternalObjects();
4311         for ( int j = 0; j < aNbSubObjects; j++ ) {
4312           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4313           aGroup->InternalObjectIndentify( j, name_dataset );
4314           // check if it is a hypothesis
4315           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4316             aDataset = new HDFdataset( name_dataset, aGroup );
4317             aDataset->OpenOnDisk();
4318             size = aDataset->GetSize();
4319             char* refFromFile = new char[ size ];
4320             aDataset->ReadFromDisk( refFromFile );
4321             aDataset->CloseOnDisk();
4322             // san - it is impossible to recover applied hypotheses using their entries within Load() method
4323             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
4324             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4325             int id = atoi( refFromFile );
4326             string anIOR = myStudyContext->getIORbyOldId( id );
4327             if ( !anIOR.empty() ) {
4328               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4329               if ( !CORBA::is_nil( hypObject ) ) {
4330                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4331                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4332                                            || !myNewMeshImpl->HasShapeToMesh()) )
4333                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4334               }
4335             }
4336           }
4337         }
4338         aGroup->CloseOnDisk();
4339       }
4340
4341       // --> try to find SUB-MESHES containers for each type of submesh
4342       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4343         char name_meshgroup[ 30 ];
4344         if ( j == GetSubMeshOnVertexTag() )
4345           strcpy( name_meshgroup, "SubMeshes On Vertex" );
4346         else if ( j == GetSubMeshOnEdgeTag() )
4347           strcpy( name_meshgroup, "SubMeshes On Edge" );
4348         else if ( j == GetSubMeshOnWireTag() )
4349           strcpy( name_meshgroup, "SubMeshes On Wire" );
4350         else if ( j == GetSubMeshOnFaceTag() )
4351           strcpy( name_meshgroup, "SubMeshes On Face" );
4352         else if ( j == GetSubMeshOnShellTag() )
4353           strcpy( name_meshgroup, "SubMeshes On Shell" );
4354         else if ( j == GetSubMeshOnSolidTag() )
4355           strcpy( name_meshgroup, "SubMeshes On Solid" );
4356         else if ( j == GetSubMeshOnCompoundTag() )
4357           strcpy( name_meshgroup, "SubMeshes On Compound" );
4358
4359         // try to get submeshes container HDF group
4360         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4361           // open submeshes containers HDF group
4362           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4363           aGroup->OpenOnDisk();
4364
4365           // get number of submeshes
4366           int aNbSubMeshes = aGroup->nInternalObjects();
4367           for ( int k = 0; k < aNbSubMeshes; k++ ) {
4368             // identify submesh
4369             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4370             aGroup->InternalObjectIndentify( k, name_submeshgroup );
4371             if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
4372               // --> get submesh id
4373               int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
4374               if ( subid <= 0 )
4375                 continue;
4376               // open submesh HDF group
4377               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4378               aSubGroup->OpenOnDisk();
4379
4380               // try to read and set reference to subshape
4381               GEOM::GEOM_Object_var aSubShapeObject;
4382               SMESH::SMESH_subMesh_var aSubMesh;
4383
4384               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4385                 // load submesh "Ref on shape" - it's an entry to SObject
4386                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4387                 aDataset->OpenOnDisk();
4388                 size = aDataset->GetSize();
4389                 char* refFromFile = new char[ size ];
4390                 aDataset->ReadFromDisk( refFromFile );
4391                 aDataset->CloseOnDisk();
4392                 if ( strlen( refFromFile ) > 0 ) {
4393                   SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
4394                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4395                   if ( !CORBA::is_nil( subShapeObject ) ) {
4396                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4397                     if ( !aSubShapeObject->_is_nil() )
4398                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
4399                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4400                     if ( aSubMesh->_is_nil() )
4401                       continue;
4402                     string iorSubString = GetORB()->object_to_string( aSubMesh );
4403                     int newSubId = myStudyContext->findId( iorSubString );
4404                     myStudyContext->mapOldToNew( subid, newSubId );
4405                   }
4406                 }
4407               }
4408
4409               if ( aSubMesh->_is_nil() )
4410                 continue;
4411
4412               // try to get applied algorithms
4413               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4414                 // open "applied algorithms" HDF group
4415                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4416                 aSubSubGroup->OpenOnDisk();
4417                 // get number of applied algorithms
4418                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4419                 for ( int l = 0; l < aNbSubObjects; l++ ) {
4420                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4421                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4422                   // check if it is an algorithm
4423                   if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4424                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4425                     aDataset->OpenOnDisk();
4426                     size = aDataset->GetSize();
4427                     char* refFromFile = new char[ size ];
4428                     aDataset->ReadFromDisk( refFromFile );
4429                     aDataset->CloseOnDisk();
4430
4431                     int id = atoi( refFromFile );
4432                     string anIOR = myStudyContext->getIORbyOldId( id );
4433                     if ( !anIOR.empty() ) {
4434                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4435                       if ( !CORBA::is_nil( hypObject ) ) {
4436                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4437                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4438                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4439                       }
4440                     }
4441                   }
4442                 }
4443                 // close "applied algorithms" HDF group
4444                 aSubSubGroup->CloseOnDisk();
4445               }
4446
4447               // try to get applied hypotheses
4448               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4449                 // open "applied hypotheses" HDF group
4450                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4451                 aSubSubGroup->OpenOnDisk();
4452                 // get number of applied hypotheses
4453                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4454                 for ( int l = 0; l < aNbSubObjects; l++ ) {
4455                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4456                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4457                   // check if it is a hypothesis
4458                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4459                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4460                     aDataset->OpenOnDisk();
4461                     size = aDataset->GetSize();
4462                     char* refFromFile = new char[ size ];
4463                     aDataset->ReadFromDisk( refFromFile );
4464                     aDataset->CloseOnDisk();
4465
4466                     int id = atoi( refFromFile );
4467                     string anIOR = myStudyContext->getIORbyOldId( id );
4468                     if ( !anIOR.empty() ) {
4469                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4470                       if ( !CORBA::is_nil( hypObject ) ) {
4471                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4472                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4473                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4474                       }
4475                     }
4476                   }
4477                 }
4478                 // close "APPLIED HYPOTHESES" hdf group
4479                 aSubSubGroup->CloseOnDisk();
4480               }
4481
4482               // close SUB-MESH hdf group
4483               aSubGroup->CloseOnDisk();
4484             }
4485           }
4486           // close SUB-MESHES containers hdf group
4487           aGroup->CloseOnDisk();
4488         }
4489       }
4490
4491       // try to get GROUPS
4492       for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
4493         char name_group[ 30 ];
4494         if ( ii == GetNodeGroupsTag() )
4495           strcpy( name_group, "Groups of Nodes" );
4496         else if ( ii == GetEdgeGroupsTag() )
4497           strcpy( name_group, "Groups of Edges" );
4498         else if ( ii == GetFaceGroupsTag() )
4499           strcpy( name_group, "Groups of Faces" );
4500         else if ( ii == GetVolumeGroupsTag() )
4501           strcpy( name_group, "Groups of Volumes" );
4502         else if ( ii == Get0DElementsGroupsTag() )
4503           strcpy( name_group, "Groups of 0D Elements" );
4504         else if ( ii == GetBallElementsGroupsTag() )
4505           strcpy( name_group, "Groups of Balls" );
4506
4507         if ( aTopGroup->ExistInternalObject( name_group ) ) {
4508           aGroup = new HDFgroup( name_group, aTopGroup );
4509           aGroup->OpenOnDisk();
4510           // get number of groups
4511           int aNbSubObjects = aGroup->nInternalObjects();
4512           for ( int j = 0; j < aNbSubObjects; j++ ) {
4513             char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4514             aGroup->InternalObjectIndentify( j, name_dataset );
4515             // check if it is an group
4516             if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
4517               // --> get group id
4518               int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
4519               if ( subid <= 0 )
4520                 continue;
4521               aDataset = new HDFdataset( name_dataset, aGroup );
4522               aDataset->OpenOnDisk();
4523
4524               // Retrieve actual group name
4525               size = aDataset->GetSize();
4526               char* nameFromFile = new char[ size ];
4527               aDataset->ReadFromDisk( nameFromFile );
4528               aDataset->CloseOnDisk();
4529
4530               // Try to find a shape reference
4531               TopoDS_Shape aShape;
4532               char aRefName[ 30 ];
4533               sprintf( aRefName, "Ref on shape %d", subid);
4534               if ( aGroup->ExistInternalObject( aRefName ) ) {
4535                 // load mesh "Ref on shape" - it's an entry to SObject
4536                 aDataset = new HDFdataset( aRefName, aGroup );
4537                 aDataset->OpenOnDisk();
4538                 size = aDataset->GetSize();
4539                 char* refFromFile = new char[ size ];
4540                 aDataset->ReadFromDisk( refFromFile );
4541                 aDataset->CloseOnDisk();
4542                 if ( strlen( refFromFile ) > 0 ) {
4543                   SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4544                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4545                   if ( !CORBA::is_nil( shapeObject ) ) {
4546                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4547                     if ( !aShapeObject->_is_nil() )
4548                       aShape = GeomObjectToShape( aShapeObject );
4549                   }
4550                 }
4551               }
4552               // Try to read a filter of SMESH_GroupOnFilter
4553               SMESH::Filter_var filter;
4554               SMESH_PredicatePtr predicate;
4555               std::string hdfGrpName = "Filter " + SMESH_Comment(subid);
4556               if ( aGroup->ExistInternalObject( hdfGrpName.c_str() ))
4557               {
4558                 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4559                 aDataset->OpenOnDisk();
4560                 size = aDataset->GetSize();
4561                 char* persistStr = new char[ size ];
4562                 aDataset->ReadFromDisk( persistStr );
4563                 aDataset->CloseOnDisk();
4564                 if ( strlen( persistStr ) > 0 ) {
4565                   filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4566                   predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4567                 }
4568               }
4569
4570               // Create group servant
4571               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4572               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4573                 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4574               // Obtain a SMESHDS_Group object
4575               if ( aNewGroup->_is_nil() )
4576                 continue;
4577
4578               string iorSubString = GetORB()->object_to_string( aNewGroup );
4579               int newSubId = myStudyContext->findId( iorSubString );
4580               myStudyContext->mapOldToNew( subid, newSubId );
4581
4582               SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4583               if ( !aGroupImpl )
4584                 continue;
4585
4586               if ( SMESH_GroupOnFilter_i* aFilterGroup =
4587                    dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4588                 aFilterGroup->SetFilter( filter );
4589
4590               SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4591               if ( !aGroupBaseDS )
4592                 continue;
4593
4594               aGroupBaseDS->SetStoreName( name_dataset );
4595
4596               // ouv : NPAL12872
4597               // Read color of the group
4598               char aGroupColorName[ 30 ];
4599               sprintf( aGroupColorName, "ColorGroup %d", subid);
4600               if ( aGroup->ExistInternalObject( aGroupColorName ) )
4601               {
4602                 aDataset = new HDFdataset( aGroupColorName, aGroup );
4603                 aDataset->OpenOnDisk();
4604                 size = aDataset->GetSize();
4605                 double* anRGB = new double[ size ];
4606                 aDataset->ReadFromDisk( anRGB );
4607                 aDataset->CloseOnDisk();
4608                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4609                 aGroupBaseDS->SetColor( aColor );
4610               }
4611
4612               // Fill group with contents from MED file
4613               // SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
4614               // if ( aGrp )
4615               //   myReader.GetGroup( aGrp );
4616             }
4617           }
4618           aGroup->CloseOnDisk();
4619         }
4620       } // reading GROUPs
4621
4622       // instead of reading mesh data, we read only brief information of all
4623       // objects: mesh, groups, sub-meshes (issue 0021208 )
4624       if ( hasData )
4625       {
4626         SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
4627                                          meshfile.ToCString(), filename.ToCString(),
4628                                          !isMultiFile );
4629       }
4630
4631       // read Sub-Mesh ORDER if any
4632       if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4633         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4634         aDataset->OpenOnDisk();
4635         size = aDataset->GetSize();
4636         int* smIDs = new int[ size ];
4637         aDataset->ReadFromDisk( smIDs );
4638         aDataset->CloseOnDisk();
4639         TListOfListOfInt anOrderIds;
4640         anOrderIds.push_back( TListOfInt() );
4641         for ( int i = 0; i < size; i++ )
4642           if ( smIDs[ i ] < 0 ) // is separator
4643             anOrderIds.push_back( TListOfInt() );
4644           else
4645             anOrderIds.back().push_back(smIDs[ i ]);
4646
4647         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4648       }
4649     } // loop on meshes
4650
4651     // update hyps needing full mesh data restored (issue 20918)
4652     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4653     {
4654       SMESH_Hypothesis_i* hyp  = hyp_data->first;
4655       hyp->UpdateAsMeshesRestored();
4656     }
4657
4658     // notify algos on completed restoration to set sub-mesh event listeners
4659     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4660     {
4661       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4662       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
4663
4664       TopoDS_Shape myLocShape;
4665       if(myLocMesh.HasShapeToMesh())
4666         myLocShape = myLocMesh.GetShapeToMesh();
4667       else
4668         myLocShape = SMESH_Mesh::PseudoShape();
4669
4670       myLocMesh.GetSubMesh(myLocShape)->
4671         ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4672     }
4673
4674     // close mesh group
4675     if(aTopGroup)
4676       aTopGroup->CloseOnDisk();
4677   }
4678   // close HDF file
4679   aFile->CloseOnDisk();
4680   delete aFile;
4681
4682   // Remove temporary files created from the stream
4683   if ( !isMultiFile )
4684   {
4685     SMESH_File meshFile( meshfile.ToCString() );
4686     if ( !meshFile ) // no meshfile exists
4687     {
4688       SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4689     }
4690     else
4691     {
4692       Engines::Container_var container = GetContainerRef();
4693       if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
4694       {
4695         container_i->registerTemporaryFile( filename.ToCString() );
4696         container_i->registerTemporaryFile( meshfile.ToCString() );
4697         container_i->registerTemporaryFile( tmpDir.ToCString() );
4698       }
4699     }
4700   }
4701   pd << ""; // prevent optimizing pd out
4702
4703   INFOS( "SMESH_Gen_i::Load completed" );
4704   return true;
4705 }
4706
4707 //=============================================================================
4708 /*!
4709  *  SMESH_Gen_i::LoadASCII
4710  *
4711  *  Load SMESH module's data in ASCII format
4712  */
4713 //=============================================================================
4714
4715 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4716                              const SALOMEDS::TMPFile& theStream,
4717                              const char*              theURL,
4718                              bool                     isMultiFile ) {
4719   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4720   return Load( theComponent, theStream, theURL, isMultiFile );
4721
4722   //before call main ::Load method it's need for decipher text format to
4723   //binary ( "|xx" => x' )
4724   int size = theStream.length();
4725   if ( int((size / 3 )*3) != size ) //error size of buffer
4726     return false;
4727
4728   int real_size = int(size / 3);
4729
4730   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4731   char tmp[3];
4732   tmp[2]='\0';
4733   int c = -1;
4734   for ( int i = 0; i < real_size; i++ )
4735   {
4736     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4737     sscanf( tmp, "%x", &c );
4738     sprintf( (char*)&(buffer[i]), "%c", (char)c );
4739   }
4740
4741   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4742
4743   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4744 }
4745
4746 //=============================================================================
4747 /*!
4748  *  SMESH_Gen_i::Close
4749  *
4750  *  Clears study-connected data when it is closed
4751  */
4752 //=============================================================================
4753
4754 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4755 {
4756   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4757
4758   // set correct current study
4759   SALOMEDS::Study_var study = theComponent->GetStudy();
4760   if ( study->StudyId() != GetCurrentStudyID())
4761     setCurrentStudy( study, /*IsBeingClosed=*/true );
4762
4763   // Clear study contexts data
4764   int studyId = GetCurrentStudyID();
4765   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
4766     delete myStudyContextMap[ studyId ];
4767     myStudyContextMap.erase( studyId );
4768   }
4769
4770   // delete SMESH_Mesh's
4771 //   See bug IPAL19437.
4772 //
4773 //   StudyContextStruct* context = myGen.GetStudyContext( studyId );
4774 //   map< int, SMESH_Mesh* >::iterator i_mesh = context->mapMesh.begin();
4775 //   for ( ; i_mesh != context->mapMesh.end(); ++i_mesh ) {
4776 //     printf( "--------------------------- SMESH_Gen_i::Close, delete aGroup = %p \n", i_mesh->second );
4777 //     delete i_mesh->second;
4778 //   }
4779
4780
4781   // delete SMESHDS_Mesh's
4782   // it's too long on big meshes
4783 //   if ( context->myDocument ) {
4784 //     delete context->myDocument;
4785 //     context->myDocument = 0;
4786 //   }
4787
4788   // remove the tmp files meshes are loaded from
4789   SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
4790
4791   myCurrentStudy = SALOMEDS::Study::_nil();
4792   return;
4793 }
4794
4795 //=============================================================================
4796 /*!
4797  *  SMESH_Gen_i::ComponentDataType
4798  *
4799  *  Get component data type
4800  */
4801 //=============================================================================
4802
4803 char* SMESH_Gen_i::ComponentDataType()
4804 {
4805   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4806   return CORBA::string_dup( "SMESH" );
4807 }
4808
4809
4810 //=============================================================================
4811 /*!
4812  *  SMESH_Gen_i::IORToLocalPersistentID
4813  *
4814  *  Transform data from transient form to persistent
4815  */
4816 //=============================================================================
4817
4818 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4819                                            const char*           IORString,
4820                                            CORBA::Boolean        /*isMultiFile*/,
4821                                            CORBA::Boolean        /*isASCII*/ )
4822 {
4823   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4824   StudyContext* myStudyContext = GetCurrentStudyContext();
4825
4826   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4827     int anId = myStudyContext->findId( IORString );
4828     if ( anId ) {
4829       if(MYDEBUG) MESSAGE( "VSR " << anId )
4830       char strId[ 20 ];
4831       sprintf( strId, "%d", anId );
4832       return  CORBA::string_dup( strId );
4833     }
4834   }
4835   return CORBA::string_dup( "" );
4836 }
4837
4838 //=============================================================================
4839 /*!
4840  *  SMESH_Gen_i::LocalPersistentIDToIOR
4841  *
4842  *  Transform data from persistent form to transient
4843  */
4844 //=============================================================================
4845
4846 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4847                                            const char*           aLocalPersistentID,
4848                                            CORBA::Boolean        /*isMultiFile*/,
4849                                            CORBA::Boolean        /*isASCII*/ )
4850 {
4851   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4852   StudyContext* myStudyContext = GetCurrentStudyContext();
4853
4854   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4855     int anId = atoi( aLocalPersistentID );
4856     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
4857   }
4858   return CORBA::string_dup( "" );
4859 }
4860
4861 //=======================================================================
4862 //function : RegisterObject
4863 //purpose  :
4864 //=======================================================================
4865
4866 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
4867 {
4868   StudyContext* myStudyContext = GetCurrentStudyContext();
4869   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4870     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
4871     return myStudyContext->addObject( string( iorString.in() ) );
4872   }
4873   return 0;
4874 }
4875
4876 //================================================================================
4877 /*!
4878  * \brief Return id of registered object
4879   * \param theObject - the Object
4880   * \retval int - Object id
4881  */
4882 //================================================================================
4883
4884 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
4885 {
4886   StudyContext* myStudyContext = GetCurrentStudyContext();
4887   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4888     string iorString = GetORB()->object_to_string( theObject );
4889     return myStudyContext->findId( iorString );
4890   }
4891   return 0;
4892 }
4893
4894 //=============================================================================
4895 /*!
4896  *  SMESH_Gen_i::SetName
4897  *
4898  *  Set a new object name
4899  */
4900 //=============================================================================
4901 void SMESH_Gen_i::SetName(const char* theIOR,
4902                           const char* theName)
4903 {
4904   if ( theIOR && strcmp( theIOR, "" ) ) {
4905     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
4906     SALOMEDS::SObject_var aSO = ObjectToSObject( myCurrentStudy, anObject );
4907     if ( !aSO->_is_nil() ) {
4908       SetName( aSO, theName );
4909     }
4910   }
4911 }
4912
4913 int SMESH_Gen_i::GetCurrentStudyID()
4914 {
4915   return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
4916 }
4917
4918 // Version information
4919 char* SMESH_Gen_i::getVersion()
4920 {
4921 #if SMESH_DEVELOPMENT
4922   return CORBA::string_dup(SMESH_VERSION_STR"dev");
4923 #else
4924   return CORBA::string_dup(SMESH_VERSION_STR);
4925 #endif
4926 }
4927
4928 //=============================================================================
4929 /*!
4930  *  SMESHEngine_factory
4931  *
4932  *  C factory, accessible with dlsym, after dlopen
4933  */
4934 //=============================================================================
4935
4936 extern "C"
4937 { SMESH_I_EXPORT
4938   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
4939                                                  PortableServer::POA_ptr   poa,
4940                                                  PortableServer::ObjectId* contId,
4941                                                  const char*               instanceName,
4942                                                  const char*               interfaceName )
4943   {
4944     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
4945     if(MYDEBUG) SCRUTE(interfaceName);
4946     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
4947     return aSMESHGen->getId() ;
4948   }
4949 }