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