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