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