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