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