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