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