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