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