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