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