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