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