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