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