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