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