Salome HOME
0020945: EDF 1465 SMESH: create a new mesh from a selected group or from selected...
[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::ElementType* typesBeg = & srcElemTypes[0];
2334     SMESH::ElementType* typesEnd = typesBeg+srcElemTypes->length(); 
2335
2336     SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2337     while ( gIt->more() )
2338     {
2339       SMESH_Group* group = gIt->next();
2340       const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2341
2342       // Check group type. We copy nodal groups containing nodes of copied element
2343       SMDSAbs_ElementType groupType = groupDS->GetType();
2344       if ( groupType != SMDSAbs_Node &&
2345            std::find( typesBeg, typesEnd, groupType ) == typesEnd )
2346         continue; // group type differs from types of meshPart
2347
2348       // Find copied elements in the group
2349       vector< const SMDS_MeshElement* > groupElems;
2350       SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2351       if ( toKeepIDs )
2352       {
2353         const SMDS_MeshElement* foundElem;
2354         if ( groupType == SMDSAbs_Node )
2355         {
2356           while ( eIt->more() )
2357             if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2358               groupElems.push_back( foundElem );
2359         }
2360         else
2361         {
2362           while ( eIt->more() )
2363             if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2364               groupElems.push_back( foundElem );
2365         }
2366       }
2367       else
2368       {
2369         TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2370         if ( e2eMap.empty() ) continue;
2371         int minID = e2eMap.begin()->first->GetID();
2372         int maxID = e2eMap.rbegin()->first->GetID();
2373         TE2EMap::iterator e2e;
2374         while ( eIt->more() && groupElems.size() < e2eMap.size())
2375         {
2376           const SMDS_MeshElement* e = eIt->next();
2377           if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2378           if ((e2e = e2eMap.find( e )) != e2eMap.end())
2379             groupElems.push_back( e2e->second );
2380         }
2381       }
2382       // Make a new group
2383       if ( !groupElems.empty() )
2384       {
2385         SMESH::SMESH_Group_var newGroupObj =
2386           newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2387         if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2388         {
2389           SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2390           SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2391           for ( unsigned i = 0; i < groupElems.size(); ++i )
2392             smdsGroup.Add( groupElems[i] );
2393
2394           nbNewGroups++;
2395         }
2396       }
2397     }
2398   }
2399
2400   *pyDump << newMesh << " = " << this
2401           << ".CopyMesh( " << meshPart << ", "
2402           << toCopyGroups << ", "
2403           << toKeepIDs << ")";
2404
2405   delete pyDump; pyDump = 0; // allow dump in GetGroups()
2406
2407   if ( nbNewGroups > 0 ) // dump created groups
2408     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2409
2410   return newMesh._retn();
2411 }
2412
2413 //================================================================================
2414 /*!
2415  *  SMESH_Gen_i::GetMEDVersion
2416  *
2417  *  Get MED version of the file by its name
2418  */
2419 //================================================================================
2420 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2421                                           SMESH::MED_VERSION& theVersion)
2422 {
2423   theVersion = SMESH::MED_V2_1;
2424   MED::EVersion aVersion = MED::GetVersionId( theFileName );
2425   switch( aVersion ) {
2426     case MED::eV2_1     : theVersion = SMESH::MED_V2_1; return true;
2427     case MED::eV2_2     : theVersion = SMESH::MED_V2_2; return true;
2428     case MED::eVUnknown : return false;
2429   }
2430   return false;
2431 }
2432
2433 //================================================================================
2434 /*!
2435  *  SMESH_Gen_i::GetMeshNames
2436  *
2437  *  Get names of meshes defined in file with the specified name
2438  */
2439 //================================================================================
2440 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2441 {
2442   SMESH::string_array_var aResult = new SMESH::string_array();
2443   MED::PWrapper aMed = MED::CrWrapper( theFileName );
2444   MED::TErr anErr;
2445   MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2446   if( anErr >= 0 ) {
2447     aResult->length( aNbMeshes );
2448     for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2449       MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2450       aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2451     }
2452   }
2453   return aResult._retn();
2454 }
2455
2456 //=============================================================================
2457 /*!
2458  *  SMESH_Gen_i::Save
2459  *
2460  *  Save SMESH module's data
2461  */
2462 //=============================================================================
2463 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
2464                                       const char*              theURL,
2465                                       bool                     isMultiFile )
2466 {
2467   INFOS( "SMESH_Gen_i::Save" );
2468
2469   //  ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
2470   // san -- in case <myCurrentStudy> differs from theComponent's study,
2471   // use that of the component
2472   if ( myCurrentStudy->_is_nil() || 
2473     theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
2474     SetCurrentStudy( theComponent->GetStudy() );
2475
2476   // Store study contents as a set of python commands
2477   SavePython(myCurrentStudy);
2478
2479   StudyContext* myStudyContext = GetCurrentStudyContext();
2480
2481   // Declare a byte stream
2482   SALOMEDS::TMPFile_var aStreamFile;
2483
2484   // Obtain a temporary dir
2485   TCollection_AsciiString tmpDir =
2486     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
2487
2488   // Create a sequence of files processed
2489   SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
2490   aFileSeq->length( NUM_TMP_FILES );
2491
2492   TCollection_AsciiString aStudyName( "" );
2493   if ( isMultiFile ) 
2494     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
2495
2496   // Set names of temporary files
2497   TCollection_AsciiString filename =
2498     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
2499   TCollection_AsciiString meshfile =
2500     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
2501   aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
2502   aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
2503   filename = tmpDir + filename;
2504   meshfile = tmpDir + meshfile;
2505
2506   HDFfile*    aFile;
2507   HDFdataset* aDataset;
2508   HDFgroup*   aTopGroup;
2509   HDFgroup*   aGroup;
2510   HDFgroup*   aSubGroup;
2511   HDFgroup*   aSubSubGroup;
2512   hdf_size    aSize[ 1 ];
2513
2514
2515   //Remove the files if they exist: BugID: 11225
2516 #ifndef WNT /* unix functionality */
2517   TCollection_AsciiString cmd("rm -f \"");
2518 #else /* windows */
2519   TCollection_AsciiString cmd("del /F \"");
2520 #endif
2521
2522   cmd+=filename;
2523   cmd+="\" \"";
2524   cmd+=meshfile;
2525   cmd+="\"";
2526   system(cmd.ToCString());
2527
2528   // MED writer to be used by storage process
2529   DriverMED_W_SMESHDS_Mesh myWriter;
2530   myWriter.SetFile( meshfile.ToCString() );
2531
2532   // IMP issue 20918
2533   // SetStoreName() to groups before storing hypotheses to let them refer to
2534   // groups using "store name", which is "Group <group_persistent_id>"
2535   {
2536     SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
2537     for ( ; itBig->More(); itBig->Next() ) {
2538       SALOMEDS::SObject_var gotBranch = itBig->Value();
2539       if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
2540         CORBA::Object_var anObject = SObjectToObject( gotBranch );
2541         if ( !CORBA::is_nil( anObject ) ) {
2542           SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
2543           if ( !myMesh->_is_nil() ) {
2544             SMESH::ListOfGroups_var groups = myMesh->GetGroups();
2545             for ( int i = 0; i < groups->length(); ++i )
2546             {
2547               SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
2548               if ( grImpl )
2549               {
2550                 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
2551                 int anId = myStudyContext->findId( string( objStr.in() ) );
2552                 char grpName[ 30 ];
2553                 sprintf( grpName, "Group %d", anId );
2554                 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
2555                 aGrpBaseDS->SetStoreName( grpName );
2556               }
2557             }
2558           }
2559         }
2560       }
2561     }
2562   }
2563
2564   // Write data
2565   // ---> create HDF file
2566   aFile = new HDFfile( (char*) filename.ToCString() );
2567   aFile->CreateOnDisk();
2568
2569   // --> iterator for top-level objects
2570   SALOMEDS::ChildIterator_var itBig = myCurrentStudy->NewChildIterator( theComponent );
2571   for ( ; itBig->More(); itBig->Next() ) {
2572     SALOMEDS::SObject_var gotBranch = itBig->Value();
2573
2574     // --> hypotheses root branch (only one for the study)
2575     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
2576       // create hypotheses root HDF group
2577       aTopGroup = new HDFgroup( "Hypotheses", aFile );
2578       aTopGroup->CreateOnDisk();
2579
2580       // iterator for all hypotheses
2581       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
2582       for ( ; it->More(); it->Next() ) {
2583         SALOMEDS::SObject_var mySObject = it->Value();
2584         CORBA::Object_var anObject = SObjectToObject( mySObject );
2585         if ( !CORBA::is_nil( anObject ) ) {
2586           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
2587           if ( !myHyp->_is_nil() ) {
2588             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2589             if ( myImpl ) {
2590               string hypname = string( myHyp->GetName() );
2591               string libname = string( myHyp->GetLibName() );
2592               // BUG SWP13062
2593               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
2594               // WNT and ".so" for X-system) must be deleted
2595               int libname_len = libname.length();
2596 #ifdef WNT
2597               if( libname_len > 4 )
2598                 libname.resize( libname_len - 4 );
2599 #else
2600               // PAL17753 (Regresion: missing hypothesis in restored study)
2601               // "lib" also should be removed from the beginning
2602               //if( libname_len > 3 )
2603                 //libname.resize( libname_len - 3 );
2604               if( libname_len > 6 )
2605                 libname = libname.substr( 3, libname_len - 3 - 3 );
2606 #endif
2607               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2608               int    id      = myStudyContext->findId( string( objStr.in() ) );
2609               string hypdata = string( myImpl->SaveTo() );
2610
2611               // for each hypothesis create HDF group basing on its id
2612               char hypGrpName[30];
2613               sprintf( hypGrpName, "Hypothesis %d", id );
2614               aGroup = new HDFgroup( hypGrpName, aTopGroup );
2615               aGroup->CreateOnDisk();
2616               // --> type name of hypothesis
2617               aSize[ 0 ] = hypname.length() + 1;
2618               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
2619               aDataset->CreateOnDisk();
2620               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
2621               aDataset->CloseOnDisk();
2622               // --> server plugin library name of hypothesis
2623               aSize[ 0 ] = libname.length() + 1;
2624               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
2625               aDataset->CreateOnDisk();
2626               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
2627               aDataset->CloseOnDisk();
2628               // --> persistent data of hypothesis
2629               aSize[ 0 ] = hypdata.length() + 1;
2630               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
2631               aDataset->CreateOnDisk();
2632               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
2633               aDataset->CloseOnDisk();
2634               // close hypothesis HDF group
2635               aGroup->CloseOnDisk();
2636             }
2637           }
2638         }
2639       }
2640       // close hypotheses root HDF group
2641       aTopGroup->CloseOnDisk();
2642     }
2643     // --> algorithms root branch (only one for the study)
2644     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
2645       // create algorithms root HDF group
2646       aTopGroup = new HDFgroup( "Algorithms", aFile );
2647       aTopGroup->CreateOnDisk();
2648
2649       // iterator for all algorithms
2650       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( gotBranch );
2651       for ( ; it->More(); it->Next() ) {
2652         SALOMEDS::SObject_var mySObject = it->Value();
2653         CORBA::Object_var anObject = SObjectToObject( mySObject );
2654         if ( !CORBA::is_nil( anObject ) ) {
2655           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
2656           if ( !myHyp->_is_nil() ) {
2657             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
2658             if ( myImpl ) {
2659               string hypname = string( myHyp->GetName() );
2660               string libname = string( myHyp->GetLibName() );
2661               // BUG SWP13062
2662               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
2663               // WNT and ".so" for X-system) must be deleted
2664               int libname_len = libname.length();
2665 #ifdef WNT
2666               if( libname_len > 4 )
2667                 libname.resize( libname_len - 4 );
2668 #else
2669               // PAL17753 (Regresion: missing hypothesis in restored study)
2670               // "lib" also should be removed from the beginning
2671               //if( libname_len > 3 )
2672                 //libname.resize( libname_len - 3 );
2673               if( libname_len > 6 )
2674                 libname = libname.substr( 3, libname_len - 3 - 3 );
2675 #endif
2676               CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2677               int    id      = myStudyContext->findId( string( objStr.in() ) );
2678               string hypdata = string( myImpl->SaveTo() );
2679
2680               // for each algorithm create HDF group basing on its id
2681               char hypGrpName[30];
2682               sprintf( hypGrpName, "Algorithm %d", id );
2683               aGroup = new HDFgroup( hypGrpName, aTopGroup );
2684               aGroup->CreateOnDisk();
2685               // --> type name of algorithm
2686               aSize[0] = hypname.length() + 1;
2687               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
2688               aDataset->CreateOnDisk();
2689               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
2690               aDataset->CloseOnDisk();
2691               // --> server plugin library name of hypothesis
2692               aSize[0] = libname.length() + 1;
2693               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
2694               aDataset->CreateOnDisk();
2695               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
2696               aDataset->CloseOnDisk();
2697               // --> persistent data of algorithm
2698               aSize[0] = hypdata.length() + 1;
2699               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
2700               aDataset->CreateOnDisk();
2701               aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
2702               aDataset->CloseOnDisk();
2703               // close algorithm HDF group
2704               aGroup->CloseOnDisk();
2705             }
2706           }
2707         }
2708       }
2709       // close algorithms root HDF group
2710       aTopGroup->CloseOnDisk();
2711     }
2712     // --> mesh objects roots branches
2713     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
2714       CORBA::Object_var anObject = SObjectToObject( gotBranch );
2715       if ( !CORBA::is_nil( anObject ) ) {
2716         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
2717         if ( !myMesh->_is_nil() ) {
2718           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
2719           if ( myImpl ) {
2720             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2721             int id = myStudyContext->findId( string( objStr.in() ) );
2722             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
2723             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
2724             bool hasShape = myLocMesh.HasShapeToMesh();
2725
2726             // for each mesh open the HDF group basing on its id
2727             char meshGrpName[ 30 ];
2728             sprintf( meshGrpName, "Mesh %d", id );
2729             aTopGroup = new HDFgroup( meshGrpName, aFile );
2730             aTopGroup->CreateOnDisk();
2731
2732             // --> put dataset to hdf file which is a flag that mesh has data
2733             string strHasData = "0";
2734             // check if the mesh is not empty
2735             if ( mySMESHDSMesh->NbNodes() > 0 ) {
2736               // write mesh data to med file
2737               myWriter.SetMesh( mySMESHDSMesh );
2738               myWriter.SetMeshId( id );
2739               strHasData = "1";
2740             }
2741             aSize[ 0 ] = strHasData.length() + 1;
2742             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
2743             aDataset->CreateOnDisk();
2744             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
2745             aDataset->CloseOnDisk();
2746
2747             // ouv : NPAL12872
2748             // for each mesh open the HDF group basing on its auto color parameter
2749             char meshAutoColorName[ 30 ];
2750             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
2751             int anAutoColor[1];
2752             anAutoColor[0] = myImpl->GetAutoColor();
2753             aSize[ 0 ] = 1;
2754             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
2755             aDataset->CreateOnDisk();
2756             aDataset->WriteOnDisk( anAutoColor );
2757             aDataset->CloseOnDisk();
2758
2759             // issue 0020693. Store _isModified flag
2760             int isModified = myLocMesh.GetIsModified();
2761             aSize[ 0 ] = 1;
2762             aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
2763             aDataset->CreateOnDisk();
2764             aDataset->WriteOnDisk( &isModified );
2765             aDataset->CloseOnDisk();
2766
2767             // issue 20918. Store Persistent Id of SMESHDS_Mesh
2768             int meshPersistentId = mySMESHDSMesh->GetPersistentId();
2769             aSize[ 0 ] = 1;
2770             aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
2771             aDataset->CreateOnDisk();
2772             aDataset->WriteOnDisk( &meshPersistentId );
2773             aDataset->CloseOnDisk();
2774
2775             // write reference on a shape if exists
2776             SALOMEDS::SObject_var myRef;
2777             bool shapeRefFound = false;
2778             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef );
2779             if ( found ) {
2780               SALOMEDS::SObject_var myShape;
2781               bool ok = myRef->ReferencedObject( myShape );
2782               if ( ok ) {
2783                 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
2784                 string myRefOnObject = myShape->GetID();
2785                 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
2786                   aSize[ 0 ] = myRefOnObject.length() + 1;
2787                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
2788                   aDataset->CreateOnDisk();
2789                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2790                   aDataset->CloseOnDisk();
2791                 }
2792               }
2793             }
2794
2795             // write applied hypotheses if exist
2796             SALOMEDS::SObject_var myHypBranch;
2797             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch );
2798             if ( found && !shapeRefFound && hasShape) { // remove applied hyps
2799               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
2800             }
2801             if ( found && (shapeRefFound || !hasShape) ) {
2802               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
2803               aGroup->CreateOnDisk();
2804
2805               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myHypBranch );
2806               int hypNb = 0;
2807               for ( ; it->More(); it->Next() ) {
2808                 SALOMEDS::SObject_var mySObject = it->Value();
2809                 SALOMEDS::SObject_var myRefOnHyp;
2810                 bool ok = mySObject->ReferencedObject( myRefOnHyp );
2811                 if ( ok ) {
2812                   // san - it is impossible to recover applied hypotheses
2813                   //       using their entries within Load() method,
2814                   // for there are no AttributeIORs in the study when Load() is working. 
2815                   // Hence, it is better to store persistent IDs of hypotheses as references to them
2816
2817                   //string myRefOnObject = myRefOnHyp->GetID();
2818                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
2819                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2820                   int id = myStudyContext->findId( string( objStr.in() ) );
2821                   //if ( myRefOnObject.length() > 0 ) {
2822                   //aSize[ 0 ] = myRefOnObject.length() + 1;
2823                   char hypName[ 30 ], hypId[ 30 ];
2824                   sprintf( hypName, "Hyp %d", ++hypNb );
2825                   sprintf( hypId, "%d", id );
2826                   aSize[ 0 ] = strlen( hypId ) + 1;
2827                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
2828                   aDataset->CreateOnDisk();
2829                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2830                   aDataset->WriteOnDisk( hypId );
2831                   aDataset->CloseOnDisk();
2832                   //}
2833                 }
2834               }
2835               aGroup->CloseOnDisk();
2836             }
2837
2838             // write applied algorithms if exist
2839             SALOMEDS::SObject_var myAlgoBranch;
2840             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(), myAlgoBranch );
2841             if ( found && !shapeRefFound && hasShape) { // remove applied algos
2842               myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
2843             }
2844             if ( found && (shapeRefFound || !hasShape)) {
2845               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
2846               aGroup->CreateOnDisk();
2847
2848               SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myAlgoBranch );
2849               int algoNb = 0;
2850               for ( ; it->More(); it->Next() ) {
2851                 SALOMEDS::SObject_var mySObject = it->Value();
2852                 SALOMEDS::SObject_var myRefOnAlgo;
2853                 bool ok = mySObject->ReferencedObject( myRefOnAlgo );
2854                 if ( ok ) {
2855                   // san - it is impossible to recover applied algorithms
2856                   //       using their entries within Load() method,
2857                   // for there are no AttributeIORs in the study when Load() is working. 
2858                   // Hence, it is better to store persistent IDs of algorithms as references to them
2859
2860                   //string myRefOnObject = myRefOnAlgo->GetID();
2861                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
2862                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2863                   int id = myStudyContext->findId( string( objStr.in() ) );
2864                   //if ( myRefOnObject.length() > 0 ) {
2865                   //aSize[ 0 ] = myRefOnObject.length() + 1;
2866                   char algoName[ 30 ], algoId[ 30 ];
2867                   sprintf( algoName, "Algo %d", ++algoNb );
2868                   sprintf( algoId, "%d", id );
2869                   aSize[ 0 ] = strlen( algoId ) + 1;
2870                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
2871                   aDataset->CreateOnDisk();
2872                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2873                   aDataset->WriteOnDisk( algoId );
2874                   aDataset->CloseOnDisk();
2875                   //}
2876                 }
2877               }
2878               aGroup->CloseOnDisk();
2879             }
2880
2881             // --> submesh objects sub-branches
2882
2883             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
2884               SALOMEDS::SObject_var mySubmeshBranch;
2885               found = gotBranch->FindSubObject( i, mySubmeshBranch );
2886
2887               if ( found ) // check if there is shape reference in submeshes
2888               {
2889                 bool hasShapeRef = false;
2890                 SALOMEDS::ChildIterator_var itSM =
2891                   myCurrentStudy->NewChildIterator( mySubmeshBranch );
2892                 for ( ; itSM->More(); itSM->Next() ) {
2893                   SALOMEDS::SObject_var mySubRef, myShape, mySObject = itSM->Value();
2894                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
2895                     mySubRef->ReferencedObject( myShape );
2896                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
2897                     hasShapeRef = true;
2898                   else
2899                   { // remove one submesh
2900                     if ( shapeRefFound )
2901                     { // unassign hypothesis
2902                       SMESH::SMESH_subMesh_var mySubMesh =
2903                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
2904                       if ( !mySubMesh->_is_nil() ) {
2905                         int shapeID = mySubMesh->GetId();
2906                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
2907                         const list<const SMESHDS_Hypothesis*>& hypList =
2908                           mySMESHDSMesh->GetHypothesis( S );
2909                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
2910                         while ( hyp != hypList.end() ) {
2911                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
2912                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
2913                         }
2914                       }
2915                     }
2916                     myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
2917                   }
2918                 } // loop on submeshes of a type
2919                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
2920                   myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
2921                   found = false;
2922                 }
2923               }  // end check if there is shape reference in submeshes
2924               if ( found ) {
2925                 char name_meshgroup[ 30 ];
2926                 if ( i == GetSubMeshOnVertexTag() )
2927                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
2928                 else if ( i == GetSubMeshOnEdgeTag() )
2929                   strcpy( name_meshgroup, "SubMeshes On Edge" );
2930                 else if ( i == GetSubMeshOnWireTag() )
2931                   strcpy( name_meshgroup, "SubMeshes On Wire" );
2932                 else if ( i == GetSubMeshOnFaceTag() )
2933                   strcpy( name_meshgroup, "SubMeshes On Face" );
2934                 else if ( i == GetSubMeshOnShellTag() )
2935                   strcpy( name_meshgroup, "SubMeshes On Shell" );
2936                 else if ( i == GetSubMeshOnSolidTag() )
2937                   strcpy( name_meshgroup, "SubMeshes On Solid" );
2938                 else if ( i == GetSubMeshOnCompoundTag() )
2939                   strcpy( name_meshgroup, "SubMeshes On Compound" );
2940
2941                 // for each type of submeshes create container HDF group
2942                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
2943                 aGroup->CreateOnDisk();
2944
2945                 // iterator for all submeshes of given type
2946                 SALOMEDS::ChildIterator_var itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
2947                 for ( ; itSM->More(); itSM->Next() ) {
2948                   SALOMEDS::SObject_var mySObject = itSM->Value();
2949                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
2950                   if ( !CORBA::is_nil( anSubObject ))
2951                   {
2952                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
2953                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
2954                     int subid = myStudyContext->findId( string( objStr.in() ) );
2955
2956                     // for each mesh open the HDF group basing on its id
2957                     char submeshGrpName[ 30 ];
2958                     sprintf( submeshGrpName, "SubMesh %d", subid );
2959                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
2960                     aSubGroup->CreateOnDisk();
2961
2962                     // write reference on a shape, already checked if it exists
2963                     SALOMEDS::SObject_var mySubRef, myShape;
2964                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ))
2965                       mySubRef->ReferencedObject( myShape );
2966                     string myRefOnObject = myShape->GetID();
2967                     if ( myRefOnObject.length() > 0 ) {
2968                       aSize[ 0 ] = myRefOnObject.length() + 1;
2969                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
2970                       aDataset->CreateOnDisk();
2971                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
2972                       aDataset->CloseOnDisk();
2973                     }
2974
2975                     // write applied hypotheses if exist
2976                     SALOMEDS::SObject_var mySubHypBranch;
2977                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(), mySubHypBranch );
2978                     if ( found ) {
2979                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
2980                       aSubSubGroup->CreateOnDisk();
2981
2982                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubHypBranch );
2983                       int hypNb = 0;
2984                       for ( ; it->More(); it->Next() ) {
2985                         SALOMEDS::SObject_var mySubSObject = it->Value();
2986                         SALOMEDS::SObject_var myRefOnHyp;
2987                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp );
2988                         if ( ok ) {
2989                           //string myRefOnObject = myRefOnHyp->GetID();
2990                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
2991                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
2992                           int id = myStudyContext->findId( string( objStr.in() ) );
2993                           //if ( myRefOnObject.length() > 0 ) {
2994                           //aSize[ 0 ] = myRefOnObject.length() + 1;
2995                           char hypName[ 30 ], hypId[ 30 ];
2996                           sprintf( hypName, "Hyp %d", ++hypNb );
2997                           sprintf( hypId, "%d", id );
2998                           aSize[ 0 ] = strlen( hypId ) + 1;
2999                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3000                           aDataset->CreateOnDisk();
3001                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3002                           aDataset->WriteOnDisk( hypId );
3003                           aDataset->CloseOnDisk();
3004                           //}
3005                         }
3006                       }
3007                       aSubSubGroup->CloseOnDisk();
3008                     }
3009
3010                     // write applied algorithms if exist
3011                     SALOMEDS::SObject_var mySubAlgoBranch;
3012                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(), mySubAlgoBranch );
3013                     if ( found ) {
3014                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3015                       aSubSubGroup->CreateOnDisk();
3016
3017                       SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( mySubAlgoBranch );
3018                       int algoNb = 0;
3019                       for ( ; it->More(); it->Next() ) {
3020                         SALOMEDS::SObject_var mySubSObject = it->Value();
3021                         SALOMEDS::SObject_var myRefOnAlgo;
3022                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo );
3023                         if ( ok ) {
3024                           //string myRefOnObject = myRefOnAlgo->GetID();
3025                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3026                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3027                           int id = myStudyContext->findId( string( objStr.in() ) );
3028                           //if ( myRefOnObject.length() > 0 ) {
3029                           //aSize[ 0 ] = myRefOnObject.length() + 1;
3030                           char algoName[ 30 ], algoId[ 30 ];
3031                           sprintf( algoName, "Algo %d", ++algoNb );
3032                           sprintf( algoId, "%d", id );
3033                           aSize[ 0 ] = strlen( algoId ) + 1;
3034                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3035                           aDataset->CreateOnDisk();
3036                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3037                           aDataset->WriteOnDisk( algoId );
3038                           aDataset->CloseOnDisk();
3039                           //}
3040                         }
3041                       }
3042                       aSubSubGroup->CloseOnDisk();
3043                     }
3044                     // close submesh HDF group
3045                     aSubGroup->CloseOnDisk();
3046                   }
3047                 }
3048                 // close container of submeshes by type HDF group
3049                 aGroup->CloseOnDisk();
3050               }
3051             }
3052             // All sub-meshes will be stored in MED file
3053             // .. will NOT (PAL 12992)
3054             //if ( shapeRefFound )
3055             //myWriter.AddAllSubMeshes();
3056
3057             // store submesh order if any
3058             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3059             if ( theOrderIds.size() ) {
3060               char order_list[ 30 ];
3061               strcpy( order_list, "Mesh Order" );
3062               // count number of submesh ids
3063               int nbIDs = 0;
3064               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3065               for ( ; idIt != theOrderIds.end(); idIt++ )
3066                 nbIDs += (*idIt).size();
3067               // number of values = number of IDs +
3068               //                    number of lists (for separators) - 1
3069               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3070               idIt = theOrderIds.begin();
3071               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3072                 const TListOfInt& idList = *idIt;
3073                 if (idIt != theOrderIds.begin()) // not first list
3074                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3075                 // dump submesh ids from current list
3076                 TListOfInt::const_iterator id_smId = idList.begin();
3077                 for( ; id_smId != idList.end(); id_smId++ )
3078                   smIDs[ i++ ] = *id_smId;
3079               }
3080               // write HDF group
3081               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3082
3083               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3084               aDataset->CreateOnDisk();
3085               aDataset->WriteOnDisk( smIDs );
3086               aDataset->CloseOnDisk();
3087               //
3088               delete[] smIDs;
3089             }
3090
3091             // groups root sub-branch
3092             SALOMEDS::SObject_var myGroupsBranch;
3093             for ( int i = GetNodeGroupsTag(); i <= GetVolumeGroupsTag(); i++ ) {
3094               found = gotBranch->FindSubObject( i, myGroupsBranch );
3095               if ( found ) {
3096                 char name_group[ 30 ];
3097                 if ( i == GetNodeGroupsTag() )
3098                   strcpy( name_group, "Groups of Nodes" );
3099                 else if ( i == GetEdgeGroupsTag() )
3100                   strcpy( name_group, "Groups of Edges" );
3101                 else if ( i == GetFaceGroupsTag() )
3102                   strcpy( name_group, "Groups of Faces" );
3103                 else if ( i == GetVolumeGroupsTag() )
3104                   strcpy( name_group, "Groups of Volumes" );
3105
3106                 aGroup = new HDFgroup( name_group, aTopGroup );
3107                 aGroup->CreateOnDisk();
3108
3109                 SALOMEDS::ChildIterator_var it = myCurrentStudy->NewChildIterator( myGroupsBranch );
3110                 for ( ; it->More(); it->Next() ) {
3111                   SALOMEDS::SObject_var mySObject = it->Value();
3112                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3113                   if ( !CORBA::is_nil( aSubObject ) ) {
3114                     SMESH_GroupBase_i* myGroupImpl =
3115                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3116                     if ( !myGroupImpl )
3117                       continue;
3118                     SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3119                     if ( !aGrpBaseDS )
3120                       continue;
3121                     
3122                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3123                     int anId = myStudyContext->findId( string( objStr.in() ) );
3124
3125                     // For each group, create a dataset named "Group <group_persistent_id>"
3126                     // and store the group's user name into it
3127                     const char* grpName = aGrpBaseDS->GetStoreName();
3128                     char* aUserName = myGroupImpl->GetName();
3129                     aSize[ 0 ] = strlen( aUserName ) + 1;
3130
3131                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3132                     aDataset->CreateOnDisk();
3133                     aDataset->WriteOnDisk( aUserName );
3134                     aDataset->CloseOnDisk();
3135
3136                     // ouv : NPAL12872
3137                     // For each group, create a dataset named "Group <group_persistent_id> Color"
3138                     // and store the group's color into it
3139                     char grpColorName[ 30 ];
3140                     sprintf( grpColorName, "ColorGroup %d", anId );
3141                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
3142                     double anRGB[3];
3143                     anRGB[ 0 ] = aColor.R;
3144                     anRGB[ 1 ] = aColor.G;
3145                     anRGB[ 2 ] = aColor.B;
3146                     aSize[ 0 ] = 3;
3147                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3148                     aDataset->CreateOnDisk();
3149                     aDataset->WriteOnDisk( anRGB );
3150                     aDataset->CloseOnDisk();
3151
3152                     // Pass SMESHDS_Group to MED writer 
3153                     SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3154                     if ( aGrpDS )
3155                       myWriter.AddGroup( aGrpDS );
3156
3157                     // write reference on a shape if exists
3158                     SMESHDS_GroupOnGeom* aGeomGrp =
3159                       dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3160                     if ( aGeomGrp ) {
3161                       SALOMEDS::SObject_var mySubRef, myShape;
3162                       if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef ) &&
3163                           mySubRef->ReferencedObject( myShape ) &&
3164                           !CORBA::is_nil( myShape->GetObject() ))
3165                       {
3166                         string myRefOnObject = myShape->GetID();
3167                         if ( myRefOnObject.length() > 0 ) {
3168                           char aRefName[ 30 ];
3169                           sprintf( aRefName, "Ref on shape %d", anId);
3170                           aSize[ 0 ] = myRefOnObject.length() + 1;
3171                           aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3172                           aDataset->CreateOnDisk();
3173                           aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3174                           aDataset->CloseOnDisk();
3175                         }
3176                       }
3177                       else // shape ref is invalid:
3178                       {
3179                         // save a group on geometry as ordinary group
3180                         myWriter.AddGroup( aGeomGrp );
3181                       }
3182                     }
3183                   }
3184                 }
3185                 aGroup->CloseOnDisk();
3186               }
3187             } // loop on groups 
3188             
3189             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3190             {
3191               // Flush current mesh information into MED file
3192               myWriter.Perform();
3193               
3194               // maybe a shape was deleted in the study
3195               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3196                 TopoDS_Shape nullShape;
3197                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3198               }
3199               
3200               if ( !mySMESHDSMesh->SubMeshes().empty() )
3201               {
3202                 // Store submeshes
3203                 // ----------------
3204                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3205                 aGroup->CreateOnDisk();
3206                 
3207                 // each element belongs to one or none submesh,
3208                 // so for each node/element, we store a submesh ID
3209                 
3210                 // Make maps of submesh IDs of elements sorted by element IDs
3211                 typedef int TElemID;
3212                 typedef int TSubMID;
3213                 map< TElemID, TSubMID > eId2smId, nId2smId;
3214                 map< TElemID, TSubMID >::iterator hint; // insertion to map is done before hint
3215                 const map<int,SMESHDS_SubMesh*>& aSubMeshes = mySMESHDSMesh->SubMeshes();
3216                 map<int,SMESHDS_SubMesh*>::const_iterator itSubM ( aSubMeshes.begin() );
3217                 SMDS_NodeIteratorPtr itNode;
3218                 SMDS_ElemIteratorPtr itElem;
3219                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
3220                 {
3221                   TSubMID          aSubMeID = itSubM->first;
3222                   SMESHDS_SubMesh* aSubMesh = itSubM->second;
3223                   if ( aSubMesh->IsComplexSubmesh() )
3224                     continue; // submesh containing other submeshs
3225                   // nodes
3226                   hint = nId2smId.begin(); // optimize insertion basing on increasing order of elem Ids in submesh
3227                   for ( itNode = aSubMesh->GetNodes(); itNode->more(); ++hint)
3228                     hint = nId2smId.insert( hint, make_pair( itNode->next()->GetID(), aSubMeID ));
3229                   // elements
3230                   hint = eId2smId.begin();
3231                   for ( itElem = aSubMesh->GetElements(); itElem->more(); ++hint)
3232                     hint = eId2smId.insert( hint, make_pair( itElem->next()->GetID(), aSubMeID ));
3233                 }
3234                 
3235                 // Care of elements that are not on submeshes
3236                 if ( mySMESHDSMesh->NbNodes() != nId2smId.size() ) {
3237                   for ( itNode = mySMESHDSMesh->nodesIterator(); itNode->more(); )
3238                     /*  --- stl_map.h says : */
3239                     /*  A %map relies on unique keys and thus a %pair is only inserted if its */
3240                     /*  first element (the key) is not already present in the %map.           */
3241                     nId2smId.insert( make_pair( itNode->next()->GetID(), 0 ));
3242                 }
3243                 int nbElems = mySMESHDSMesh->NbEdges() + mySMESHDSMesh->NbFaces() + mySMESHDSMesh->NbVolumes();
3244                 if ( nbElems != eId2smId.size() ) {
3245                   for ( itElem = mySMESHDSMesh->elementsIterator(); itElem->more(); )
3246                     eId2smId.insert( make_pair( itElem->next()->GetID(), 0 ));
3247                 }
3248                 
3249                 // Store submesh IDs
3250                 for ( int isNode = 0; isNode < 2; ++isNode )
3251                 {
3252                   map< TElemID, TSubMID >& id2smId = isNode ? nId2smId : eId2smId;
3253                   if ( id2smId.empty() ) continue;
3254                   map< TElemID, TSubMID >::const_iterator id_smId = id2smId.begin();
3255                   // make and fill array of submesh IDs
3256                   int* smIDs = new int [ id2smId.size() ];
3257                   for ( int i = 0; id_smId != id2smId.end(); ++id_smId, ++i )
3258                     smIDs[ i ] = id_smId->second;
3259                   // write HDF group
3260                   aSize[ 0 ] = id2smId.size();
3261                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3262                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3263                   aDataset->CreateOnDisk();
3264                   aDataset->WriteOnDisk( smIDs );
3265                   aDataset->CloseOnDisk();
3266                   //
3267                   delete[] smIDs;
3268                 }
3269                 
3270                 // Store node positions on sub-shapes (SMDS_Position):
3271                 // ----------------------------------------------------
3272                 
3273                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3274                 aGroup->CreateOnDisk();
3275                 
3276                 // in aGroup, create 5 datasets to contain:
3277                 // "Nodes on Edges" - ID of node on edge
3278                 // "Edge positions" - U parameter on node on edge
3279                 // "Nodes on Faces" - ID of node on face
3280                 // "Face U positions" - U parameter of node on face
3281                 // "Face V positions" - V parameter of node on face
3282                 
3283                 // Find out nb of nodes on edges and faces
3284                 // Collect corresponing sub-meshes
3285                 int nbEdgeNodes = 0, nbFaceNodes = 0;
3286                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3287                 // loop on SMESHDS_SubMesh'es
3288                 for ( itSubM = aSubMeshes.begin(); itSubM != aSubMeshes.end() ; itSubM++ )
3289                 {
3290                   SMESHDS_SubMesh* aSubMesh = (*itSubM).second;
3291                   if ( aSubMesh->IsComplexSubmesh() )
3292                     continue; // submesh containing other submeshs
3293                   int nbNodes = aSubMesh->NbNodes();
3294                   if ( nbNodes == 0 ) continue;
3295                   
3296                   int aShapeID = (*itSubM).first;
3297                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3298                     continue;
3299                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3300                   // write only SMDS_FacePosition and SMDS_EdgePosition
3301                   switch ( aShapeType ) {
3302                   case TopAbs_FACE:
3303                     nbFaceNodes += nbNodes;
3304                     aFaceSM.push_back( aSubMesh );
3305                     break;
3306                   case TopAbs_EDGE:
3307                     nbEdgeNodes += nbNodes;
3308                     aEdgeSM.push_back( aSubMesh );
3309                     break;
3310                   default:
3311                     continue;
3312                   }
3313                 }
3314                 // Treat positions on edges or faces
3315                 for ( int onFace = 0; onFace < 2; onFace++ )
3316                 {
3317                   // Create arrays to store in datasets
3318                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3319                   if (!nbNodes) continue;
3320                   int* aNodeIDs = new int [ nbNodes ];
3321                   double* aUPos = new double [ nbNodes ];
3322                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3323                   
3324                   // Fill arrays
3325                   // loop on sub-meshes
3326                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3327                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3328                   for ( ; itSM != pListSM->end(); itSM++ )
3329                   {
3330                     SMESHDS_SubMesh* aSubMesh = (*itSM);
3331                     
3332                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3333                     // loop on nodes in aSubMesh
3334                     while ( itNode->more() )
3335                     {
3336                       //node ID
3337                       const SMDS_MeshNode* node = itNode->next();
3338                       aNodeIDs [ iNode ] = node->GetID();
3339                       
3340                       // Position
3341                       const SMDS_PositionPtr pos = node->GetPosition();
3342                       if ( onFace ) { // on FACE
3343                         const SMDS_FacePosition* fPos =
3344                           dynamic_cast<const SMDS_FacePosition*>( pos.get() );
3345                         if ( fPos ) {
3346                           aUPos[ iNode ] = fPos->GetUParameter();
3347                           aVPos[ iNode ] = fPos->GetVParameter();
3348                           iNode++;
3349                         }
3350                         else
3351                           nbNodes--;
3352                       }
3353                       else { // on EDGE
3354                         const SMDS_EdgePosition* ePos =
3355                           dynamic_cast<const SMDS_EdgePosition*>( pos.get() );
3356                         if ( ePos ) {
3357                           aUPos[ iNode ] = ePos->GetUParameter();
3358                           iNode++;
3359                         }
3360                         else
3361                           nbNodes--;
3362                       }
3363                     } // loop on nodes in aSubMesh
3364                   } // loop on sub-meshes
3365                   
3366                   // Write datasets
3367                   if ( nbNodes )
3368                   {
3369                     aSize[ 0 ] = nbNodes;
3370                     // IDS
3371                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3372                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3373                     aDataset->CreateOnDisk();
3374                     aDataset->WriteOnDisk( aNodeIDs );
3375                     aDataset->CloseOnDisk();
3376                 
3377                     // U Positions
3378                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
3379                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3380                     aDataset->CreateOnDisk();
3381                     aDataset->WriteOnDisk( aUPos );
3382                     aDataset->CloseOnDisk();
3383                     // V Positions
3384                     if ( onFace ) {
3385                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3386                       aDataset->CreateOnDisk();
3387                       aDataset->WriteOnDisk( aVPos );
3388                       aDataset->CloseOnDisk();
3389                     }
3390                   }
3391                   delete [] aNodeIDs;
3392                   delete [] aUPos;
3393                   if ( aVPos ) delete [] aVPos;
3394                   
3395                 } // treat positions on edges or faces
3396                 
3397                 // close "Node Positions" group
3398                 aGroup->CloseOnDisk(); 
3399                 
3400               } // if ( there are submeshes in SMESHDS_Mesh )
3401             } // if ( hasData )
3402             
3403             // close mesh HDF group
3404             aTopGroup->CloseOnDisk();
3405           }
3406         }
3407       }
3408     }
3409   }
3410   
3411   // close HDF file
3412   aFile->CloseOnDisk();
3413   delete aFile;
3414
3415   // Convert temporary files to stream
3416   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq.in(), isMultiFile );
3417
3418   // Remove temporary files and directory
3419   if ( !isMultiFile ) 
3420     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
3421
3422   INFOS( "SMESH_Gen_i::Save() completed" );
3423   return aStreamFile._retn();
3424 }
3425
3426 //=============================================================================
3427 /*!
3428  *  SMESH_Gen_i::SaveASCII
3429  *
3430  *  Save SMESH module's data in ASCII format
3431  */
3432 //=============================================================================
3433
3434 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3435                                            const char*              theURL,
3436                                            bool                     isMultiFile ) {
3437   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3438   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3439   //return aStreamFile._retn();
3440
3441   //after usual saving needs to encipher binary to text string
3442   //Any binary symbol will be represent as "|xx" () hexadecimal format number
3443   int size = aStreamFile.in().length();
3444   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3445   for ( int i = 0; i < size; i++ )
3446     sprintf( (char*)&(buffer[i*3]), "|%02x", (char*)(aStreamFile[i]) );
3447
3448   buffer[size * 3] = '\0';
3449
3450   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3451   
3452   return anAsciiStreamFile._retn();
3453 }
3454
3455 //=============================================================================
3456 /*!
3457  *  SMESH_Gen_i::loadGeomData
3458  *
3459  *  Load GEOM module data
3460  */
3461 //=============================================================================
3462
3463 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
3464 {
3465   if ( theCompRoot->_is_nil() )
3466     return;
3467
3468   SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theCompRoot->GetStudy() );
3469   if ( aStudy->_is_nil() )
3470     return;
3471
3472   SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder(); 
3473   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
3474 }
3475 //=============================================================================
3476 /*!
3477  * \brief Creates SMDS_Position according to shape type
3478  */
3479 //=============================================================================
3480
3481 class PositionCreator {
3482 public:
3483   SMDS_PositionPtr MakePosition(const TopAbs_ShapeEnum type) {
3484     return (this->*myFuncTable[ type ])();
3485   }
3486   PositionCreator() {
3487     myFuncTable.resize( (size_t) TopAbs_SHAPE, & PositionCreator::defaultPosition );
3488     myFuncTable[ TopAbs_SOLID  ] = & PositionCreator::volumePosition;
3489     myFuncTable[ TopAbs_FACE   ] = & PositionCreator::facePosition;
3490     myFuncTable[ TopAbs_EDGE   ] = & PositionCreator::edgePosition;
3491     myFuncTable[ TopAbs_VERTEX ] = & PositionCreator::vertexPosition;
3492   }
3493 private:
3494   SMDS_PositionPtr edgePosition()    const { return SMDS_PositionPtr( new SMDS_EdgePosition  ); }
3495   SMDS_PositionPtr facePosition()    const { return SMDS_PositionPtr( new SMDS_FacePosition  ); }
3496   SMDS_PositionPtr volumePosition()  const { return SMDS_PositionPtr( new SMDS_SpacePosition ); }
3497   SMDS_PositionPtr vertexPosition()  const { return SMDS_PositionPtr( new SMDS_VertexPosition); }
3498   SMDS_PositionPtr defaultPosition() const { return SMDS_SpacePosition::originSpacePosition();  }
3499   typedef SMDS_PositionPtr (PositionCreator:: * FmakePos)() const;
3500   vector<FmakePos> myFuncTable;
3501 };
3502
3503 //=============================================================================
3504 /*!
3505  *  SMESH_Gen_i::Load
3506  *
3507  *  Load SMESH module's data
3508  */
3509 //=============================================================================
3510
3511 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
3512                         const SALOMEDS::TMPFile& theStream,
3513                         const char*              theURL,
3514                         bool                     isMultiFile )
3515 {
3516   INFOS( "SMESH_Gen_i::Load" );
3517
3518   if ( myCurrentStudy->_is_nil() || 
3519        theComponent->GetStudy()->StudyId() != myCurrentStudy->StudyId() )
3520     SetCurrentStudy( theComponent->GetStudy() );
3521
3522   /*  if( !theComponent->_is_nil() )
3523       {
3524       //SALOMEDS::Study_var aStudy = SALOMEDS::Study::_narrow( theComponent->GetStudy() );
3525       if( !myCurrentStudy->FindComponent( "GEOM" )->_is_nil() )
3526       loadGeomData( myCurrentStudy->FindComponent( "GEOM" ) );
3527       }*/
3528
3529   StudyContext* myStudyContext = GetCurrentStudyContext();
3530
3531   // Get temporary files location
3532   TCollection_AsciiString tmpDir =
3533     isMultiFile ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3534     
3535     INFOS( "THE URL++++++++++++++" )
3536     INFOS( theURL );
3537     INFOS( "THE TMP PATH+++++++++" );
3538     INFOS( tmpDir );
3539
3540   // Convert the stream into sequence of files to process
3541   SALOMEDS::ListOfFileNames_var aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
3542                                                                             tmpDir.ToCString(),
3543                                                                             isMultiFile );
3544   TCollection_AsciiString aStudyName( "" );
3545   if ( isMultiFile ) 
3546     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
3547
3548   // Set names of temporary files
3549   TCollection_AsciiString filename = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH.hdf" );
3550   TCollection_AsciiString meshfile = tmpDir + aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );
3551
3552   int size;
3553   HDFfile*    aFile;
3554   HDFdataset* aDataset;
3555   HDFgroup*   aTopGroup;
3556   HDFgroup*   aGroup;
3557   HDFgroup*   aSubGroup;
3558   HDFgroup*   aSubSubGroup;
3559
3560   // Read data
3561   // ---> open HDF file
3562   aFile = new HDFfile( (char*) filename.ToCString() );
3563   try {
3564     aFile->OpenOnDisk( HDF_RDONLY );
3565   }
3566   catch ( HDFexception ) {
3567     INFOS( "Load(): " << filename << " not found!" );
3568     return false;
3569   }
3570
3571   DriverMED_R_SMESHDS_Mesh myReader;
3572   myReader.SetFile( meshfile.ToCString() );
3573
3574   // For PAL13473 ("Repetitive mesh") implementation.
3575   // New dependencies between SMESH objects are established:
3576   // now hypotheses can refer to meshes, shapes and other hypotheses.
3577   // To keep data consistent, the following order of data restoration
3578   // imposed:
3579   // 1. Create hypotheses
3580   // 2. Create all meshes
3581   // 3. Load hypotheses' data
3582   // 4. All the rest
3583
3584   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
3585   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
3586
3587   // get total number of top-level groups
3588   int aNbGroups = aFile->nInternalObjects(); 
3589   if ( aNbGroups > 0 ) {
3590     // --> in first turn we should read&create hypotheses
3591     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
3592       // open hypotheses root HDF group
3593       aTopGroup = new HDFgroup( "Hypotheses", aFile ); 
3594       aTopGroup->OpenOnDisk();
3595
3596       // get number of hypotheses
3597       int aNbObjects = aTopGroup->nInternalObjects(); 
3598       for ( int j = 0; j < aNbObjects; j++ ) {
3599         // try to identify hypothesis
3600         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
3601         aTopGroup->InternalObjectIndentify( j, hypGrpName );
3602
3603         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
3604           // open hypothesis group
3605           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
3606           aGroup->OpenOnDisk();
3607
3608           // --> get hypothesis id
3609           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
3610           string hypname;
3611           string libname;
3612           string hypdata;
3613
3614           // get number of datasets
3615           int aNbSubObjects = aGroup->nInternalObjects();
3616           for ( int k = 0; k < aNbSubObjects; k++ ) {
3617             // identify dataset
3618             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
3619             aGroup->InternalObjectIndentify( k, name_of_subgroup );
3620             // --> get hypothesis name
3621             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
3622               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3623               aDataset->OpenOnDisk();
3624               size = aDataset->GetSize();
3625               char* hypname_str = new char[ size ];
3626               aDataset->ReadFromDisk( hypname_str );
3627               hypname = string( hypname_str );
3628               delete [] hypname_str;
3629               aDataset->CloseOnDisk();
3630             }
3631             // --> get hypothesis plugin library name
3632             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
3633               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3634               aDataset->OpenOnDisk();
3635               size = aDataset->GetSize();
3636               char* libname_str = new char[ size ];
3637               aDataset->ReadFromDisk( libname_str );
3638               if(MYDEBUG) SCRUTE( libname_str );
3639               libname = string( libname_str );
3640               delete [] libname_str;
3641               aDataset->CloseOnDisk();
3642             }
3643             // --> get hypothesis data
3644             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
3645               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3646               aDataset->OpenOnDisk();
3647               size = aDataset->GetSize();
3648               char* hypdata_str = new char[ size ];
3649               aDataset->ReadFromDisk( hypdata_str );
3650               hypdata = string( hypdata_str );
3651               delete [] hypdata_str;
3652               aDataset->CloseOnDisk();
3653             }
3654           }
3655           // close hypothesis HDF group
3656           aGroup->CloseOnDisk();
3657
3658           // --> restore hypothesis from data
3659           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
3660             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
3661                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
3662             SMESH::SMESH_Hypothesis_var myHyp;
3663
3664             try { // protect persistence mechanism against exceptions
3665               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
3666             }
3667             catch (...) {
3668               INFOS( "Exception during hypothesis creation" );
3669             }
3670
3671             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3672             if ( myImpl ) {
3673               // myImpl->LoadFrom( hypdata.c_str() );
3674               hypDataList.push_back( make_pair( myImpl, hypdata ));
3675               string iorString = GetORB()->object_to_string( myHyp );
3676               int newId = myStudyContext->findId( iorString );
3677               myStudyContext->mapOldToNew( id, newId );
3678             }
3679             else
3680               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
3681           }
3682         }
3683       }
3684       // close hypotheses root HDF group
3685       aTopGroup->CloseOnDisk();
3686       aTopGroup = 0;
3687     }
3688
3689     // --> then we should read&create algorithms
3690     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
3691       // open algorithms root HDF group
3692       aTopGroup = new HDFgroup( "Algorithms", aFile ); 
3693       aTopGroup->OpenOnDisk();
3694
3695       // get number of algorithms
3696       int aNbObjects = aTopGroup->nInternalObjects(); 
3697       for ( int j = 0; j < aNbObjects; j++ ) {
3698         // try to identify algorithm
3699         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
3700         aTopGroup->InternalObjectIndentify( j, hypGrpName );
3701
3702         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
3703           // open algorithm group
3704           aGroup = new HDFgroup( hypGrpName, aTopGroup ); 
3705           aGroup->OpenOnDisk();
3706
3707           // --> get algorithm id
3708           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
3709           string hypname;
3710           string libname;
3711           string hypdata;
3712
3713           // get number of datasets
3714           int aNbSubObjects = aGroup->nInternalObjects();
3715           for ( int k = 0; k < aNbSubObjects; k++ ) {
3716             // identify dataset
3717             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
3718             aGroup->InternalObjectIndentify( k, name_of_subgroup );
3719             // --> get algorithm name
3720             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
3721               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3722               aDataset->OpenOnDisk();
3723               size = aDataset->GetSize();
3724               char* hypname_str = new char[ size ];
3725               aDataset->ReadFromDisk( hypname_str );
3726               hypname = string( hypname_str );
3727               delete [] hypname_str;
3728               aDataset->CloseOnDisk();
3729             }
3730             // --> get algorithm plugin library name
3731             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
3732               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3733               aDataset->OpenOnDisk();
3734               size = aDataset->GetSize();
3735               char* libname_str = new char[ size ];
3736               aDataset->ReadFromDisk( libname_str );
3737               if(MYDEBUG) SCRUTE( libname_str );
3738               libname = string( libname_str );
3739               delete [] libname_str;
3740               aDataset->CloseOnDisk();
3741             }
3742             // --> get algorithm data
3743             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
3744               aDataset = new HDFdataset( name_of_subgroup, aGroup );
3745               aDataset->OpenOnDisk();
3746               size = aDataset->GetSize();
3747               char* hypdata_str = new char[ size ];
3748               aDataset->ReadFromDisk( hypdata_str );
3749               if(MYDEBUG) SCRUTE( hypdata_str );
3750               hypdata = string( hypdata_str );
3751               delete [] hypdata_str;
3752               aDataset->CloseOnDisk();
3753             }
3754           }
3755           // close algorithm HDF group
3756           aGroup->CloseOnDisk();
3757
3758           // --> restore algorithm from data
3759           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
3760             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
3761                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
3762             SMESH::SMESH_Hypothesis_var myHyp;
3763
3764             try { // protect persistence mechanism against exceptions
3765               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
3766             }
3767             catch (...) {
3768               INFOS( "Exception during hypothesis creation" );
3769             }
3770
3771             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3772             if ( myImpl ) {
3773               //myImpl->LoadFrom( hypdata.c_str() );
3774               hypDataList.push_back( make_pair( myImpl, hypdata ));
3775               string iorString = GetORB()->object_to_string( myHyp );
3776               int newId = myStudyContext->findId( iorString );
3777               myStudyContext->mapOldToNew( id, newId );
3778             }
3779             else
3780               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
3781           }
3782         }
3783       }
3784       // close algorithms root HDF group
3785       aTopGroup->CloseOnDisk();
3786       aTopGroup = 0;
3787     }
3788
3789     // --> the rest groups should be meshes
3790     for ( int i = 0; i < aNbGroups; i++ ) {
3791       // identify next group
3792       char meshName[ HDF_NAME_MAX_LEN+1 ];
3793       aFile->InternalObjectIndentify( i, meshName );
3794
3795       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
3796         // --> get mesh id
3797         int id = atoi( string( meshName ).substr( 4 ).c_str() );
3798         if ( id <= 0 )
3799           continue;
3800
3801         // open mesh HDF group
3802         aTopGroup = new HDFgroup( meshName, aFile ); 
3803         aTopGroup->OpenOnDisk();
3804
3805         // get number of child HDF objects
3806         int aNbObjects = aTopGroup->nInternalObjects(); 
3807         if ( aNbObjects > 0 ) {
3808           // create mesh
3809           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
3810           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
3811           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
3812           if ( !myNewMeshImpl )
3813             continue;
3814           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
3815
3816           string iorString = GetORB()->object_to_string( myNewMesh );
3817           int newId = myStudyContext->findId( iorString );
3818           myStudyContext->mapOldToNew( id, newId );
3819
3820           // ouv : NPAL12872
3821           // try to read and set auto color flag
3822           char aMeshAutoColorName[ 30 ];
3823           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
3824           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
3825           {
3826             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
3827             aDataset->OpenOnDisk();
3828             size = aDataset->GetSize();
3829             int* anAutoColor = new int[ size ];
3830             aDataset->ReadFromDisk( anAutoColor );
3831             aDataset->CloseOnDisk();
3832             myNewMeshImpl->SetAutoColor( (bool)anAutoColor[0] );
3833           }
3834
3835           // try to read and set reference to shape
3836           GEOM::GEOM_Object_var aShapeObject;
3837           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
3838             // load mesh "Ref on shape" - it's an entry to SObject
3839             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
3840             aDataset->OpenOnDisk();
3841             size = aDataset->GetSize();
3842             char* refFromFile = new char[ size ];
3843             aDataset->ReadFromDisk( refFromFile );
3844             aDataset->CloseOnDisk();
3845             if ( strlen( refFromFile ) > 0 ) {
3846               SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
3847
3848               // Make sure GEOM data are loaded first
3849               //loadGeomData( shapeSO->GetFatherComponent() );
3850
3851               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
3852               if ( !CORBA::is_nil( shapeObject ) ) {
3853                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
3854                 if ( !aShapeObject->_is_nil() )
3855                   myNewMeshImpl->SetShape( aShapeObject );
3856               }
3857             }
3858           }
3859
3860           // issue 0020693. Restore _isModified flag
3861           if( aTopGroup->ExistInternalObject( "_isModified" ) )
3862           {
3863             aDataset = new HDFdataset( "_isModified", aTopGroup );
3864             aDataset->OpenOnDisk();
3865             size = aDataset->GetSize();
3866             int* isModified = new int[ size ];
3867             aDataset->ReadFromDisk( isModified );
3868             aDataset->CloseOnDisk();
3869             myNewMeshImpl->GetImpl().SetIsModified( bool(*isModified));
3870           }
3871
3872           // issue 20918. Restore Persistent Id of SMESHDS_Mesh
3873           if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
3874           {
3875             aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
3876             aDataset->OpenOnDisk();
3877             size = aDataset->GetSize();
3878             int* meshPersistentId = new int[ size ];
3879             aDataset->ReadFromDisk( meshPersistentId );
3880             aDataset->CloseOnDisk();
3881             myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
3882           }
3883         }
3884       }
3885     }
3886
3887     // As all object that can be referred by hypothesis are created,
3888     // we can restore hypothesis data
3889
3890     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
3891     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
3892     {
3893       SMESH_Hypothesis_i* hyp  = hyp_data->first;
3894       string &            data = hyp_data->second;
3895       hyp->LoadFrom( data.c_str() );
3896     }
3897
3898     // Restore the rest mesh data
3899
3900     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
3901     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
3902     {
3903       aTopGroup                   = meshi_group->second;
3904       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
3905       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
3906       SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3907
3908       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
3909       bool hasData = false;
3910
3911       // get mesh old id
3912       string iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
3913       int newId = myStudyContext->findId( iorString );
3914       int id = myStudyContext->getOldId( newId );
3915
3916       // try to find mesh data dataset
3917       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
3918         // load mesh "has data" flag
3919         aDataset = new HDFdataset( "Has data", aTopGroup );
3920         aDataset->OpenOnDisk();
3921         size = aDataset->GetSize();
3922         char* strHasData = new char[ size ];
3923         aDataset->ReadFromDisk( strHasData );
3924         aDataset->CloseOnDisk();
3925         if ( strcmp( strHasData, "1") == 0 ) {
3926           // read mesh data from MED file
3927           myReader.SetMesh( mySMESHDSMesh );
3928           myReader.SetMeshId( id );
3929           myReader.Perform();
3930           hasData = true;
3931         }
3932       }
3933
3934       // try to get applied algorithms
3935       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
3936         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3937         aGroup->OpenOnDisk();
3938         // get number of applied algorithms
3939         int aNbSubObjects = aGroup->nInternalObjects(); 
3940         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
3941         for ( int j = 0; j < aNbSubObjects; j++ ) {
3942           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3943           aGroup->InternalObjectIndentify( j, name_dataset );
3944           // check if it is an algorithm
3945           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
3946             aDataset = new HDFdataset( name_dataset, aGroup );
3947             aDataset->OpenOnDisk();
3948             size = aDataset->GetSize();
3949             char* refFromFile = new char[ size ];
3950             aDataset->ReadFromDisk( refFromFile );
3951             aDataset->CloseOnDisk();
3952
3953             // san - it is impossible to recover applied algorithms using their entries within Load() method
3954
3955             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3956             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3957             int id = atoi( refFromFile );
3958             string anIOR = myStudyContext->getIORbyOldId( id );
3959             if ( !anIOR.empty() ) {
3960               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3961               if ( !CORBA::is_nil( hypObject ) ) {
3962                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
3963                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
3964                                            || !myNewMeshImpl->HasShapeToMesh()) )
3965                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
3966               }
3967             }
3968           }
3969         }
3970         aGroup->CloseOnDisk();
3971       }
3972
3973       // try to get applied hypotheses
3974       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
3975         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3976         aGroup->OpenOnDisk();
3977         // get number of applied hypotheses
3978         int aNbSubObjects = aGroup->nInternalObjects(); 
3979         for ( int j = 0; j < aNbSubObjects; j++ ) {
3980           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
3981           aGroup->InternalObjectIndentify( j, name_dataset );
3982           // check if it is a hypothesis
3983           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
3984             aDataset = new HDFdataset( name_dataset, aGroup );
3985             aDataset->OpenOnDisk();
3986             size = aDataset->GetSize();
3987             char* refFromFile = new char[ size ];
3988             aDataset->ReadFromDisk( refFromFile );
3989             aDataset->CloseOnDisk();
3990
3991             // san - it is impossible to recover applied hypotheses using their entries within Load() method
3992
3993             //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
3994             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
3995             int id = atoi( refFromFile );
3996             string anIOR = myStudyContext->getIORbyOldId( id );
3997             if ( !anIOR.empty() ) {
3998               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
3999               if ( !CORBA::is_nil( hypObject ) ) {
4000                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4001                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4002                                            || !myNewMeshImpl->HasShapeToMesh()) )
4003                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4004               }
4005             }
4006           }
4007         }
4008         aGroup->CloseOnDisk();
4009       }
4010
4011       // --> try to find submeshes containers for each type of submesh
4012       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4013         char name_meshgroup[ 30 ];
4014         if ( j == GetSubMeshOnVertexTag() )
4015           strcpy( name_meshgroup, "SubMeshes On Vertex" );
4016         else if ( j == GetSubMeshOnEdgeTag() )
4017           strcpy( name_meshgroup, "SubMeshes On Edge" );
4018         else if ( j == GetSubMeshOnWireTag() )
4019           strcpy( name_meshgroup, "SubMeshes On Wire" );
4020         else if ( j == GetSubMeshOnFaceTag() )
4021           strcpy( name_meshgroup, "SubMeshes On Face" );
4022         else if ( j == GetSubMeshOnShellTag() )
4023           strcpy( name_meshgroup, "SubMeshes On Shell" );
4024         else if ( j == GetSubMeshOnSolidTag() )
4025           strcpy( name_meshgroup, "SubMeshes On Solid" );
4026         else if ( j == GetSubMeshOnCompoundTag() )
4027           strcpy( name_meshgroup, "SubMeshes On Compound" );
4028
4029         // try to get submeshes container HDF group
4030         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4031           // open submeshes containers HDF group
4032           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4033           aGroup->OpenOnDisk();
4034
4035           // get number of submeshes
4036           int aNbSubMeshes = aGroup->nInternalObjects(); 
4037           for ( int k = 0; k < aNbSubMeshes; k++ ) {
4038             // identify submesh
4039             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4040             aGroup->InternalObjectIndentify( k, name_submeshgroup );
4041             if ( string( name_submeshgroup ).substr( 0, 7 ) == string( "SubMesh" )  ) {
4042               // --> get submesh id
4043               int subid = atoi( string( name_submeshgroup ).substr( 7 ).c_str() );
4044               if ( subid <= 0 )
4045                 continue;
4046               // open submesh HDF group
4047               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4048               aSubGroup->OpenOnDisk();
4049
4050               // try to read and set reference to subshape
4051               GEOM::GEOM_Object_var aSubShapeObject;
4052               SMESH::SMESH_subMesh_var aSubMesh;
4053
4054               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4055                 // load submesh "Ref on shape" - it's an entry to SObject
4056                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4057                 aDataset->OpenOnDisk();
4058                 size = aDataset->GetSize();
4059                 char* refFromFile = new char[ size ];
4060                 aDataset->ReadFromDisk( refFromFile );
4061                 aDataset->CloseOnDisk();
4062                 if ( strlen( refFromFile ) > 0 ) {
4063                   SALOMEDS::SObject_var subShapeSO = myCurrentStudy->FindObjectID( refFromFile );
4064                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4065                   if ( !CORBA::is_nil( subShapeObject ) ) {
4066                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4067                     if ( !aSubShapeObject->_is_nil() )
4068                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
4069                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4070                     if ( aSubMesh->_is_nil() )
4071                       continue;
4072                     string iorSubString = GetORB()->object_to_string( aSubMesh );
4073                     int newSubId = myStudyContext->findId( iorSubString );
4074                     myStudyContext->mapOldToNew( subid, newSubId );
4075                   }
4076                 }
4077               }
4078
4079               if ( aSubMesh->_is_nil() )
4080                 continue;
4081
4082               // VSR: Get submesh data from MED convertor
4083               //                  int anInternalSubmeshId = aSubMesh->GetId(); // this is not a persistent ID, it's an internal one computed from sub-shape
4084               //                  if (myNewMeshImpl->_mapSubMesh.find(anInternalSubmeshId) != myNewMeshImpl->_mapSubMesh.end()) {
4085               //                    if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): loading from MED file submesh with ID = " <<
4086               //                            subid << " for subshape # " << anInternalSubmeshId);
4087               //                    SMESHDS_SubMesh* aSubMeshDS =
4088               //                      myNewMeshImpl->_mapSubMesh[anInternalSubmeshId]->CreateSubMeshDS();
4089               //                    if ( !aSubMeshDS ) {
4090               //                      if(MYDEBUG) MESSAGE("VSR - SMESH_Gen_i::Load(): FAILED to create a submesh for subshape # " <<
4091               //                              anInternalSubmeshId << " in current mesh!");
4092               //                    }
4093               //                    else
4094               //                      myReader.GetSubMesh( aSubMeshDS, subid );
4095               //                  }
4096
4097               // try to get applied algorithms
4098               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4099                 // open "applied algorithms" HDF group
4100                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4101                 aSubSubGroup->OpenOnDisk();
4102                 // get number of applied algorithms
4103                 int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
4104                 for ( int l = 0; l < aNbSubObjects; l++ ) {
4105                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4106                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4107                   // check if it is an algorithm
4108                   if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4109                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4110                     aDataset->OpenOnDisk();
4111                     size = aDataset->GetSize();
4112                     char* refFromFile = new char[ size ];
4113                     aDataset->ReadFromDisk( refFromFile );
4114                     aDataset->CloseOnDisk();
4115
4116                     //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
4117                     //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4118                     int id = atoi( refFromFile );
4119                     string anIOR = myStudyContext->getIORbyOldId( id );
4120                     if ( !anIOR.empty() ) {
4121                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4122                       if ( !CORBA::is_nil( hypObject ) ) {
4123                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4124                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4125                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4126                       }
4127                     }
4128                   }
4129                 }
4130                 // close "applied algorithms" HDF group
4131                 aSubSubGroup->CloseOnDisk();
4132               }
4133
4134               // try to get applied hypotheses
4135               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4136                 // open "applied hypotheses" HDF group
4137                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4138                 aSubSubGroup->OpenOnDisk();
4139                 // get number of applied hypotheses
4140                 int aNbSubObjects = aSubSubGroup->nInternalObjects(); 
4141                 for ( int l = 0; l < aNbSubObjects; l++ ) {
4142                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4143                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4144                   // check if it is a hypothesis
4145                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4146                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4147                     aDataset->OpenOnDisk();
4148                     size = aDataset->GetSize();
4149                     char* refFromFile = new char[ size ];
4150                     aDataset->ReadFromDisk( refFromFile );
4151                     aDataset->CloseOnDisk();
4152
4153                     //SALOMEDS::SObject_var hypSO = myCurrentStudy->FindObjectID( refFromFile );
4154                     //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4155                     int id = atoi( refFromFile );
4156                     string anIOR = myStudyContext->getIORbyOldId( id );
4157                     if ( !anIOR.empty() ) {
4158                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4159                       if ( !CORBA::is_nil( hypObject ) ) {
4160                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4161                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4162                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4163                       }
4164                     }
4165                   }
4166                 }
4167                 // close "applied hypotheses" HDF group
4168                 aSubSubGroup->CloseOnDisk();
4169               }
4170
4171               // close submesh HDF group
4172               aSubGroup->CloseOnDisk();
4173             }
4174           }
4175           // close submeshes containers HDF group
4176           aGroup->CloseOnDisk();
4177         }
4178       }
4179
4180       if(hasData) {
4181
4182         // Read sub-meshes from MED
4183         // -------------------------
4184         if(MYDEBUG) MESSAGE("Create all sub-meshes");
4185         bool submeshesInFamilies = ( ! aTopGroup->ExistInternalObject( "Submeshes" ));
4186         if ( submeshesInFamilies )
4187         {
4188           // old way working before fix of PAL 12992
4189           myReader.CreateAllSubMeshes();
4190         }
4191         else
4192         {
4193           // open a group
4194           aGroup = new HDFgroup( "Submeshes", aTopGroup ); 
4195           aGroup->OpenOnDisk();
4196
4197           int maxID = Max( mySMESHDSMesh->MaxSubMeshIndex(), mySMESHDSMesh->MaxShapeIndex() );
4198           vector< SMESHDS_SubMesh * > subMeshes( maxID + 1, (SMESHDS_SubMesh*) 0 );
4199           vector< TopAbs_ShapeEnum  > smType   ( maxID + 1, TopAbs_SHAPE ); 
4200
4201           PositionCreator aPositionCreator;
4202
4203           SMDS_NodeIteratorPtr nIt = mySMESHDSMesh->nodesIterator();
4204           SMDS_ElemIteratorPtr eIt = mySMESHDSMesh->elementsIterator();
4205           for ( int isNode = 0; isNode < 2; ++isNode )
4206           {
4207             string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4208             if ( aGroup->ExistInternalObject( (char*) aDSName.c_str() ))
4209             {
4210               aDataset = new HDFdataset( (char*) aDSName.c_str(), aGroup );
4211               aDataset->OpenOnDisk();
4212               // read submesh IDs for all elements sorted by ID
4213               int nbElems = aDataset->GetSize();
4214               int* smIDs = new int [ nbElems ];
4215               aDataset->ReadFromDisk( smIDs );
4216               aDataset->CloseOnDisk();
4217
4218               // get elements sorted by ID
4219               TIDSortedElemSet elemSet;
4220               if ( isNode )
4221                 while ( nIt->more() ) elemSet.insert( nIt->next() );
4222               else
4223                 while ( eIt->more() ) elemSet.insert( eIt->next() );
4224               //ASSERT( elemSet.size() == nbElems ); -- issue 20182
4225               // -- Most probably a bad study was saved when there were
4226               // not fixed bugs in SMDS_MeshInfo
4227               if ( elemSet.size() < nbElems ) {
4228 #ifdef _DEBUG_
4229                 cout << "SMESH_Gen_i::Load(), warning: Node position data is invalid" << endl;
4230 #endif
4231                 nbElems = elemSet.size();
4232               }
4233               // add elements to submeshes
4234               TIDSortedElemSet::iterator iE = elemSet.begin();
4235               for ( int i = 0; i < nbElems; ++i, ++iE )
4236               {
4237                 int smID = smIDs[ i ];
4238                 if ( smID == 0 ) continue;
4239                 const SMDS_MeshElement* elem = *iE;
4240                 if( smID > maxID ) {
4241                   // corresponding subshape no longer exists: maybe geom group has been edited
4242                   if ( myNewMeshImpl->HasShapeToMesh() )
4243                     mySMESHDSMesh->RemoveElement( elem );
4244                   continue;
4245                 }
4246                 // get or create submesh
4247                 SMESHDS_SubMesh* & sm = subMeshes[ smID ];
4248                 if ( ! sm ) {
4249                   sm = mySMESHDSMesh->NewSubMesh( smID );
4250                   smType[ smID ] = mySMESHDSMesh->IndexToShape( smID ).ShapeType();
4251                 }
4252                 // add
4253                 if ( isNode ) {
4254                   SMDS_PositionPtr pos = aPositionCreator.MakePosition( smType[ smID ]);
4255                   pos->SetShapeId( smID );
4256                   SMDS_MeshNode* node = const_cast<SMDS_MeshNode*>( static_cast<const SMDS_MeshNode*>( elem ));
4257                   node->SetPosition( pos );
4258                   sm->AddNode( node );
4259                 } else {
4260                   sm->AddElement( elem );
4261                 }
4262               }
4263               delete [] smIDs;
4264             }
4265           }
4266         } // end reading submeshes
4267
4268         // Read node positions on sub-shapes (SMDS_Position)
4269
4270         if ( aTopGroup->ExistInternalObject( "Node Positions" ))
4271         {
4272           // There are 5 datasets to read:
4273           // "Nodes on Edges" - ID of node on edge
4274           // "Edge positions" - U parameter on node on edge
4275           // "Nodes on Faces" - ID of node on face
4276           // "Face U positions" - U parameter of node on face
4277           // "Face V positions" - V parameter of node on face
4278           const char* aEid_DSName = "Nodes on Edges";
4279           const char* aEu_DSName  = "Edge positions";
4280           const char* aFu_DSName  = "Face U positions";
4281           //char* aFid_DSName = "Nodes on Faces";
4282           //char* aFv_DSName  = "Face V positions";
4283
4284           // data to retrieve
4285           int nbEids = 0, nbFids = 0;
4286           int *aEids = 0, *aFids  = 0;
4287           double *aEpos = 0, *aFupos = 0, *aFvpos = 0;
4288
4289           // open a group
4290           aGroup = new HDFgroup( "Node Positions", aTopGroup ); 
4291           aGroup->OpenOnDisk();
4292
4293           // loop on 5 data sets
4294           int aNbObjects = aGroup->nInternalObjects();
4295           for ( int i = 0; i < aNbObjects; i++ )
4296           {
4297             // identify dataset
4298             char aDSName[ HDF_NAME_MAX_LEN+1 ];
4299             aGroup->InternalObjectIndentify( i, aDSName );
4300             // read data
4301             aDataset = new HDFdataset( aDSName, aGroup );
4302             aDataset->OpenOnDisk();
4303             if ( aDataset->GetType() == HDF_FLOAT64 ) // Positions
4304             {
4305               double* pos = new double [ aDataset->GetSize() ];
4306               aDataset->ReadFromDisk( pos );
4307               // which one?
4308               if ( strncmp( aDSName, aEu_DSName, strlen( aEu_DSName )) == 0 )
4309                 aEpos = pos;
4310               else if ( strncmp( aDSName, aFu_DSName, strlen( aFu_DSName )) == 0 )
4311                 aFupos = pos;
4312               else
4313                 aFvpos = pos;
4314             }
4315             else // NODE IDS
4316             {
4317               int aSize = aDataset->GetSize();
4318
4319               // for reading files, created from 18.07.2005 till 10.10.2005
4320               if (aDataset->GetType() == HDF_STRING)
4321                 aSize /= sizeof(int);
4322
4323               int* ids = new int [aSize];
4324               aDataset->ReadFromDisk( ids );
4325               // on face or nodes?
4326               if ( strncmp( aDSName, aEid_DSName, strlen( aEid_DSName )) == 0 ) {
4327                 aEids = ids;
4328                 nbEids = aSize;
4329               }
4330               else {
4331                 aFids = ids;
4332                 nbFids = aSize;
4333               }
4334             }
4335             aDataset->CloseOnDisk();
4336           } // loop on 5 datasets
4337
4338           // Set node positions on edges or faces
4339           for ( int onFace = 0; onFace < 2; onFace++ )
4340           {
4341             int nbNodes = ( onFace ? nbFids : nbEids );
4342             if ( nbNodes == 0 ) continue;
4343             int* aNodeIDs = ( onFace ? aFids : aEids );
4344             double* aUPos = ( onFace ? aFupos : aEpos );
4345             double* aVPos = ( onFace ? aFvpos : 0 );
4346             // loop on node IDs
4347             for ( int iNode = 0; iNode < nbNodes; iNode++ )
4348             {
4349               const SMDS_MeshNode* node = mySMESHDSMesh->FindNode( aNodeIDs[ iNode ]);
4350               if ( !node ) continue; // maybe removed while Loading() if geometry changed
4351               SMDS_PositionPtr aPos = node->GetPosition();
4352               ASSERT( aPos );
4353               if ( onFace ) {
4354                 // ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_FACE );-- issue 20182
4355                 // -- Most probably a bad study was saved when there were
4356                 // not fixed bugs in SMDS_MeshInfo
4357                 if ( aPos->GetTypeOfPosition() == SMDS_TOP_FACE ) {
4358                   SMDS_FacePosition* fPos = const_cast<SMDS_FacePosition*>
4359                     ( static_cast<const SMDS_FacePosition*>( aPos.get() ));
4360                   fPos->SetUParameter( aUPos[ iNode ]);
4361                   fPos->SetVParameter( aVPos[ iNode ]);
4362                 }
4363               }
4364               else {
4365                 // ASSERT( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE );-- issue 20182
4366                 if ( aPos->GetTypeOfPosition() == SMDS_TOP_EDGE ) {
4367                   SMDS_EdgePosition* fPos = const_cast<SMDS_EdgePosition*>
4368                     ( static_cast<const SMDS_EdgePosition*>( aPos.get() ));
4369                   fPos->SetUParameter( aUPos[ iNode ]);
4370                 }
4371               }
4372             }
4373           }
4374           if ( aEids ) delete [] aEids;
4375           if ( aFids ) delete [] aFids;
4376           if ( aEpos ) delete [] aEpos;
4377           if ( aFupos ) delete [] aFupos;
4378           if ( aFvpos ) delete [] aFvpos;
4379
4380           aGroup->CloseOnDisk();
4381
4382         } // if ( aTopGroup->ExistInternalObject( "Node Positions" ) )
4383       } // if ( hasData )
4384
4385       // try to get groups
4386       for ( int ii = GetNodeGroupsTag(); ii <= GetVolumeGroupsTag(); ii++ ) {
4387         char name_group[ 30 ];
4388         if ( ii == GetNodeGroupsTag() )
4389           strcpy( name_group, "Groups of Nodes" );
4390         else if ( ii == GetEdgeGroupsTag() )
4391           strcpy( name_group, "Groups of Edges" );
4392         else if ( ii == GetFaceGroupsTag() )
4393           strcpy( name_group, "Groups of Faces" );
4394         else if ( ii == GetVolumeGroupsTag() )
4395           strcpy( name_group, "Groups of Volumes" );
4396
4397         if ( aTopGroup->ExistInternalObject( name_group ) ) {
4398           aGroup = new HDFgroup( name_group, aTopGroup );
4399           aGroup->OpenOnDisk();
4400           // get number of groups
4401           int aNbSubObjects = aGroup->nInternalObjects(); 
4402           for ( int j = 0; j < aNbSubObjects; j++ ) {
4403             char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4404             aGroup->InternalObjectIndentify( j, name_dataset );
4405             // check if it is an group
4406             if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
4407               // --> get group id
4408               int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
4409               if ( subid <= 0 )
4410                 continue;
4411               aDataset = new HDFdataset( name_dataset, aGroup );
4412               aDataset->OpenOnDisk();
4413
4414               // Retrieve actual group name
4415               size = aDataset->GetSize();
4416               char* nameFromFile = new char[ size ];
4417               aDataset->ReadFromDisk( nameFromFile );
4418               aDataset->CloseOnDisk();
4419
4420               // Try to find a shape reference
4421               TopoDS_Shape aShape;
4422               char aRefName[ 30 ];
4423               sprintf( aRefName, "Ref on shape %d", subid);
4424               if ( aGroup->ExistInternalObject( aRefName ) ) {
4425                 // load mesh "Ref on shape" - it's an entry to SObject
4426                 aDataset = new HDFdataset( aRefName, aGroup );
4427                 aDataset->OpenOnDisk();
4428                 size = aDataset->GetSize();
4429                 char* refFromFile = new char[ size ];
4430                 aDataset->ReadFromDisk( refFromFile );
4431                 aDataset->CloseOnDisk();
4432                 if ( strlen( refFromFile ) > 0 ) {
4433                   SALOMEDS::SObject_var shapeSO = myCurrentStudy->FindObjectID( refFromFile );
4434                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4435                   if ( !CORBA::is_nil( shapeObject ) ) {
4436                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4437                     if ( !aShapeObject->_is_nil() )
4438                       aShape = GeomObjectToShape( aShapeObject );
4439                   }
4440                 }
4441               }
4442               // Create group servant
4443               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4444               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4445                 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape ) );
4446               // Obtain a SMESHDS_Group object 
4447               if ( aNewGroup->_is_nil() )
4448                 continue;
4449
4450               string iorSubString = GetORB()->object_to_string( aNewGroup );
4451               int newSubId = myStudyContext->findId( iorSubString );
4452               myStudyContext->mapOldToNew( subid, newSubId );
4453
4454               SMESH_GroupBase_i* aGroupImpl =
4455                 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aNewGroup ).in() );
4456               if ( !aGroupImpl )
4457                 continue;
4458
4459               SMESH_Group* aLocalGroup  = myLocMesh.GetGroup( aGroupImpl->GetLocalID() );
4460               if ( !aLocalGroup )
4461                 continue;
4462
4463               SMESHDS_GroupBase* aGroupBaseDS = aLocalGroup->GetGroupDS();
4464               aGroupBaseDS->SetStoreName( name_dataset );
4465
4466               // ouv : NPAL12872
4467               // Read color of the group
4468               char aGroupColorName[ 30 ];
4469               sprintf( aGroupColorName, "ColorGroup %d", subid);
4470               if ( aGroup->ExistInternalObject( aGroupColorName ) )
4471               {
4472                 aDataset = new HDFdataset( aGroupColorName, aGroup );
4473                 aDataset->OpenOnDisk();
4474                 size = aDataset->GetSize();
4475                 double* anRGB = new double[ size ];
4476                 aDataset->ReadFromDisk( anRGB );
4477                 aDataset->CloseOnDisk();
4478                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4479                 aGroupBaseDS->SetColor( aColor );
4480               }
4481
4482               // Fill group with contents from MED file
4483               SMESHDS_Group* aGrp = dynamic_cast<SMESHDS_Group*>( aGroupBaseDS );
4484               if ( aGrp )
4485                 myReader.GetGroup( aGrp );
4486             }
4487           }
4488           aGroup->CloseOnDisk();
4489         }
4490       }
4491
4492       // read submeh order if any
4493       if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4494         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4495         aDataset->OpenOnDisk();
4496         size = aDataset->GetSize();
4497         int* smIDs = new int[ size ];
4498         aDataset->ReadFromDisk( smIDs );
4499         aDataset->CloseOnDisk();
4500         TListOfListOfInt anOrderIds;
4501         anOrderIds.push_back( TListOfInt() );
4502         for ( int i = 0; i < size; i++ )
4503           if ( smIDs[ i ] < 0 ) // is separator
4504             anOrderIds.push_back( TListOfInt() );
4505           else
4506             anOrderIds.back().push_back(smIDs[ i ]);
4507         
4508         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4509       }
4510     } // loop on meshes
4511
4512     // notify algos on completed restoration
4513     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4514     {
4515       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4516       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
4517
4518       TopoDS_Shape myLocShape;
4519       if(myLocMesh.HasShapeToMesh())
4520         myLocShape = myLocMesh.GetShapeToMesh();
4521       else
4522         myLocShape = SMESH_Mesh::PseudoShape();
4523         
4524       myLocMesh.GetSubMesh(myLocShape)->
4525         ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4526     }
4527
4528     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4529     {
4530       SMESH_Hypothesis_i* hyp  = hyp_data->first;
4531       hyp->UpdateAsMeshesRestored(); // for hyps needing full mesh data restored (issue 20918)
4532     }
4533
4534     // close mesh group
4535     if(aTopGroup)
4536       aTopGroup->CloseOnDisk();   
4537   }
4538   // close HDF file
4539   aFile->CloseOnDisk();
4540   delete aFile;
4541
4542   // Remove temporary files created from the stream
4543   if ( !isMultiFile ) 
4544     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq.in(), true );
4545
4546   INFOS( "SMESH_Gen_i::Load completed" );
4547   return true;
4548 }
4549
4550 //=============================================================================
4551 /*!
4552  *  SMESH_Gen_i::LoadASCII
4553  *
4554  *  Load SMESH module's data in ASCII format
4555  */
4556 //=============================================================================
4557
4558 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4559                              const SALOMEDS::TMPFile& theStream,
4560                              const char*              theURL,
4561                              bool                     isMultiFile ) {
4562   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4563   return Load( theComponent, theStream, theURL, isMultiFile );
4564
4565   //before call main ::Load method it's need for decipher text format to
4566   //binary ( "|xx" => x' )
4567   int size = theStream.length();
4568   if ( int((size / 3 )*3) != size ) //error size of buffer
4569     return false;
4570
4571   int real_size = int(size / 3);
4572
4573   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4574   char tmp[3];
4575   tmp[2]='\0';
4576   int c = -1;
4577   for ( int i = 0; i < real_size; i++ )
4578   {
4579     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4580     sscanf( tmp, "%x", &c );
4581     sprintf( (char*)&(buffer[i]), "%c", (char)c );
4582   }
4583
4584   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4585   
4586   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4587 }
4588
4589 //=============================================================================
4590 /*!
4591  *  SMESH_Gen_i::Close
4592  *
4593  *  Clears study-connected data when it is closed
4594  */
4595 //=============================================================================
4596
4597 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4598 {
4599   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4600
4601   // set correct current study
4602   if (theComponent->GetStudy()->StudyId() != GetCurrentStudyID())
4603     SetCurrentStudy(theComponent->GetStudy());
4604
4605   // Clear study contexts data
4606   int studyId = GetCurrentStudyID();
4607   if ( myStudyContextMap.find( studyId ) != myStudyContextMap.end() ) {
4608     delete myStudyContextMap[ studyId ];
4609     myStudyContextMap.erase( studyId );
4610   }
4611
4612   // delete SMESH_Mesh's
4613 //   See bug IPAL19437.
4614 //
4615 //   StudyContextStruct* context = myGen.GetStudyContext( studyId );
4616 //   map< int, SMESH_Mesh* >::iterator i_mesh = context->mapMesh.begin();
4617 //   for ( ; i_mesh != context->mapMesh.end(); ++i_mesh ) {
4618 //     printf( "--------------------------- SMESH_Gen_i::Close, delete aGroup = %p \n", i_mesh->second );
4619 //     delete i_mesh->second;
4620 //   }
4621   
4622
4623   // delete SMESHDS_Mesh's
4624   // it's too long on big meshes
4625 //   if ( context->myDocument ) {
4626 //     delete context->myDocument;
4627 //     context->myDocument = 0;
4628 //   }
4629   
4630   myCurrentStudy = SALOMEDS::Study::_nil();
4631   return;
4632 }
4633
4634 //=============================================================================
4635 /*!
4636  *  SMESH_Gen_i::ComponentDataType
4637  * 
4638  *  Get component data type
4639  */
4640 //=============================================================================
4641
4642 char* SMESH_Gen_i::ComponentDataType()
4643 {
4644   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4645   return CORBA::string_dup( "SMESH" );
4646 }
4647
4648     
4649 //=============================================================================
4650 /*!
4651  *  SMESH_Gen_i::IORToLocalPersistentID
4652  *  
4653  *  Transform data from transient form to persistent
4654  */
4655 //=============================================================================
4656
4657 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4658                                            const char*           IORString,
4659                                            CORBA::Boolean        /*isMultiFile*/,
4660                                            CORBA::Boolean        /*isASCII*/ )
4661 {
4662   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4663   StudyContext* myStudyContext = GetCurrentStudyContext();
4664   
4665   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4666     int anId = myStudyContext->findId( IORString );
4667     if ( anId ) {
4668       if(MYDEBUG) MESSAGE( "VSR " << anId )
4669       char strId[ 20 ];
4670       sprintf( strId, "%d", anId );
4671       return  CORBA::string_dup( strId );
4672     }
4673   }
4674   return CORBA::string_dup( "" );
4675 }
4676
4677 //=============================================================================
4678 /*!
4679  *  SMESH_Gen_i::LocalPersistentIDToIOR
4680  *
4681  *  Transform data from persistent form to transient
4682  */
4683 //=============================================================================
4684
4685 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4686                                            const char*           aLocalPersistentID,
4687                                            CORBA::Boolean        /*isMultiFile*/,
4688                                            CORBA::Boolean        /*isASCII*/ )
4689 {
4690   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
4691   StudyContext* myStudyContext = GetCurrentStudyContext();
4692
4693   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
4694     int anId = atoi( aLocalPersistentID );
4695     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
4696   }
4697   return CORBA::string_dup( "" );
4698 }
4699
4700 //=======================================================================
4701 //function : RegisterObject
4702 //purpose  : 
4703 //=======================================================================
4704
4705 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
4706 {
4707   StudyContext* myStudyContext = GetCurrentStudyContext();
4708   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4709     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
4710     return myStudyContext->addObject( string( iorString.in() ) );
4711   }
4712   return 0;
4713 }
4714
4715 //================================================================================
4716 /*!
4717  * \brief Return id of registered object
4718   * \param theObject - the Object
4719   * \retval int - Object id
4720  */
4721 //================================================================================
4722
4723 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
4724 {
4725   StudyContext* myStudyContext = GetCurrentStudyContext();
4726   if ( myStudyContext && !CORBA::is_nil( theObject )) {
4727     string iorString = GetORB()->object_to_string( theObject );
4728     return myStudyContext->findId( iorString );
4729   }
4730   return 0;
4731 }
4732
4733 //=============================================================================
4734 /*!
4735  *  SMESH_Gen_i::SetName
4736  *
4737  *  Set a new object name
4738  */
4739 //=============================================================================
4740 void SMESH_Gen_i::SetName(const char* theIOR,
4741                           const char* theName)
4742 {
4743   if ( theIOR && strcmp( theIOR, "" ) ) {
4744     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
4745     SALOMEDS::SObject_var aSO = ObjectToSObject( myCurrentStudy, anObject );
4746     if ( !aSO->_is_nil() ) {
4747       SetName( aSO, theName );
4748     }
4749   }
4750 }
4751
4752 int SMESH_Gen_i::GetCurrentStudyID()
4753 {
4754   return myCurrentStudy->_is_nil() || myCurrentStudy->_non_existent() ? -1 : myCurrentStudy->StudyId();
4755 }
4756     
4757 //=============================================================================
4758 /*! 
4759  *  SMESHEngine_factory
4760  *
4761  *  C factory, accessible with dlsym, after dlopen  
4762  */
4763 //=============================================================================
4764
4765 extern "C"
4766 { SMESH_I_EXPORT
4767   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
4768                                                  PortableServer::POA_ptr   poa, 
4769                                                  PortableServer::ObjectId* contId,
4770                                                  const char*               instanceName, 
4771                                                  const char*               interfaceName )
4772   {
4773     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
4774     if(MYDEBUG) SCRUTE(interfaceName);
4775     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
4776     return aSMESHGen->getId() ;
4777   }
4778 }