Salome HOME
ac694c4feacf8b61498e02470a72df1e959b1165
[modules/smesh.git] / src / SMESH_I / SMESH_Gen_i.cxx
1 // Copyright (C) 2007-2016  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   SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1997   ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1998   TopoDS_Shape myLocShape;
1999   if(theMesh->HasShapeToMesh())
2000     myLocShape = GeomObjectToShape( theShapeObject );
2001   else
2002     myLocShape = SMESH_Mesh::PseudoShape();
2003   myGen.CancelCompute( myLocMesh, myLocShape);
2004 }
2005
2006 //=============================================================================
2007 /*!
2008  *  SMESH_Gen_i::Precompute
2009  *
2010  *  Compute mesh as preview till indicated dimension on shape
2011  */
2012 //=============================================================================
2013
2014 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2015                                                    GEOM::GEOM_Object_ptr theShapeObject,
2016                                                    SMESH::Dimension      theDimension,
2017                                                    SMESH::long_array&    theShapesId)
2018      throw ( SALOME::SALOME_Exception )
2019 {
2020   Unexpect aCatch(SALOME_SalomeException);
2021   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2022
2023   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2024     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2025                                   SALOME::BAD_PARAM );
2026
2027   if ( CORBA::is_nil( theMesh ) )
2028     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2029                                   SALOME::BAD_PARAM );
2030
2031   SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2032   try {
2033     // get mesh servant
2034     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2035     meshServant->Load();
2036     ASSERT( meshServant );
2037     if ( meshServant ) {
2038       // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2039       meshServant->CheckGeomModif();
2040       // get local TopoDS_Shape
2041       TopoDS_Shape myLocShape;
2042       if(theMesh->HasShapeToMesh())
2043         myLocShape = GeomObjectToShape( theShapeObject );
2044       else
2045         return result._retn();;
2046
2047       // call implementation compute
2048       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2049       TSetOfInt shapeIds;
2050       ::MeshDimension aDim = (MeshDimension)theDimension;
2051       if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2052       {
2053         int nbShapeId = shapeIds.size();
2054         theShapesId.length( nbShapeId );
2055         // iterates on shapes and collect mesh entities into mesh preview
2056         TSetOfInt::const_iterator idIt = shapeIds.begin();
2057         TSetOfInt::const_iterator idEnd = shapeIds.end();
2058         std::map< int, int > mapOfShIdNb;
2059         std::set< SMESH_TLink > setOfEdge;
2060         std::list< SMDSAbs_ElementType > listOfElemType;
2061         typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2062         typedef TNode2LocalIDMap::iterator         TNodeLocalID;
2063         TNode2LocalIDMap mapNode2LocalID;
2064         list< TNodeLocalID > connectivity;
2065         int i, nbConnNodes = 0;
2066         std::set< const SMESH_subMesh* > setOfVSubMesh;
2067         // iterates on shapes
2068         for ( ; idIt != idEnd; idIt++ )
2069         {
2070           if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2071             continue;
2072           SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2073           if ( !sm || !sm->IsMeshComputed() )
2074             continue;
2075
2076           const TopoDS_Shape& aSh = sm->GetSubShape();
2077           const int shDim = myGen.GetShapeDim( aSh );
2078           if ( shDim < 1 || shDim > theDimension )
2079             continue;
2080
2081           mapOfShIdNb[ *idIt ] = 0;
2082           theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2083
2084           SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2085           if ( !smDS ) continue;
2086
2087           if ( theDimension == SMESH::DIM_2D )
2088           {
2089             SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2090             while ( faceIt->more() )
2091             {
2092               const SMDS_MeshElement* face = faceIt->next();
2093               int aNbNode = face->NbNodes();
2094               if ( aNbNode > 4 )
2095                 aNbNode /= 2; // do not take into account additional middle nodes
2096
2097               SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2098               for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2099               {
2100                 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2101                 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2102                 {
2103                   listOfElemType.push_back( SMDSAbs_Edge );
2104                   connectivity.push_back
2105                     ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2106                   connectivity.push_back
2107                     ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2108                 }
2109                 node1 = node2;
2110               }
2111             }
2112           }
2113           else if ( theDimension == SMESH::DIM_1D )
2114           {
2115             SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2116             while ( nodeIt->more() )
2117             {
2118               listOfElemType.push_back( SMDSAbs_Node );
2119               connectivity.push_back
2120                 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2121             }
2122             // add corner nodes by first vertex from edge
2123             SMESH_subMeshIteratorPtr edgeSmIt =
2124               sm->getDependsOnIterator(/*includeSelf*/false,
2125                                        /*complexShapeFirst*/false);
2126             while ( edgeSmIt->more() )
2127             {
2128               SMESH_subMesh* vertexSM = edgeSmIt->next();
2129               // check that vertex is not already treated
2130               if ( !setOfVSubMesh.insert( vertexSM ).second )
2131                 continue;
2132               if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2133                 continue;
2134
2135               const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2136               SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2137               while ( nodeIt->more() )
2138               {
2139                 listOfElemType.push_back( SMDSAbs_Node );
2140                 connectivity.push_back
2141                   ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2142               }
2143             }
2144           }
2145         }
2146
2147         // fill node coords and assign local ids to the nodes
2148         int nbNodes = mapNode2LocalID.size();
2149         result->nodesXYZ.length( nbNodes );
2150         TNodeLocalID node2ID = mapNode2LocalID.begin();
2151         for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2152           node2ID->second = i;
2153           const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2154           result->nodesXYZ[i].x = node->X();
2155           result->nodesXYZ[i].y = node->Y();
2156           result->nodesXYZ[i].z = node->Z();
2157         }
2158         // fill connectivity
2159         result->elementConnectivities.length( nbConnNodes );
2160         list< TNodeLocalID >::iterator connIt = connectivity.begin();
2161         for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2162           result->elementConnectivities[i] = (*connIt)->second;
2163         }
2164
2165         // fill element types
2166         result->elementTypes.length( listOfElemType.size() );
2167         std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2168         std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2169         for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2170         {
2171           SMDSAbs_ElementType elemType = *typeIt;
2172           result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2173           result->elementTypes[i].isPoly           = false;
2174           result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2175         }
2176
2177         // correct number of shapes
2178         theShapesId.length( mapOfShIdNb.size() );
2179       }
2180     }
2181   }
2182   catch ( std::bad_alloc ) {
2183     INFOS( "Precompute(): lack of memory" );
2184   }
2185   catch ( SALOME_Exception& S_ex ) {
2186     INFOS( "Precompute(): catch exception "<< S_ex.what() );
2187   }
2188   catch ( ... ) {
2189     INFOS( "Precompute(): unknown exception " );
2190   }
2191   return result._retn();
2192 }
2193
2194
2195 //=============================================================================
2196 /*!
2197  *  SMESH_Gen_i::Evaluate
2198  *
2199  *  Evaluate mesh on a shape
2200  */
2201 //=============================================================================
2202
2203 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2204                                          GEOM::GEOM_Object_ptr theShapeObject)
2205 //                                     SMESH::long_array& theNbElems)
2206      throw ( SALOME::SALOME_Exception )
2207 {
2208   Unexpect aCatch(SALOME_SalomeException);
2209   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2210
2211   if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2212     THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2213                                   SALOME::BAD_PARAM );
2214
2215   if ( CORBA::is_nil( theMesh ) )
2216     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2217                                   SALOME::BAD_PARAM );
2218
2219   SMESH::long_array_var nbels = new SMESH::long_array;
2220   nbels->length(SMESH::Entity_Last);
2221   int i = SMESH::Entity_Node;
2222   for (; i < SMESH::Entity_Last; i++)
2223     nbels[i] = 0;
2224
2225   // Update Python script
2226   TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2227                 << theMesh << ", " << theShapeObject << ")";
2228
2229   try {
2230     // get mesh servant
2231     SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2232     ASSERT( meshServant );
2233     if ( meshServant ) {
2234       meshServant->Load();
2235       // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2236       meshServant->CheckGeomModif();
2237       // get local TopoDS_Shape
2238       TopoDS_Shape myLocShape;
2239       if(theMesh->HasShapeToMesh())
2240         myLocShape = GeomObjectToShape( theShapeObject );
2241       else
2242         myLocShape = SMESH_Mesh::PseudoShape();
2243       // call implementation compute
2244       ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2245       MapShapeNbElems aResMap;
2246       /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2247       MapShapeNbElemsItr anIt = aResMap.begin();
2248       for(; anIt!=aResMap.end(); anIt++) {
2249         const vector<int>& aVec = (*anIt).second;
2250         for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2251           int nbElem = aVec[i];
2252           if ( nbElem < 0 ) // algo failed, check that it has reported a message
2253           {
2254             SMESH_subMesh*            sm = anIt->first;
2255             SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2256             const SMESH_Algo*       algo = sm->GetAlgo();
2257             if ( (algo && !error.get()) || error->IsOK() )
2258               error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2259           }
2260           else
2261           {
2262             nbels[i] += aVec[i];
2263           }
2264         }
2265       }
2266       return nbels._retn();
2267     }
2268   }
2269   catch ( std::bad_alloc ) {
2270     INFOS( "Evaluate(): lack of memory" );
2271   }
2272   catch ( SALOME_Exception& S_ex ) {
2273     INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2274   }
2275   catch ( ... ) {
2276     INFOS( "Evaluate(): unknown exception " );
2277   }
2278
2279   return nbels._retn();
2280 }
2281
2282 //================================================================================
2283 /*!
2284  * \brief Return geometrical object the given element is built on
2285  *  \param theMesh - the mesh the element is in
2286  *  \param theElementID - the element ID
2287  *  \param theGeomName - the name of the result geom object if it is not yet published
2288  *  \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2289  */
2290 //================================================================================
2291
2292 GEOM::GEOM_Object_ptr
2293 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
2294                                        CORBA::Long            theElementID,
2295                                        const char*            theGeomName)
2296   throw ( SALOME::SALOME_Exception )
2297 {
2298   Unexpect aCatch(SALOME_SalomeException);
2299
2300   GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2301   if ( !geom->_is_nil() ) {
2302     GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2303     GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
2304
2305     // try to find the corresponding SObject
2306     SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2307     if ( SObj->_is_nil() ) // submesh can be not found even if published
2308     {
2309       // try to find published submesh
2310       GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2311       if ( !geom->IsMainShape() && list->length() == 1 ) {
2312         SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2313         SALOMEDS::ChildIterator_wrap it;
2314         if ( !mainSO->_is_nil() ) {
2315           it = getStudyServant()->NewChildIterator( mainSO );
2316         }
2317         if ( !it->_is_nil() ) {
2318           for ( it->InitEx(true); it->More(); it->Next() ) {
2319             SALOMEDS::SObject_wrap      so = it->Value();
2320             CORBA::Object_var         obj = SObjectToObject( so );
2321             GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2322             if ( !subGeom->_is_nil() ) {
2323               GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2324               if ( subList->length() == 1 && list[0] == subList[0] ) {
2325                 SObj = so;
2326                 geom = subGeom;
2327                 break;
2328               }
2329             }
2330           }
2331         }
2332       }
2333     }
2334     if ( SObj->_is_nil() ) // publish a new subshape
2335       SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2336
2337     // return only published geometry
2338     if ( !SObj->_is_nil() ) {
2339       //return geom._retn(); -- servant of geom must be UnRegister()ed;
2340       CORBA::Object_var    obj = SObjectToObject( SObj );
2341       GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2342       return go._retn();
2343     }
2344   }
2345   return GEOM::GEOM_Object::_nil();
2346 }
2347
2348 //================================================================================
2349 /*!
2350  * \brief Return geometrical object the given element is built on.
2351  *  \param theMesh - the mesh the element is in
2352  *  \param theElementID - the element ID
2353  *  \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2354  */
2355 //================================================================================
2356
2357 GEOM::GEOM_Object_ptr
2358 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr  theMesh,
2359                                         CORBA::Long            theElementID)
2360   throw ( SALOME::SALOME_Exception )
2361 {
2362   Unexpect aCatch(SALOME_SalomeException);
2363   if ( CORBA::is_nil( theMesh ) )
2364     THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2365
2366   GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2367   GEOM::GEOM_Gen_ptr    geomGen   = GetGeomEngine();
2368
2369   // get a core mesh DS
2370   SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2371   if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2372   {
2373     ::SMESH_Mesh & mesh = meshServant->GetImpl();
2374     SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2375     // find the element in mesh
2376     if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2377       // find a shape id by the element
2378       if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2379         // get a geom object by the shape id
2380         GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2381         if ( geom->_is_nil() ) {
2382           // try to find a published sub-shape
2383           SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2384           SALOMEDS::ChildIterator_wrap it;
2385           if ( !mainSO->_is_nil() ) {
2386             it = getStudyServant()->NewChildIterator( mainSO );
2387           }
2388           if ( !it->_is_nil() ) {
2389             for ( it->InitEx(true); it->More(); it->Next() ) {
2390               SALOMEDS::SObject_wrap      so = it->Value();
2391               CORBA::Object_var         obj = SObjectToObject( so );
2392               GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2393               if ( !subGeom->_is_nil() ) {
2394                 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2395                 if ( subList->length() == 1 && shapeID == subList[0] ) {
2396                   geom = subGeom;
2397                   break;
2398                 }
2399               }
2400             }
2401           }
2402         }
2403         if ( geom->_is_nil() ) {
2404           // explode
2405           GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2406           if ( !op->_is_nil() )
2407             geom = op->GetSubShape( mainShape, shapeID );
2408         }
2409         else {
2410           geom->Register();
2411         }
2412         if ( !geom->_is_nil() ) {
2413           GeomObjectToShape( geom ); // let geom client remember the found shape
2414           return geom._retn();
2415         }
2416       }
2417     }
2418   }
2419   return GEOM::GEOM_Object::_nil();
2420 }
2421
2422 //================================================================================
2423 /*!
2424  *  SMESH_Gen_i::Concatenate
2425  *
2426  *  Concatenate the given meshes into one mesh
2427  */
2428 //================================================================================
2429
2430 SMESH::SMESH_Mesh_ptr
2431 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2432                          CORBA::Boolean                theUniteIdenticalGroups,
2433                          CORBA::Boolean                theMergeNodesAndElements,
2434                          CORBA::Double                 theMergeTolerance)
2435   throw ( SALOME::SALOME_Exception )
2436 {
2437   return ConcatenateCommon(theMeshesArray,
2438                            theUniteIdenticalGroups,
2439                            theMergeNodesAndElements,
2440                            theMergeTolerance,
2441                            false);
2442 }
2443
2444 //================================================================================
2445 /*!
2446  *  SMESH_Gen_i::ConcatenateWithGroups
2447  *
2448  *  Concatenate the given meshes into one mesh
2449  *  Create the groups of all elements from initial meshes
2450  */
2451 //================================================================================
2452
2453 SMESH::SMESH_Mesh_ptr
2454 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2455                                    CORBA::Boolean                theUniteIdenticalGroups,
2456                                    CORBA::Boolean                theMergeNodesAndElements,
2457                                    CORBA::Double                 theMergeTolerance)
2458   throw ( SALOME::SALOME_Exception )
2459 {
2460   return ConcatenateCommon(theMeshesArray,
2461                            theUniteIdenticalGroups,
2462                            theMergeNodesAndElements,
2463                            theMergeTolerance,
2464                            true);
2465 }
2466
2467 //================================================================================
2468 /*!
2469  *  SMESH_Gen_i::ConcatenateCommon
2470  *
2471  *  Concatenate the given meshes into one mesh
2472  */
2473 //================================================================================
2474
2475 SMESH::SMESH_Mesh_ptr
2476 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2477                                CORBA::Boolean                theUniteIdenticalGroups,
2478                                CORBA::Boolean                theMergeNodesAndElements,
2479                                CORBA::Double                 theMergeTolerance,
2480                                CORBA::Boolean                theCommonGroups)
2481   throw ( SALOME::SALOME_Exception )
2482 {
2483   std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2484   TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2485
2486   // create mesh
2487   SMESH::SMESH_Mesh_var newMesh = CreateEmptyMesh();
2488   SMESH_Mesh_i*         newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2489   if ( !newImpl ) return newMesh._retn();
2490
2491   ::SMESH_Mesh&   locMesh = newImpl->GetImpl();
2492   SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2493
2494   typedef std::list<SMESH::SMESH_Group_var>          TListOfNewGroups;
2495   typedef std::pair<string, SMESH::ElementType >     TNameAndType;
2496   typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2497   TGroupsMap       groupsMap;
2498   TListOfNewGroups listOfNewGroups;
2499
2500   ::SMESH_MeshEditor               newEditor( &locMesh );
2501   ::SMESH_MeshEditor::ElemFeatures elemType;
2502
2503   // loop on sub-meshes
2504   for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2505   {
2506     if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2507     SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2508     SMESH_Mesh_i*         initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2509     if ( !initImpl ) continue;
2510     initImpl->Load();
2511
2512     // assure that IDs increments by one during iteration
2513     ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2514     SMESHDS_Mesh*  initMeshDS = initLocMesh.GetMeshDS();
2515     if ( initMeshDS->MaxNodeID()    > initMeshDS->NbNodes() ||
2516          initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2517     {
2518       initMeshDS->Modified();
2519       initMeshDS->CompactMesh();
2520     }
2521
2522     // remember nb of elements before filling in
2523     SMESH::long_array_var prevState =  newMesh->GetNbElementsByType();
2524
2525     // copy nodes
2526
2527     std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2528     SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2529     while ( elemIt->more() )
2530     {
2531       SMESH_NodeXYZ node = elemIt->next();
2532       newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2533     }
2534
2535     // copy elements
2536
2537     std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2538     elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2539     while ( elemIt->more() )
2540     {
2541       const SMDS_MeshElement* elem = elemIt->next();
2542       elemType.myNodes.resize( elem->NbNodes() );
2543
2544       SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2545       for ( int k = 0; itNodes->more(); k++)
2546       {
2547         const SMDS_MeshNode* node = itNodes->next();
2548         elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2549       }
2550
2551       // creates a corresponding element on existent nodes in new mesh
2552       newElems[ elem->GetID() ] =
2553         newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2554     }
2555     newEditor.ClearLastCreated(); // forget the history
2556
2557
2558     // create groups of just added elements
2559     SMESH::SMESH_Group_var newGroup;
2560     SMESH::ElementType     groupType;
2561     if ( theCommonGroups )
2562     {
2563       // type names
2564       const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2565       { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2566         const int nbNames = sizeof(typeNames) / sizeof(const char*);
2567         int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2568       }
2569
2570       SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2571
2572       for( groupType = SMESH::NODE;
2573            groupType < SMESH::NB_ELEMENT_TYPES;
2574            groupType = (SMESH::ElementType)( groupType + 1 ))
2575       {
2576         if ( curState[ groupType ] <= prevState[ groupType ])
2577           continue; // no elements of groupType added from the i-th mesh
2578
2579         // make a group name
2580         std::string groupName = "Gr";
2581         SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2582         if ( meshSO ) {
2583           CORBA::String_var name = meshSO->GetName();
2584           groupName += name;
2585         }
2586         groupName += "_";
2587         groupName += typeNames[ groupType ];
2588
2589         // make and fill a group
2590         newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2591         std::vector< const SMDS_MeshElement* > & elemVec =
2592           ( groupType == SMESH::NODE ) ? newNodes : newElems;
2593         if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2594         {
2595           if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2596           {
2597             for ( size_t j = 0; j < elemVec.size(); ++j )
2598             {
2599               if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2600                 grpDS->Add( elemVec[j] );
2601             }
2602           }
2603         }
2604         listOfNewGroups.clear();
2605         listOfNewGroups.push_back( newGroup );
2606         groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2607                                           listOfNewGroups ));
2608       }
2609     }
2610
2611     if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2612     {
2613       // copy groups
2614
2615       SMESH::SMESH_GroupBase_ptr group;
2616       CORBA::String_var          groupName;
2617       SMESH::long_array_var newIDs = new SMESH::long_array();
2618
2619       // loop on groups of a source mesh
2620       SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2621       for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2622       {
2623         group     = listOfGroups[iG];
2624         groupType = group->GetType();
2625         groupName = group->GetName();
2626         std::string name = groupName.in();
2627
2628         // convert a list of IDs
2629         newIDs->length( group->Size() );
2630         std::vector< const SMDS_MeshElement* > & elemVec =
2631           ( groupType == SMESH::NODE ) ? newNodes : newElems;
2632         SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2633         int nbElems = 0;
2634         while ( itGrElems->more() )
2635         {
2636           const SMDS_MeshElement*    elem = itGrElems->next();
2637           const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2638           if ( newElem )
2639             newIDs[ nbElems++ ] = newElem->GetID();
2640         }
2641         newIDs->length( nbElems );
2642
2643         // check that a current group name and type don't have identical ones in final mesh
2644         listOfNewGroups.clear();
2645         TNameAndType nameAndType( name, groupType );
2646         TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2647         if ( anIter == groupsMap.end() )
2648         {
2649           // add a new group in the mesh
2650           newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2651           newGroup->Add( newIDs );
2652
2653           listOfNewGroups.push_back( newGroup );
2654           groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2655         }
2656         else if ( theUniteIdenticalGroups )
2657         {
2658           // unite identical groups
2659           TListOfNewGroups& aNewGroups = anIter->second;
2660           aNewGroups.front()->Add( newIDs );
2661         }
2662         else
2663         {
2664           // rename identical groups
2665           newGroup = newImpl->CreateGroup( groupType, groupName );
2666           newGroup->Add( newIDs );
2667
2668           TListOfNewGroups& newGroups = anIter->second;
2669           std::string newGroupName;
2670           if ( newGroups.size() == 1 )
2671           {
2672             newGroupName = name + "_1";
2673             newGroups.front()->SetName( newGroupName.c_str() );
2674           }
2675           newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2676           newGroup->SetName( newGroupName.c_str() );
2677           newGroups.push_back( newGroup );
2678         }
2679       } // loop on groups
2680     } // if an IDSource is a mesh
2681   } //meshes loop
2682
2683   if ( theMergeNodesAndElements ) // merge nodes
2684   {
2685     TIDSortedNodeSet meshNodes; // no input nodes == treat all
2686     SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2687     newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2688                                    /*SeparateCornersAndMedium=*/ false );
2689     newEditor.MergeNodes( groupsOfNodes );
2690     // merge elements
2691     newEditor.MergeEqualElements();
2692   }
2693
2694   // Update Python script
2695   pythonDump << newMesh << " = " << this
2696              << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "("
2697              << theMeshesArray << ", "
2698              << theUniteIdenticalGroups << ", "
2699              << theMergeNodesAndElements << ", "
2700              << TVar( theMergeTolerance ) << ")";
2701
2702   pPythonDump.reset(); // enable python dump from GetGroups()
2703
2704   // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2705   if ( !newMesh->_is_nil() )
2706   {
2707     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2708   }
2709
2710   // IPAL21468 Change icon of compound because it need not be computed.
2711   SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2712   SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2713
2714   newMeshDS->Modified();
2715
2716   return newMesh._retn();
2717 }
2718
2719 //================================================================================
2720 /*!
2721  * \brief Create a mesh by copying a part of another mesh
2722  *  \param meshPart - a part of mesh to copy
2723  *  \param toCopyGroups - to create in the new mesh groups
2724  *                        the copied elements belongs to
2725  *  \param toKeepIDs - to preserve IDs of the copied elements or not
2726  *  \retval SMESH::SMESH_Mesh_ptr - the new mesh
2727  */
2728 //================================================================================
2729
2730 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2731                                             const char*               meshName,
2732                                             CORBA::Boolean            toCopyGroups,
2733                                             CORBA::Boolean            toKeepIDs)
2734   throw ( SALOME::SALOME_Exception )
2735 {
2736   Unexpect aCatch(SALOME_SalomeException);
2737
2738   TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2739   std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2740
2741   // 1. Get source mesh
2742
2743   if ( CORBA::is_nil( meshPart ))
2744     THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2745
2746   SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2747   SMESH_Mesh_i*       srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2748   if ( !srcMesh_i )
2749     THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2750
2751   SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2752
2753   // 2. Make a new mesh
2754
2755   SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2756   SMESH_Mesh_i*       newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2757   if ( !newMesh_i )
2758     THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2759   SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2760   if ( !meshSO->_is_nil() )
2761   {
2762     SetName( meshSO, meshName, "Mesh" );
2763     SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2764   }
2765   SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2766   ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2767   ::SMESH_MeshEditor::ElemFeatures elemType;
2768
2769   // 3. Get elements to copy
2770
2771   SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2772   TIDSortedElemSet srcElems;
2773   SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2774   if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2775   {
2776     srcMesh_i->Load();
2777     srcElemIt = srcMeshDS->elementsIterator();
2778     srcNodeIt = srcMeshDS->nodesIterator();
2779   }
2780   else
2781   {
2782     SMESH::long_array_var ids = meshPart->GetIDs();
2783     if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2784     {
2785       for ( CORBA::ULong i=0; i < ids->length(); i++ )
2786         if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2787           srcElems.insert( elem );
2788     }
2789     else
2790     {
2791       for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2792         if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2793           srcElems.insert( elem );
2794     }
2795     if ( srcElems.empty() )
2796       return newMesh._retn();
2797
2798     typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2799     srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2800   }
2801
2802   // 4. Copy elements
2803
2804   typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2805   TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2806   TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2807   int iN;
2808   const SMDS_MeshNode *nSrc, *nTgt;
2809   vector< const SMDS_MeshNode* > nodes;
2810   while ( srcElemIt->more() )
2811   {
2812     const SMDS_MeshElement * elem = srcElemIt->next();
2813     // find / add nodes
2814     nodes.resize( elem->NbNodes());
2815     SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2816     if ( toKeepIDs ) {
2817       for ( iN = 0; nIt->more(); ++iN )
2818       {
2819         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2820         nTgt = newMeshDS->FindNode( nSrc->GetID());
2821         if ( !nTgt )
2822           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2823         nodes[ iN ] = nTgt;
2824       }
2825     }
2826     else {
2827       for ( iN = 0; nIt->more(); ++iN )
2828       {
2829         nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2830         TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2831         if ( !n2n->second )
2832           n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2833         nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2834       }
2835     }
2836     // add elements
2837     if ( elem->GetType() != SMDSAbs_Node )
2838     {
2839       elemType.Init( elem, /*basicOnly=*/false );
2840       if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2841
2842       const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2843       if ( toCopyGroups && !toKeepIDs )
2844         e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2845     }
2846   } // while ( srcElemIt->more() )
2847
2848   // 4(b). Copy free nodes
2849
2850   if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2851   {
2852     while ( srcNodeIt->more() )
2853     {
2854       nSrc = srcNodeIt->next();
2855       if ( nSrc->NbInverseElements() == 0 )
2856       {
2857         if ( toKeepIDs )
2858           nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2859         else
2860           n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2861       }
2862     }
2863   }
2864
2865   // 5. Copy groups
2866
2867   int nbNewGroups = 0;
2868   if ( toCopyGroups )
2869   {
2870     SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2871     while ( gIt->more() )
2872     {
2873       SMESH_Group* group = gIt->next();
2874       const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2875
2876       // Check group type. We copy nodal groups containing nodes of copied element
2877       SMDSAbs_ElementType groupType = groupDS->GetType();
2878       if ( groupType != SMDSAbs_Node &&
2879            newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2880         continue; // group type differs from types of meshPart
2881
2882       // Find copied elements in the group
2883       vector< const SMDS_MeshElement* > groupElems;
2884       SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2885       if ( toKeepIDs )
2886       {
2887         const SMDS_MeshElement* foundElem;
2888         if ( groupType == SMDSAbs_Node )
2889         {
2890           while ( eIt->more() )
2891             if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2892               groupElems.push_back( foundElem );
2893         }
2894         else
2895         {
2896           while ( eIt->more() )
2897             if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2898               groupElems.push_back( foundElem );
2899         }
2900       }
2901       else
2902       {
2903         TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2904         if ( e2eMap.empty() ) continue;
2905         int minID = e2eMap.begin()->first->GetID();
2906         int maxID = e2eMap.rbegin()->first->GetID();
2907         TE2EMap::iterator e2e;
2908         while ( eIt->more() && groupElems.size() < e2eMap.size())
2909         {
2910           const SMDS_MeshElement* e = eIt->next();
2911           if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2912           if ((e2e = e2eMap.find( e )) != e2eMap.end())
2913             groupElems.push_back( e2e->second );
2914         }
2915       }
2916       // Make a new group
2917       if ( !groupElems.empty() )
2918       {
2919         SMESH::SMESH_Group_var newGroupObj =
2920           newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2921         if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2922         {
2923           SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2924           SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2925           for ( unsigned i = 0; i < groupElems.size(); ++i )
2926             smdsGroup.Add( groupElems[i] );
2927
2928           nbNewGroups++;
2929         }
2930       }
2931     }
2932   }
2933
2934   newMeshDS->Modified();
2935
2936   *pyDump << newMesh << " = " << this
2937           << ".CopyMesh( " << meshPart << ", "
2938           << "'" << meshName << "', "
2939           << toCopyGroups << ", "
2940           << toKeepIDs << ")";
2941
2942   pyDumpDeleter.reset(); // allow dump in GetGroups()
2943
2944   if ( nbNewGroups > 0 ) // dump created groups
2945     SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2946
2947   return newMesh._retn();
2948 }
2949
2950
2951 namespace // utils for CopyMeshWithGeom()
2952 {
2953   typedef std::map< std::string, std::string >             TStr2StrMap;
2954   typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
2955
2956   //================================================================================
2957   /*!
2958    * \brief Return a new sub-shape corresponding to an old one
2959    */
2960   //================================================================================
2961
2962   struct ShapeMapper
2963   {
2964     SMESH_Mesh_i* mySrcMesh_i;
2965     SMESH_Mesh_i* myNewMesh_i;
2966     SMESH_Gen_i*  myGen_i;
2967     bool          myToPublish;
2968     bool          myIsSameGeom;
2969
2970     TStr2StrMap   myOld2NewEntryMap; // map of study entries
2971
2972     bool                       myGIPMapDone;
2973     GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
2974
2975     // not directly relating to shape search
2976     TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
2977
2978     //================================================================================
2979     /*!
2980      * \brief Constructor
2981      */
2982     ShapeMapper( SMESH_Mesh_i* srcMesh_i,
2983                  SMESH_Mesh_i* newMesh_i,
2984                  SMESH_Gen_i*  smeshGen_i )
2985       : mySrcMesh_i( srcMesh_i ),
2986         myNewMesh_i( newMesh_i ),
2987         myGen_i    ( smeshGen_i ),
2988         myToPublish( smeshGen_i->IsEnablePublish() ),
2989         myGIPMapDone( false )
2990     {
2991       // retrieve from the study shape mapping made thanks to
2992       // "Set presentation parameters and sub-shapes from arguments" option
2993
2994       GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
2995       GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
2996       SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
2997       SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
2998       if ( newSO->_is_nil() )
2999       {
3000         myToPublish = false;
3001         return;
3002       }
3003       if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3004         return;
3005       CORBA::String_var oldEntry = oldSO->GetID();
3006       CORBA::String_var newEntry = newSO->GetID();
3007       myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3008                                                 std::string( newEntry.in() )));
3009
3010       SALOMEDS::Study_var            study = myGen_i->getStudyServant();
3011       GEOM::GEOM_Gen_var           geomGen = myGen_i->GetGeomEngine();
3012       GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3013       GEOM::ListOfGO_var         subShapes = op->GetExistingSubObjects( mainShapeNew,
3014                                                                         /*groupsOnly=*/false );
3015       for ( CORBA::ULong i = 0; i < subShapes->length(); ++i )
3016       {
3017         newSO = myGen_i->ObjectToSObject( subShapes[ i ]);
3018         SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3019         for ( ; anIter->More(); anIter->Next() )
3020         {
3021           SALOMEDS::SObject_wrap so = anIter->Value();
3022           if ( so->ReferencedObject( oldSO.inout() ))
3023           {
3024             oldEntry = oldSO->GetID();
3025             newEntry = newSO->GetID();
3026             myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3027                                                       std::string( newEntry.in() )));
3028           }
3029         }
3030       }
3031     }
3032
3033     //================================================================================
3034     /*!
3035      * \brief Find a new sub-shape corresponding to an old one
3036      */
3037     GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3038     {
3039       if ( myIsSameGeom )
3040         return GEOM::GEOM_Object::_duplicate( oldShape );
3041
3042       GEOM::GEOM_Object_var newShape;
3043
3044       if ( CORBA::is_nil( oldShape ))
3045         return newShape._retn();
3046
3047       if ( !isChildOfOld( oldShape ))
3048         return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3049
3050       GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3051       GEOM::GEOM_Gen_var         geomGen = myGen_i->GetGeomEngine();
3052
3053       // try to find by entry
3054       if ( myToPublish )
3055       {
3056         CORBA::String_var  oldEntry = oldShape->GetStudyEntry();
3057         TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3058         if ( o2nID != myOld2NewEntryMap.end() )
3059         {
3060           newShape = getShapeByEntry( o2nID->second );
3061         }
3062       }
3063
3064       if ( newShape->_is_nil() )
3065       {
3066         // try to construct a new sub-shape using myGIPMap
3067         buildGIPMap();
3068         std::vector< int >   newIndices;
3069         GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3070         for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3071         {
3072           findNewIDs( oldIndices[i], newIndices );
3073         }
3074         if ( !newIndices.empty() )
3075         {
3076           try
3077           {
3078             if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3079             {
3080               int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3081
3082               GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3083               newShape = grOp->CreateGroup( mainShapeNew, groupType );
3084
3085               GEOM::ListOfLong_var  newIndicesList = new GEOM::ListOfLong();
3086               newIndicesList->length( newIndices.size() );
3087               for ( size_t i = 0; i < newIndices.size(); ++i )
3088                 newIndicesList[ i ] = newIndices[ i ];
3089               grOp->UnionIDs( newShape, newIndicesList );
3090             }
3091             else
3092             {
3093               GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3094               newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3095             }
3096           }
3097           catch (...)
3098           {
3099           }
3100         }
3101       }
3102
3103       if ( !newShape->_is_nil() && myToPublish )
3104       {
3105         CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3106         if ( !newEntry.in() || !newEntry.in()[0] )
3107         {
3108           CORBA::String_var    name = oldShape->GetName();
3109           SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3110           newEntry = newShape->GetStudyEntry();
3111           oldEntry = oldShape->GetStudyEntry();
3112           myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3113                                                     std::string( newEntry.in() )));
3114         }
3115       }
3116
3117       return newShape._retn();
3118     }
3119
3120     //================================================================================
3121     /*!
3122      * \brief Return a study entry of a new shape by study entry of the old one
3123      */
3124     std::string FindNew( const std::string & oldEntry )
3125     {
3126       if ( myIsSameGeom )
3127         return oldEntry;
3128
3129       TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3130       if ( o2nID != myOld2NewEntryMap.end() )
3131         return o2nID->second;
3132
3133       GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3134       if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3135         return oldEntry;
3136
3137       GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3138       if ( newShape->_is_nil() )
3139         return std::string();
3140
3141       CORBA::String_var newEntry = newShape->GetStudyEntry();
3142       return newEntry.in();
3143     }
3144
3145     //================================================================================
3146     /*!
3147      * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3148      *        Return zero if not found or there are more than one new ID
3149      */
3150     int FindNew( int oldID )
3151     {
3152       if ( myIsSameGeom )
3153         return oldID;
3154
3155       buildGIPMap();
3156
3157       int newID = 0;
3158
3159       if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3160       {
3161         if (( myGIPMap[ oldID ].length() == 1 ) ||
3162             ( myGIPMap[ oldID ].length() > 1 &&
3163               getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX ))
3164         {
3165           newID = myGIPMap[ oldID ][ 0 ];
3166         }
3167       }
3168       return newID;
3169     }
3170
3171     //================================================================================
3172     /*!
3173      * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3174      *        Return zero if the old shape is not kept as is in the new shape.
3175      */
3176     int FindNewNotChanged( SMESH_subMesh* oldSM )
3177     {
3178       if ( myIsSameGeom )
3179         return oldSM->GetId();
3180
3181       int newID = FindNew( oldSM->GetId() );
3182       if ( !newID )
3183         return 0;
3184
3185       SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3186       if ( !newSM )
3187         return 0;
3188
3189       // consider a sub-shape as not changed if all its sub-shapes are mapped into
3190       // one new sub-shape of the same type.
3191
3192       if ( oldSM->DependsOn().size() !=
3193            newSM->DependsOn().size() )
3194         return 0;
3195
3196       SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3197       while ( srcSMIt->more() )
3198       {
3199         oldSM = srcSMIt->next();
3200         int newSubID = FindNew( oldSM->GetId() );
3201         if ( getShapeType( myNewMesh_i, newSubID ) !=
3202              getShapeType( mySrcMesh_i, oldSM->GetId() ))
3203           return 0;
3204       }
3205       return newID;
3206     }
3207
3208     //================================================================================
3209     /*!
3210      * \brief Return shape by study entry
3211      */
3212     GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3213     {
3214       GEOM::GEOM_Object_var shape;
3215       SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3216       if ( !so->_is_nil() )
3217       {
3218         CORBA::Object_var obj = so->GetObject();
3219         shape = GEOM::GEOM_Object::_narrow( obj );
3220       }
3221       return shape._retn();
3222     }
3223
3224     //================================================================================
3225     /*!
3226      * \brief Fill myGIPMap by calling GetInPlaceMap()
3227      */
3228     void buildGIPMap()
3229     {
3230       if ( !myGIPMapDone )
3231       {
3232         myGIPMapDone = true;
3233
3234         GEOM::GEOM_Object_var   mainShapeNew = myNewMesh_i->GetShapeToMesh();
3235         GEOM::GEOM_Object_var   mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3236         GEOM::GEOM_Gen_var           geomGen = myGen_i->GetGeomEngine();
3237         GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3238         try
3239         {
3240           myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3241         }
3242         catch( ... )
3243         {
3244           myGIPMap = new GEOM::ListOfListOfLong();
3245         }
3246       }
3247     }
3248
3249     //================================================================================
3250     /*!
3251      * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3252      *        number of found IDs
3253      */
3254     int findNewIDs( int oldID, std::vector< int >& newIDs  )
3255     {
3256       size_t prevNbIDs = newIDs.size();
3257
3258       if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3259       {
3260         for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3261           newIDs.push_back( myGIPMap[ oldID ][ i ]);
3262       }
3263       return newIDs.size() - prevNbIDs;
3264     }
3265
3266     //================================================================================
3267     /*!
3268      * \brief Check if an object relates to the old shape
3269      */
3270     bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3271     {
3272       if ( CORBA::is_nil( oldShape ))
3273         return false;
3274       GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3275       GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3276       return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3277                mainShapeOld1->_is_equivalent( oldShape ));
3278     }
3279
3280     //================================================================================
3281     /*!
3282      * \brief Return shape type by shape ID
3283      */
3284     TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3285     {
3286       SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3287       const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3288       return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3289     }
3290
3291     //================================================================================
3292     /*!
3293      * \brief Store a source sub-shape for which a counterpart not found and
3294      *        a smesh object invalid due to that
3295      */
3296     void AddInvalid( GEOM::GEOM_Object_var  srcShape,
3297                      SALOMEDS::SObject_wrap smeshSO )
3298     {
3299       CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3300       if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3301       {
3302         CORBA::String_var smeshEntry = smeshSO->GetID();
3303         myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3304       }
3305     }
3306
3307     //================================================================================
3308     /*!
3309      * \brief Store a source sub-shape for which a counterpart not found and
3310      *        a smesh object invalid due to that
3311      */
3312     void AddInvalid( std::string            geomEntry,
3313                      SALOMEDS::SObject_wrap smeshSO )
3314     {
3315       if ( !geomEntry.empty() )
3316       {
3317         CORBA::String_var smeshEntry = smeshSO->GetID();
3318         myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3319       }
3320     }
3321
3322     //================================================================================
3323     /*!
3324      * \brief Store a source sub-shape for which a counterpart not found and
3325      *        a smesh object invalid due to that
3326      */
3327     void AddInvalid( int                    oldGeomID,
3328                      SALOMEDS::SObject_wrap smeshSO )
3329     {
3330       int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3331       if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3332         return;
3333
3334       const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3335                                  "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3336
3337       SMESH_Comment geomName( typeName[ shapeType ]);
3338       geomName << " #" << oldGeomID;
3339
3340       CORBA::String_var smeshEntry = smeshSO->GetID();
3341       myInvalidMap[ geomName ].insert( smeshEntry.in() );
3342     }
3343
3344     //================================================================================
3345     /*!
3346      * \brief Return entries of a source sub-shape for which a counterpart not found and
3347      *        of smesh objects invalid due to that
3348      */
3349     void GetInvalid( SMESH::string_array_out &               theInvalidEntries,
3350                      std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3351     {
3352       int nbSO = 0;
3353       TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3354       for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3355       {
3356         nbSO += 1 + entry2entrySet->second.size();
3357       }
3358       int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3359       theInvalidEntries->length  ( nbSO );
3360       theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3361
3362       entry2entrySet = myInvalidMap.begin();
3363       for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3364       {
3365         theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3366
3367         std::set< std::string > & entrySet = entry2entrySet->second;
3368         std::set< std::string >::iterator entry = entrySet.begin();
3369         for ( ; entry != entrySet.end(); ++entry )
3370         {
3371           theInvalidEntries[ iEntry++ ] = entry->c_str();
3372
3373           SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3374           if ( !so->_is_nil() )
3375             theInvalidMeshSObjects[ iSO++ ] = so;
3376         }
3377       }
3378     }
3379
3380   }; // struct ShapeMapper
3381
3382   //================================================================================
3383   /*!
3384    * \brief Append an item to a CORBA sequence
3385    */
3386   template < class CORBA_seq, class ITEM >
3387   void append( CORBA_seq& seq, ITEM item )
3388   {
3389     if ( !CORBA::is_nil( item ))
3390     {
3391       seq->length( 1 + seq->length() );
3392       seq[ seq->length() - 1 ] = item;
3393     }
3394   }
3395 }
3396
3397 //================================================================================
3398 /*!
3399  * \brief Create a mesh by copying definitions of another mesh to a given geometry
3400  *  \param [in] sourceMesh - a mesh to copy
3401  *  \param [in] newGeometry - a new geometry
3402  *  \param [in] toCopyGroups - to create groups in the new mesh
3403  *  \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3404  *         otherwise new hypotheses with the same parameters will be created for the new mesh.
3405  *  \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3406  *  \param [out] newMesh - return a new mesh
3407  *  \param [out] newGroups - return new groups
3408  *  \param [out] newSubmeshes - return new sub-meshes
3409  *  \param [out] newHypotheses - return new algorithms and hypotheses
3410  *  \param [out] invalidEntries - return study entries of objects whose
3411  *         counterparts are not found in the newGeometry, followed by entries
3412  *         of mesh sub-objects that are invalid because they depend on a not found
3413  *         preceeding sub-shape
3414  *  \return CORBA::Boolean - is a success
3415  */
3416 //================================================================================
3417
3418 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr       theSourceMesh,
3419                                               GEOM::GEOM_Object_ptr       theNewGeometry,
3420                                               const char*                 theMeshName,
3421                                               CORBA::Boolean              theToCopyGroups,
3422                                               CORBA::Boolean              theToReuseHypotheses,
3423                                               CORBA::Boolean              theToCopyElements,
3424                                               SMESH::SMESH_Mesh_out       theNewMesh,
3425                                               SMESH::ListOfGroups_out     theNewGroups,
3426                                               SMESH::submesh_array_out    theNewSubmeshes,
3427                                               SMESH::ListOfHypothesis_out theNewHypotheses,
3428                                               SMESH::string_array_out     theInvalidEntries)
3429 throw ( SALOME::SALOME_Exception )
3430 {
3431   if ( CORBA::is_nil( theSourceMesh ) ||
3432        CORBA::is_nil( theNewGeometry ))
3433     THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3434
3435   if ( !theSourceMesh->HasShapeToMesh() )
3436     THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3437
3438   bool ok = true;
3439   SMESH_TRY;
3440
3441   TPythonDump pyDump; // prevent dump from CreateMesh()
3442
3443   theNewMesh        = CreateMesh( theNewGeometry );
3444   theNewGroups      = new SMESH::ListOfGroups();
3445   theNewSubmeshes   = new SMESH::submesh_array();
3446   theNewHypotheses  = new SMESH::ListOfHypothesis();
3447   theInvalidEntries = new SMESH::string_array();
3448
3449   std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3450
3451   GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3452   GEOM::GEOM_Object_var geom, newGeom;
3453   SALOMEDS::SObject_wrap so;
3454
3455   SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3456   SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3457   srcMesh_i->Load();
3458
3459   ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3460
3461   // treat hypotheses of mesh and sub-meshes
3462   SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3463   for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3464   {
3465     bool isSubMesh = ( iSM < smList->length() );
3466     if ( isSubMesh )
3467     {
3468       // create a new sub-mesh
3469       SMESH::SMESH_subMesh_var newSM;
3470       geom = smList[iSM]->GetSubShape();
3471       so   = ObjectToSObject( smList[iSM] );
3472       CORBA::String_var name;
3473       if ( !so->_is_nil() )
3474         name = so->GetName();
3475       newGeom = shapeMapper.FindNew( geom );
3476       if ( newGeom->_is_nil() )
3477       {
3478         newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3479         shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3480         ok = false;
3481       }
3482       else
3483       {
3484         newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3485       }
3486       append( theNewSubmeshes, newSM );
3487
3488       if ( newGeom->_is_nil() )
3489         continue; // don't assign hypotheses
3490     }
3491     else
3492     {
3493       newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3494       geom    = srcGeom;
3495       so      = ObjectToSObject( theNewMesh );
3496       SetName( so, theMeshName, "Mesh" );
3497     }
3498
3499     // assign hypotheses
3500     SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3501     for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3502     {
3503       SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3504       SMESH_Hypothesis_i*       hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3505
3506       // get geometry hyp depends on
3507       std::vector< std::string > entryArray;
3508       std::vector< int >         subIDArray;
3509       bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3510
3511       if ( !theToReuseHypotheses || dependsOnGeom )
3512       {
3513         // create a new hypothesis
3514         CORBA::String_var type = hyp->GetName();
3515         CORBA::String_var lib  = hyp->GetLibName();
3516         CORBA::String_var data = hyp_i->SaveTo();
3517         if ( data.in()[0] )
3518         {
3519           hyp   = CreateHypothesis( type, lib );
3520           hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3521           hyp_i->LoadFrom( data.in() );
3522           append( theNewHypotheses, hyp );
3523         }
3524       }
3525
3526       // update geometry hyp depends on
3527       if ( dependsOnGeom )
3528       {
3529         for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3530         {
3531           if ( !entryArray[ iGeo ].empty() )
3532           {
3533             std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3534             if ( newEntry.empty() )
3535             {
3536               ok = false;
3537               shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3538               shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3539             }
3540             entryArray[ iGeo ] = newEntry;
3541           }
3542         }
3543         for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3544         {
3545           if ( subIDArray[ iGeo ] > 0 )
3546           {
3547             int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3548             if ( newID < 1 )
3549             {
3550               ok = false;
3551               shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3552               shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3553             }
3554             subIDArray[ iGeo ] = newID;
3555           }
3556         }
3557         if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3558           ok = false;
3559       }
3560
3561       CORBA::String_var errorText;
3562       theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3563       if ( errorText.in()[0] )
3564         ok = false;
3565
3566     } // loop on hypotheses
3567   } // loop on sub-meshes and mesh
3568
3569
3570   // copy mesh elements, keeping IDs
3571   SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3572   if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3573   {
3574     ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3575     ::SMESH_MeshEditor::ElemFeatures elemData;
3576
3577     SMESH_subMesh*         srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3578     SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3579                                                                         /*vertexLast=*/false);
3580     while ( srcSMIt->more() )
3581     {
3582       SMESH_subMesh* srcSM = srcSMIt->next();
3583       if ( srcSM->IsEmpty() )
3584         continue; // not yet computed
3585       int newID = shapeMapper.FindNewNotChanged( srcSM );
3586       if ( newID < 1 )
3587         continue;
3588
3589       SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3590       SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3591       while ( nIt->more() )
3592       {
3593         SMESH_NodeXYZ node( nIt->next() );
3594         const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3595                                                                  node->GetID() );
3596         const SMDS_PositionPtr pos = node->GetPosition();
3597         const double*           uv = pos->GetParameters();
3598         switch ( pos->GetTypeOfPosition() )
3599         {
3600         case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID );               break;
3601         case SMDS_TOP_FACE:    newMeshDS->SetNodeOnFace  ( newNode, newID, uv[0], uv[1] ); break;
3602         case SMDS_TOP_EDGE:    newMeshDS->SetNodeOnEdge  ( newNode, newID, uv[0] );        break;
3603         case SMDS_TOP_VERTEX:  newMeshDS->SetNodeOnVertex( newNode, newID );               break;
3604         default: ;
3605         }
3606       }
3607       SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3608       while( eIt->more() )
3609       {
3610         const SMDS_MeshElement* e = eIt->next();
3611         elemData.Init( e, /*basicOnly=*/false );
3612         elemData.SetID( e->GetID() );
3613         elemData.myNodes.resize( e->NbNodes() );
3614         SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3615         size_t iN;
3616         for ( iN = 0; nnIt->more(); ++iN )
3617         {
3618           const SMDS_MeshNode* srcNode = nnIt->next();
3619           elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3620           if ( !elemData.myNodes[ iN ])
3621             break;
3622         }
3623         if ( iN == elemData.myNodes.size() )
3624           if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3625             newMeshDS->SetMeshElementOnShape( newElem, newID );
3626       }
3627       if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3628         newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3629     }
3630   }
3631
3632
3633   // treat groups
3634
3635   TStr2StrMap old2newGroupMap;
3636
3637   SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3638
3639   SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3640   CORBA::ULong nbGroups = groups->length(), nbAddedGroups = 0;
3641   for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3642   {
3643     SMESH::SMESH_Group_var         stdlGroup = SMESH::SMESH_Group::_narrow        ( groups[ i ]);
3644     SMESH::SMESH_GroupOnGeom_var   geomGroup = SMESH::SMESH_GroupOnGeom::_narrow  ( groups[ i ]);
3645     SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3646
3647     CORBA::String_var      name = groups[ i ]->GetName();
3648     SMESH::ElementType elemType = groups[ i ]->GetType();
3649
3650     SMESH::SMESH_GroupBase_var newGroup;
3651
3652     if ( !stdlGroup->_is_nil() )
3653     {
3654       if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3655       {
3656         SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3657         const bool isElem = ( elemType != SMESH::NODE );
3658         CORBA::ULong iE = 0;
3659         for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3660           if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3661             break;
3662         if ( iE < elemIDs->length() )
3663         {
3664           stdlGroup = theNewMesh->CreateGroup( elemType, name );
3665           stdlGroup->Add( elemIDs );
3666           newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3667         }
3668       }
3669     }
3670     else if ( !geomGroup->_is_nil() )
3671     {
3672       GEOM::GEOM_Object_var    geom = geomGroup->GetShape();
3673       GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3674       if ( newGeom->_is_nil() )
3675       {
3676         newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3677         shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3678         ok = false;
3679       }
3680       else
3681       {
3682         newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3683       }
3684     }
3685     else if ( !fltrGroup->_is_nil() )
3686     {
3687       // replace geometry in a filter
3688       SMESH::Filter_var filter = fltrGroup->GetFilter();
3689       SMESH::Filter::Criteria_var criteria;
3690       filter->GetCriteria( criteria.out() );
3691
3692       bool isMissingGroup = false;
3693       std::vector< std::string > badEntries;
3694
3695       for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3696       {
3697         const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3698         switch ( criteria[ iCr ].Type )
3699         {
3700         case SMESH::FT_BelongToMeshGroup:
3701         {
3702           SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3703           btgg->SetGroupID( thresholdID );
3704           SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3705           SALOMEDS::SObject_wrap   refGroupSO = ObjectToSObject( refGroup );
3706           if ( refGroupSO->_is_nil() )
3707             break;
3708           CORBA::String_var     refID = refGroupSO->GetID();
3709           TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3710           if ( o2nID == old2newGroupMap.end() )
3711           {
3712             isMissingGroup = true; // corresponding new group not yet created
3713             break;
3714           }
3715           criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3716
3717           if ( o2nID->second.empty() ) // new referred group is invalid
3718             badEntries.push_back( refID.in() );
3719           break;
3720         }
3721         case SMESH::FT_BelongToGeom:
3722         case SMESH::FT_BelongToPlane:
3723         case SMESH::FT_BelongToCylinder:
3724         case SMESH::FT_BelongToGenSurface:
3725         case SMESH::FT_LyingOnGeom:
3726         {
3727           std::string newID = shapeMapper.FindNew( thresholdID );
3728           criteria[ iCr ].ThresholdID = newID.c_str();
3729           if ( newID.empty() )
3730             badEntries.push_back( thresholdID );
3731           break;
3732         }
3733         case SMESH::FT_ConnectedElements:
3734         {
3735           if ( thresholdID && thresholdID[0] )
3736           {
3737             std::string newID = shapeMapper.FindNew( thresholdID );
3738             criteria[ iCr ].ThresholdID = newID.c_str();
3739             if ( newID.empty() )
3740               badEntries.push_back( thresholdID );
3741           }
3742           break;
3743         }
3744         default:;
3745         }
3746       } // loop on criteria
3747
3748       if ( isMissingGroup && i < nbGroups )
3749       {
3750         // to treat the group again
3751         append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3752         ++nbAddedGroups;
3753         continue;
3754       }
3755       SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3756       newFilter->SetCriteria( criteria );
3757
3758       newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3759       newFilter->UnRegister();
3760
3761       SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3762       for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3763         shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3764
3765       if ( isMissingGroup ) // all groups treated but a referred groups still not found
3766       {
3767         invalidSObjects.push_back( ObjectToSObject( newGroup ));
3768         ok = false;
3769       }
3770       if ( !badEntries.empty() )
3771         ok = false;
3772
3773     } // treat a group on filter
3774
3775     append( theNewGroups, newGroup );
3776
3777     // fill old2newGroupMap
3778     SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3779     SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3780     if ( !srcSO->_is_nil() )
3781     {
3782       CORBA::String_var srcID, newID("");
3783       srcID = srcSO->GetID();
3784       if ( !newSO->_is_nil() )
3785         newID = newSO->GetID();
3786       old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3787                                               std::string( newID.in() )));
3788     }
3789
3790     if ( newGroup->_is_nil() )
3791       ok = false;
3792
3793   } // loop on groups
3794
3795   // set mesh name
3796   if ( !theMeshName || !theMeshName[0] )
3797   {
3798     SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
3799     SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
3800     CORBA::String_var oldName = soOld->GetName();
3801     SetName( soNew, oldName.in(), "Mesh" );
3802   }
3803   // mark invalid objects
3804   shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3805
3806   for ( size_t i = 0; i < invalidSObjects.size(); ++i )
3807     highLightInvalid( invalidSObjects[i].in(), true );
3808
3809   pyDump << "ok, "
3810          << theNewMesh << ", "
3811          << theNewGroups << ", "
3812          << *theNewSubmeshes.ptr() << ", "
3813          << *theNewHypotheses.ptr() << ", "
3814          << "invalidEntries = " << this << ".CopyMeshWithGeom( "
3815          << theSourceMesh << ", "
3816          << theNewGeometry << ", "
3817          << "'" << theMeshName << "', "
3818          << theToCopyGroups << ", "
3819          << theToReuseHypotheses << ", "
3820          << theToCopyElements << " )";
3821
3822   SMESH_CATCH( SMESH::throwCorbaException );
3823
3824   return ok;
3825 }
3826
3827 //================================================================================
3828 /*!
3829  * \brief Get version of MED format being used.
3830  */
3831 //================================================================================
3832
3833 char* SMESH_Gen_i::GetMEDFileVersion()
3834 {
3835   MED::TInt majeur, mineur, release;
3836   majeur =  mineur = release = 0;
3837   MED::GetVersionRelease(majeur, mineur, release);
3838   std::ostringstream version;
3839   version << majeur << "." << mineur << "." << release;
3840   return CORBA::string_dup( version.str().c_str() );
3841 }
3842
3843 //================================================================================
3844 /*!
3845  *  SMESH_Gen_i::GetMEDVersion
3846  *
3847  *  Get MED version of the file by its name
3848  */
3849 //================================================================================
3850 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
3851 {
3852   std::string version = MED::GetMEDVersion( theFileName );
3853   return CORBA::string_dup( version.c_str() );
3854 }
3855
3856 //================================================================================
3857 /*!
3858  *  SMESH_Gen_i::CheckCompatibility
3859  *
3860  *  Check compatibility of file with MED format being used, read only.
3861  */
3862 //================================================================================
3863 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
3864 {
3865   return MED::CheckCompatibility( theFileName );
3866 }
3867
3868 //================================================================================
3869 /*!
3870  *  SMESH_Gen_i::CheckWriteCompatibility
3871  *
3872  *  Check compatibility of file with MED format being used, for append on write.
3873  */
3874 //================================================================================
3875 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
3876 {
3877   return MED::CheckCompatibility( theFileName, true );
3878 }
3879
3880 //================================================================================
3881 /*!
3882  *  SMESH_Gen_i::GetMeshNames
3883  *
3884  *  Get names of meshes defined in file with the specified name
3885  */
3886 //================================================================================
3887 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
3888 {
3889   //MESSAGE("GetMeshNames " << theFileName);
3890   SMESH::string_array_var aResult = new SMESH::string_array();
3891   MED::PWrapper aMed = MED::CrWrapperR( theFileName );
3892   MED::TErr anErr;
3893   MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
3894   //MESSAGE("---" << aNbMeshes);
3895   if( anErr >= 0 ) {
3896     aResult->length( aNbMeshes );
3897     for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
3898       MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
3899       aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
3900     }
3901   }
3902   return aResult._retn();
3903 }
3904
3905 //=============================================================================
3906 /*!
3907  *  SMESH_Gen_i::Save
3908  *
3909  *  Save SMESH module's data
3910  */
3911 //=============================================================================
3912 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
3913                                       const char*              theURL,
3914                                       bool                     isMultiFile )
3915 {
3916   if (!myStudyContext)
3917     UpdateStudy();
3918
3919   // Store study contents as a set of python commands
3920   SavePython();
3921
3922   SALOMEDS::Study_var aStudy = getStudyServant();
3923
3924   // Declare a byte stream
3925   SALOMEDS::TMPFile_var aStreamFile;
3926
3927   // Obtain a temporary dir
3928   TCollection_AsciiString tmpDir =
3929     ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3930
3931   // Create a sequence of files processed
3932   SALOMEDS_Tool::ListOfFiles aFileSeq;
3933   aFileSeq.reserve( NUM_TMP_FILES );
3934
3935   TCollection_AsciiString aStudyName( "" );
3936   if ( isMultiFile )
3937     aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
3938
3939   // Set names of temporary files
3940   TCollection_AsciiString filename =
3941     aStudyName + TCollection_AsciiString( "_SMESH.hdf" );        // for SMESH data itself
3942   TCollection_AsciiString meshfile =
3943     aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" );   // for mesh data to be stored in MED file
3944   aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
3945   aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
3946   filename = tmpDir + filename;
3947   meshfile = tmpDir + meshfile;
3948
3949   HDFfile*    aFile;
3950   HDFdataset* aDataset;
3951   HDFgroup*   aTopGroup;
3952   HDFgroup*   aGroup;
3953   HDFgroup*   aSubGroup;
3954   HDFgroup*   aSubSubGroup;
3955   hdf_size    aSize[ 1 ];
3956
3957
3958   //Remove the files if they exist: BugID: 11225
3959 #ifndef WIN32 /* unix functionality */
3960   TCollection_AsciiString cmd("rm -f \"");
3961 #else /* windows */
3962   TCollection_AsciiString cmd("del /F \"");
3963 #endif
3964
3965   cmd+=filename;
3966   cmd+="\" \"";
3967   cmd+=meshfile;
3968   cmd+="\"";
3969   system(cmd.ToCString());
3970
3971   // MED writer to be used by storage process
3972   DriverMED_W_SMESHDS_Mesh myWriter;
3973   myWriter.SetFile( meshfile.ToCString() );
3974
3975   // IMP issue 20918
3976   // SetStoreName() to groups before storing hypotheses to let them refer to
3977   // groups using "store name", which is "Group <group_persistent_id>"
3978   {
3979     SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
3980     for ( ; itBig->More(); itBig->Next() ) {
3981       SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3982       if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3983         CORBA::Object_var anObject = SObjectToObject( gotBranch );
3984         if ( !CORBA::is_nil( anObject ) ) {
3985           SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3986           if ( !myMesh->_is_nil() ) {
3987             myMesh->Load(); // load from study file if not yet done
3988             TPythonDump pd; // not to dump GetGroups()
3989             SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3990             for ( CORBA::ULong i = 0; i < groups->length(); ++i )
3991             {
3992               SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3993               if ( grImpl )
3994               {
3995                 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3996                 int anId = myStudyContext->findId( string( objStr.in() ) );
3997                 char grpName[ 30 ];
3998                 sprintf( grpName, "Group %d", anId );
3999                 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4000                 aGrpBaseDS->SetStoreName( grpName );
4001               }
4002             }
4003           }
4004         }
4005       }
4006     }
4007   }
4008
4009   // Write data
4010   // ---> create HDF file
4011   aFile = new HDFfile( (char*) filename.ToCString() );
4012   aFile->CreateOnDisk();
4013
4014   // --> iterator for top-level objects
4015   SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4016   for ( ; itBig->More(); itBig->Next() ) {
4017     SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4018
4019     // --> hypotheses root branch (only one for the study)
4020     if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4021       // create hypotheses root HDF group
4022       aTopGroup = new HDFgroup( "Hypotheses", aFile );
4023       aTopGroup->CreateOnDisk();
4024
4025       // iterator for all hypotheses
4026       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4027       for ( ; it->More(); it->Next() ) {
4028         SALOMEDS::SObject_wrap mySObject = it->Value();
4029         CORBA::Object_var anObject = SObjectToObject( mySObject );
4030         if ( !CORBA::is_nil( anObject ) ) {
4031           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4032           if ( !myHyp->_is_nil() ) {
4033             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4034             if ( myImpl ) {
4035               CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4036               std::string hypname = hn.in();
4037               std::string libname = ln.in();
4038               // BUG SWP13062
4039               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4040               // WIN32 and ".so" for X-system) must be deleted
4041               int libname_len = libname.length();
4042 #ifdef WIN32
4043               if( libname_len > 4 )
4044                 libname.resize( libname_len - 4 );
4045 #else
4046               // PAL17753 (Regression: missing hypothesis in restored study)
4047               // "lib" also should be removed from the beginning
4048               //if( libname_len > 3 )
4049               //libname.resize( libname_len - 3 );
4050               if( libname_len > 6 )
4051                 libname = libname.substr( 3, libname_len - 3 - 3 );
4052 #endif
4053               CORBA::String_var  objStr = GetORB()->object_to_string( anObject );
4054               CORBA::String_var hypdata = myImpl->SaveTo();
4055               int                    id = myStudyContext->findId( string( objStr.in() ));
4056
4057               // for each hypothesis create HDF group basing on its id
4058               char hypGrpName[30];
4059               sprintf( hypGrpName, "Hypothesis %d", id );
4060               aGroup = new HDFgroup( hypGrpName, aTopGroup );
4061               aGroup->CreateOnDisk();
4062               // --> type name of hypothesis
4063               aSize[ 0 ] = hypname.length() + 1;
4064               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4065               aDataset->CreateOnDisk();
4066               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4067               aDataset->CloseOnDisk();
4068               // --> server plugin library name of hypothesis
4069               aSize[ 0 ] = libname.length() + 1;
4070               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4071               aDataset->CreateOnDisk();
4072               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4073               aDataset->CloseOnDisk();
4074               // --> persistent data of hypothesis
4075               aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4076               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4077               aDataset->CreateOnDisk();
4078               aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4079               aDataset->CloseOnDisk();
4080               // close hypothesis HDF group
4081               aGroup->CloseOnDisk();
4082             }
4083           }
4084         }
4085       }
4086       // close hypotheses root HDF group
4087       aTopGroup->CloseOnDisk();
4088     }
4089     // --> algorithms root branch (only one for the study)
4090     else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4091       // create algorithms root HDF group
4092       aTopGroup = new HDFgroup( "Algorithms", aFile );
4093       aTopGroup->CreateOnDisk();
4094
4095       // iterator for all algorithms
4096       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4097       for ( ; it->More(); it->Next() ) {
4098         SALOMEDS::SObject_wrap mySObject = it->Value();
4099         CORBA::Object_var anObject = SObjectToObject( mySObject );
4100         if ( !CORBA::is_nil( anObject ) ) {
4101           SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4102           if ( !myHyp->_is_nil() ) {
4103             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4104             if ( myImpl ) {
4105               CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4106               std::string hypname = hn.in();
4107               std::string libname = ln.in();
4108               // BUG SWP13062
4109               // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4110               // WIN32 and ".so" for X-system) must be deleted
4111               int libname_len = libname.length();
4112 #ifdef WIN32
4113               if( libname_len > 4 )
4114                 libname.resize( libname_len - 4 );
4115 #else
4116               // PAL17753 (Regression: missing hypothesis in restored study)
4117               // "lib" also should be removed from the beginning
4118               //if( libname_len > 3 )
4119               //libname.resize( libname_len - 3 );
4120               if( libname_len > 6 )
4121                 libname = libname.substr( 3, libname_len - 3 - 3 );
4122 #endif
4123               CORBA::String_var  objStr = GetORB()->object_to_string( anObject );
4124               CORBA::String_var hypdata = myImpl->SaveTo();
4125               int                    id = myStudyContext->findId( string( objStr.in() ) );
4126
4127               // for each algorithm create HDF group basing on its id
4128               char hypGrpName[30];
4129               sprintf( hypGrpName, "Algorithm %d", id );
4130               aGroup = new HDFgroup( hypGrpName, aTopGroup );
4131               aGroup->CreateOnDisk();
4132               // --> type name of algorithm
4133               aSize[0] = hypname.length() + 1;
4134               aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4135               aDataset->CreateOnDisk();
4136               aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4137               aDataset->CloseOnDisk();
4138               // --> server plugin library name of hypothesis
4139               aSize[0] = libname.length() + 1;
4140               aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4141               aDataset->CreateOnDisk();
4142               aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4143               aDataset->CloseOnDisk();
4144               // --> persistent data of algorithm
4145               aSize[0] = strlen( hypdata.in() ) + 1;
4146               aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4147               aDataset->CreateOnDisk();
4148               aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4149               aDataset->CloseOnDisk();
4150               // close algorithm HDF group
4151               aGroup->CloseOnDisk();
4152             }
4153           }
4154         }
4155       }
4156       // close algorithms root HDF group
4157       aTopGroup->CloseOnDisk();
4158     }
4159     // --> mesh objects roots branches
4160     else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4161       CORBA::Object_var anObject = SObjectToObject( gotBranch );
4162       if ( !CORBA::is_nil( anObject ) ) {
4163         SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4164         if ( !myMesh->_is_nil() ) {
4165           SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4166           if ( myImpl ) {
4167             CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4168             int id = myStudyContext->findId( string( objStr.in() ) );
4169             ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4170             SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4171             bool hasShape = myLocMesh.HasShapeToMesh();
4172
4173             // for each mesh open the HDF group basing on its id
4174             char meshGrpName[ 30 ];
4175             sprintf( meshGrpName, "Mesh %d", id );
4176             aTopGroup = new HDFgroup( meshGrpName, aFile );
4177             aTopGroup->CreateOnDisk();
4178
4179             // --> put dataset to hdf file which is a flag that mesh has data
4180             string strHasData = "0";
4181             // check if the mesh is not empty
4182             if ( mySMESHDSMesh->NbNodes() > 0 ) {
4183               // write mesh data to med file
4184               myWriter.SetMesh( mySMESHDSMesh );
4185               myWriter.SetMeshId( id );
4186               strHasData = "1";
4187             }
4188             aSize[ 0 ] = strHasData.length() + 1;
4189             aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4190             aDataset->CreateOnDisk();
4191             aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4192             aDataset->CloseOnDisk();
4193
4194             // ouv : NPAL12872
4195             // for each mesh open the HDF group basing on its auto color parameter
4196             char meshAutoColorName[ 30 ];
4197             sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4198             int anAutoColor[1];
4199             anAutoColor[0] = myImpl->GetAutoColor();
4200             aSize[ 0 ] = 1;
4201             aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4202             aDataset->CreateOnDisk();
4203             aDataset->WriteOnDisk( anAutoColor );
4204             aDataset->CloseOnDisk();
4205
4206             // issue 0020693. Store _isModified flag
4207             int isModified = myLocMesh.GetIsModified();
4208             aSize[ 0 ] = 1;
4209             aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4210             aDataset->CreateOnDisk();
4211             aDataset->WriteOnDisk( &isModified );
4212             aDataset->CloseOnDisk();
4213
4214             // issue 20918. Store Persistent Id of SMESHDS_Mesh
4215             int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4216             aSize[ 0 ] = 1;
4217             aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4218             aDataset->CreateOnDisk();
4219             aDataset->WriteOnDisk( &meshPersistentId );
4220             aDataset->CloseOnDisk();
4221
4222             // write reference on a shape if exists
4223             SALOMEDS::SObject_wrap myRef;
4224             bool shapeRefFound = false;
4225             bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4226             if ( found ) {
4227               SALOMEDS::SObject_wrap myShape;
4228               bool ok = myRef->ReferencedObject( myShape.inout() );
4229               if ( ok ) {
4230                 CORBA::Object_var shapeObj = myShape->GetObject();
4231                 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4232                 CORBA::String_var myRefOnObject = myShape->GetID();
4233                 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4234                   aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4235                   aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4236                   aDataset->CreateOnDisk();
4237                   aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4238                   aDataset->CloseOnDisk();
4239                 }
4240               }
4241             }
4242
4243             // Store file info
4244             std::string info = myImpl->FileInfoToString();
4245             if ( !info.empty() )
4246             {
4247               aSize[ 0 ] = info.size();
4248               aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4249               aDataset->CreateOnDisk();
4250               aDataset->WriteOnDisk( (char*) info.data() );
4251               aDataset->CloseOnDisk();
4252             }
4253
4254             // write applied hypotheses if exist
4255             SALOMEDS::SObject_wrap myHypBranch;
4256             found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4257             if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4258               aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4259             }
4260             if ( found && (shapeRefFound || !hasShape) ) {
4261               aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4262               aGroup->CreateOnDisk();
4263
4264               SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4265               int hypNb = 0;
4266               for ( ; it->More(); it->Next() ) {
4267                 SALOMEDS::SObject_wrap mySObject = it->Value();
4268                 SALOMEDS::SObject_wrap myRefOnHyp;
4269                 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4270                 if ( ok ) {
4271                   // san - it is impossible to recover applied hypotheses
4272                   //       using their entries within Load() method,
4273                   // for there are no AttributeIORs in the study when Load() is working.
4274                   // Hence, it is better to store persistent IDs of hypotheses as references to them
4275
4276                   //string myRefOnObject = myRefOnHyp->GetID();
4277                   CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4278                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4279                   int id = myStudyContext->findId( string( objStr.in() ) );
4280                   //if ( myRefOnObject.length() > 0 ) {
4281                   //aSize[ 0 ] = myRefOnObject.length() + 1;
4282                   char hypName[ 30 ], hypId[ 30 ];
4283                   sprintf( hypName, "Hyp %d", ++hypNb );
4284                   sprintf( hypId, "%d", id );
4285                   aSize[ 0 ] = strlen( hypId ) + 1;
4286                   aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4287                   aDataset->CreateOnDisk();
4288                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4289                   aDataset->WriteOnDisk( hypId );
4290                   aDataset->CloseOnDisk();
4291                   //}
4292                 }
4293               }
4294               aGroup->CloseOnDisk();
4295             }
4296
4297             // write applied algorithms if exist
4298             SALOMEDS::SObject_wrap myAlgoBranch;
4299             found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4300                                               myAlgoBranch.inout() );
4301             if ( found && !shapeRefFound && hasShape) { // remove applied algos
4302               aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4303             }
4304             if ( found && (shapeRefFound || !hasShape)) {
4305               aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4306               aGroup->CreateOnDisk();
4307
4308               SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4309               int algoNb = 0;
4310               for ( ; it->More(); it->Next() ) {
4311                 SALOMEDS::SObject_wrap mySObject = it->Value();
4312                 SALOMEDS::SObject_wrap myRefOnAlgo;
4313                 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4314                 if ( ok ) {
4315                   // san - it is impossible to recover applied algorithms
4316                   //       using their entries within Load() method,
4317                   // for there are no AttributeIORs in the study when Load() is working.
4318                   // Hence, it is better to store persistent IDs of algorithms as references to them
4319
4320                   //string myRefOnObject = myRefOnAlgo->GetID();
4321                   CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4322                   CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4323                   int id = myStudyContext->findId( string( objStr.in() ) );
4324                   //if ( myRefOnObject.length() > 0 ) {
4325                   //aSize[ 0 ] = myRefOnObject.length() + 1;
4326                   char algoName[ 30 ], algoId[ 30 ];
4327                   sprintf( algoName, "Algo %d", ++algoNb );
4328                   sprintf( algoId, "%d", id );
4329                   aSize[ 0 ] = strlen( algoId ) + 1;
4330                   aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4331                   aDataset->CreateOnDisk();
4332                   //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4333                   aDataset->WriteOnDisk( algoId );
4334                   aDataset->CloseOnDisk();
4335                   //}
4336                 }
4337               }
4338               aGroup->CloseOnDisk();
4339             }
4340
4341             // --> submesh objects sub-branches
4342
4343             for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4344               SALOMEDS::SObject_wrap mySubmeshBranch;
4345               found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4346
4347               if ( found ) // check if there is shape reference in submeshes
4348               {
4349                 bool hasShapeRef = false;
4350                 SALOMEDS::ChildIterator_wrap itSM =
4351                   aStudy->NewChildIterator( mySubmeshBranch );
4352                 for ( ; itSM->More(); itSM->Next() ) {
4353                   SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4354                   if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4355                     mySubRef->ReferencedObject( myShape.inout() );
4356                   if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4357                     hasShapeRef = true;
4358                   else
4359                   { // remove one submesh
4360                     if ( shapeRefFound )
4361                     { // unassign hypothesis
4362                       SMESH::SMESH_subMesh_var mySubMesh =
4363                         SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4364                       if ( !mySubMesh->_is_nil() ) {
4365                         int shapeID = mySubMesh->GetId();
4366                         TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4367                         const list<const SMESHDS_Hypothesis*>& hypList =
4368                           mySMESHDSMesh->GetHypothesis( S );
4369                         list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4370                         while ( hyp != hypList.end() ) {
4371                           int hypID = (*hyp++)->GetID(); // goto next hyp here because
4372                           myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4373                         }
4374                       }
4375                     }
4376                     aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4377                   }
4378                 } // loop on submeshes of a type
4379                 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4380                   aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4381                   found = false;
4382                 }
4383               }  // end check if there is shape reference in submeshes
4384               if ( found ) {
4385                 char name_meshgroup[ 30 ];
4386                 if ( i == GetSubMeshOnVertexTag() )
4387                   strcpy( name_meshgroup, "SubMeshes On Vertex" );
4388                 else if ( i == GetSubMeshOnEdgeTag() )
4389                   strcpy( name_meshgroup, "SubMeshes On Edge" );
4390                 else if ( i == GetSubMeshOnWireTag() )
4391                   strcpy( name_meshgroup, "SubMeshes On Wire" );
4392                 else if ( i == GetSubMeshOnFaceTag() )
4393                   strcpy( name_meshgroup, "SubMeshes On Face" );
4394                 else if ( i == GetSubMeshOnShellTag() )
4395                   strcpy( name_meshgroup, "SubMeshes On Shell" );
4396                 else if ( i == GetSubMeshOnSolidTag() )
4397                   strcpy( name_meshgroup, "SubMeshes On Solid" );
4398                 else if ( i == GetSubMeshOnCompoundTag() )
4399                   strcpy( name_meshgroup, "SubMeshes On Compound" );
4400
4401                 // for each type of submeshes create container HDF group
4402                 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4403                 aGroup->CreateOnDisk();
4404
4405                 // iterator for all submeshes of given type
4406                 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4407                 for ( ; itSM->More(); itSM->Next() ) {
4408                   SALOMEDS::SObject_wrap mySObject = itSM->Value();
4409                   CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4410                   if ( !CORBA::is_nil( anSubObject ))
4411                   {
4412                     SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4413                     CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4414                     int subid = myStudyContext->findId( string( objStr.in() ) );
4415
4416                     // for each mesh open the HDF group basing on its id
4417                     char submeshGrpName[ 30 ];
4418                     sprintf( submeshGrpName, "SubMesh %d", subid );
4419                     aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4420                     aSubGroup->CreateOnDisk();
4421
4422                     // write reference on a shape, already checked if it exists
4423                     SALOMEDS::SObject_wrap mySubRef, myShape;
4424                     if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4425                       mySubRef->ReferencedObject( myShape.inout() );
4426                     string myRefOnObject = myShape->GetID();
4427                     if ( myRefOnObject.length() > 0 ) {
4428                       aSize[ 0 ] = myRefOnObject.length() + 1;
4429                       aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4430                       aDataset->CreateOnDisk();
4431                       aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4432                       aDataset->CloseOnDisk();
4433                     }
4434
4435                     // write applied hypotheses if exist
4436                     SALOMEDS::SObject_wrap mySubHypBranch;
4437                     found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4438                                                       mySubHypBranch.inout() );
4439                     if ( found ) {
4440                       aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4441                       aSubSubGroup->CreateOnDisk();
4442
4443                       SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4444                       int hypNb = 0;
4445                       for ( ; it->More(); it->Next() ) {
4446                         SALOMEDS::SObject_wrap mySubSObject = it->Value();
4447                         SALOMEDS::SObject_wrap myRefOnHyp;
4448                         bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4449                         if ( ok ) {
4450                           //string myRefOnObject = myRefOnHyp->GetID();
4451                           CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4452                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4453                           int id = myStudyContext->findId( string( objStr.in() ) );
4454                           //if ( myRefOnObject.length() > 0 ) {
4455                           //aSize[ 0 ] = myRefOnObject.length() + 1;
4456                           char hypName[ 30 ], hypId[ 30 ];
4457                           sprintf( hypName, "Hyp %d", ++hypNb );
4458                           sprintf( hypId, "%d", id );
4459                           aSize[ 0 ] = strlen( hypId ) + 1;
4460                           aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4461                           aDataset->CreateOnDisk();
4462                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4463                           aDataset->WriteOnDisk( hypId );
4464                           aDataset->CloseOnDisk();
4465                           //}
4466                         }
4467                       }
4468                       aSubSubGroup->CloseOnDisk();
4469                     }
4470
4471                     // write applied algorithms if exist
4472                     SALOMEDS::SObject_wrap mySubAlgoBranch;
4473                     found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4474                                                       mySubAlgoBranch.inout() );
4475                     if ( found ) {
4476                       aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4477                       aSubSubGroup->CreateOnDisk();
4478
4479                       SALOMEDS::ChildIterator_wrap it =
4480                         aStudy->NewChildIterator( mySubAlgoBranch );
4481                       int algoNb = 0;
4482                       for ( ; it->More(); it->Next() ) {
4483                         SALOMEDS::SObject_wrap mySubSObject = it->Value();
4484                         SALOMEDS::SObject_wrap myRefOnAlgo;
4485                         bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4486                         if ( ok ) {
4487                           //string myRefOnObject = myRefOnAlgo->GetID();
4488                           CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4489                           CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4490                           int id = myStudyContext->findId( string( objStr.in() ) );
4491                           //if ( myRefOnObject.length() > 0 ) {
4492                           //aSize[ 0 ] = myRefOnObject.length() + 1;
4493                           char algoName[ 30 ], algoId[ 30 ];
4494                           sprintf( algoName, "Algo %d", ++algoNb );
4495                           sprintf( algoId, "%d", id );
4496                           aSize[ 0 ] = strlen( algoId ) + 1;
4497                           aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4498                           aDataset->CreateOnDisk();
4499                           //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4500                           aDataset->WriteOnDisk( algoId );
4501                           aDataset->CloseOnDisk();
4502                           //}
4503                         }
4504                       }
4505                       aSubSubGroup->CloseOnDisk();
4506                     }
4507                     // close submesh HDF group
4508                     aSubGroup->CloseOnDisk();
4509                   }
4510                 }
4511                 // close container of submeshes by type HDF group
4512                 aGroup->CloseOnDisk();
4513               }
4514             }
4515             // All sub-meshes will be stored in MED file
4516             // .. will NOT (PAL 12992)
4517             //if ( shapeRefFound )
4518             //myWriter.AddAllSubMeshes();
4519
4520             // store submesh order if any
4521             const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4522             if ( theOrderIds.size() ) {
4523               char order_list[ 30 ];
4524               strcpy( order_list, "Mesh Order" );
4525               // count number of submesh ids
4526               int nbIDs = 0;
4527               TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4528               for ( ; idIt != theOrderIds.end(); idIt++ )
4529                 nbIDs += (*idIt).size();
4530               // number of values = number of IDs +
4531               //                    number of lists (for separators) - 1
4532               int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4533               idIt = theOrderIds.begin();
4534               for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4535                 const TListOfInt& idList = *idIt;
4536                 if (idIt != theOrderIds.begin()) // not first list
4537                   smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4538                 // dump submesh ids from current list
4539                 TListOfInt::const_iterator id_smId = idList.begin();
4540                 for( ; id_smId != idList.end(); id_smId++ )
4541                   smIDs[ i++ ] = *id_smId;
4542               }
4543               // write HDF group
4544               aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4545
4546               aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4547               aDataset->CreateOnDisk();
4548               aDataset->WriteOnDisk( smIDs );
4549               aDataset->CloseOnDisk();
4550               //
4551               delete[] smIDs;
4552             }
4553
4554             // groups root sub-branch
4555             SALOMEDS::SObject_wrap myGroupsBranch;
4556             for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4557               found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4558               if ( found ) {
4559                 char name_group[ 30 ];
4560                 if ( i == GetNodeGroupsTag() )
4561                   strcpy( name_group, "Groups of Nodes" );
4562                 else if ( i == GetEdgeGroupsTag() )
4563                   strcpy( name_group, "Groups of Edges" );
4564                 else if ( i == GetFaceGroupsTag() )
4565                   strcpy( name_group, "Groups of Faces" );
4566                 else if ( i == GetVolumeGroupsTag() )
4567                   strcpy( name_group, "Groups of Volumes" );
4568                 else if ( i == Get0DElementsGroupsTag() )
4569                   strcpy( name_group, "Groups of 0D Elements" );
4570                 else if ( i == GetBallElementsGroupsTag() )
4571                   strcpy( name_group, "Groups of Balls" );
4572
4573                 aGroup = new HDFgroup( name_group, aTopGroup );
4574                 aGroup->CreateOnDisk();
4575
4576                 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4577                 for ( ; it->More(); it->Next() ) {
4578                   SALOMEDS::SObject_wrap mySObject = it->Value();
4579                   CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4580                   if ( !CORBA::is_nil( aSubObject ) ) {
4581                     SMESH_GroupBase_i* myGroupImpl =
4582                       dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4583                     if ( !myGroupImpl )
4584                       continue;
4585                     SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4586                     if ( !aGrpBaseDS )
4587                       continue;
4588
4589                     CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4590                     int anId = myStudyContext->findId( string( objStr.in() ) );
4591
4592                     // For each group, create a dataset named "Group <group_persistent_id>"
4593                     // and store the group's user name into it
4594                     const char*         grpName = aGrpBaseDS->GetStoreName();
4595                     CORBA::String_var aUserName = myGroupImpl->GetName();
4596                     aSize[ 0 ] = strlen( aUserName ) + 1;
4597
4598                     aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4599                     aDataset->CreateOnDisk();
4600                     aDataset->WriteOnDisk( aUserName );
4601                     aDataset->CloseOnDisk();
4602
4603                     // ouv : NPAL12872
4604                     // For each group, create a dataset named "Group <group_persistent_id> Color"
4605                     // and store the group's color into it
4606                     char grpColorName[ 30 ];
4607                     sprintf( grpColorName, "ColorGroup %d", anId );
4608                     SALOMEDS::Color aColor = myGroupImpl->GetColor();
4609                     double anRGB[3];
4610                     anRGB[ 0 ] = aColor.R;
4611                     anRGB[ 1 ] = aColor.G;
4612                     anRGB[ 2 ] = aColor.B;
4613                     aSize[ 0 ] = 3;
4614                     aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4615                     aDataset->CreateOnDisk();
4616                     aDataset->WriteOnDisk( anRGB );
4617                     aDataset->CloseOnDisk();
4618
4619                     // Pass SMESHDS_Group to MED writer
4620                     SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4621                     if ( aGrpDS )
4622                       myWriter.AddGroup( aGrpDS );
4623
4624                     // write reference on a shape if exists
4625                     SMESHDS_GroupOnGeom* aGeomGrp =
4626                       dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4627                     if ( aGeomGrp ) {
4628                       SALOMEDS::SObject_wrap mySubRef, myShape;
4629                       if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4630                           mySubRef->ReferencedObject( myShape.inout() ) &&
4631                           !CORBA::is_nil( myShape->GetObject() ))
4632                       {
4633                         CORBA::String_var myRefOnObject = myShape->GetID();
4634                         if ( myRefOnObject.in()[0] ) {
4635                           char aRefName[ 30 ];
4636                           sprintf( aRefName, "Ref on shape %d", anId);
4637                           aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4638                           aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4639                           aDataset->CreateOnDisk();
4640                           aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4641                           aDataset->CloseOnDisk();
4642                         }
4643                       }
4644                       else // shape ref is invalid:
4645                       {
4646                         // save a group on geometry as ordinary group
4647                         myWriter.AddGroup( aGeomGrp );
4648                       }
4649                     }
4650                     else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4651                               dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4652                     {
4653                       std::string str = aFilterGrp_i->FilterToString();
4654                       std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4655                       aSize[ 0 ] = str.length() + 1;
4656                       aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4657                       aDataset->CreateOnDisk();
4658                       aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4659                       aDataset->CloseOnDisk();
4660                     }
4661                   }
4662                 }
4663                 aGroup->CloseOnDisk();
4664               }
4665             } // loop on groups
4666
4667             if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4668             {
4669               // Flush current mesh information into MED file
4670               myWriter.Perform();
4671
4672               // save info on nb of elements
4673               SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4674
4675               // maybe a shape was deleted in the study
4676               if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4677                 TopoDS_Shape nullShape;
4678                 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4679               }
4680
4681               SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4682               if ( smIt->more() )
4683               {
4684                 // Store submeshes
4685                 // ----------------
4686                 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4687                 aGroup->CreateOnDisk();
4688
4689                 // each element belongs to one or none submesh,
4690                 // so for each node/element, we store a submesh ID
4691
4692                 // Store submesh IDs
4693                 for ( int isNode = 0; isNode < 2; ++isNode )
4694                 {
4695                   SMDS_ElemIteratorPtr eIt =
4696                     mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4697                   int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4698                   if ( nbElems < 1 )
4699                     continue;
4700                   std::vector<int> smIDs; smIDs.reserve( nbElems );
4701                   while ( eIt->more() )
4702                     if ( const SMDS_MeshElement* e = eIt->next())
4703                       smIDs.push_back( e->getshapeId() );
4704                   // write HDF group
4705                   aSize[ 0 ] = nbElems;
4706                   string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4707                   aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4708                   aDataset->CreateOnDisk();
4709                   aDataset->WriteOnDisk( & smIDs[0] );
4710                   aDataset->CloseOnDisk();
4711                 }
4712
4713                 aGroup->CloseOnDisk();
4714
4715                 // Store node positions on sub-shapes (SMDS_Position):
4716                 // ----------------------------------------------------
4717
4718                 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4719                 aGroup->CreateOnDisk();
4720
4721                 // in aGroup, create 5 datasets to contain:
4722                 // "Nodes on Edges" - ID of node on edge
4723                 // "Edge positions" - U parameter on node on edge
4724                 // "Nodes on Faces" - ID of node on face
4725                 // "Face U positions" - U parameter of node on face
4726                 // "Face V positions" - V parameter of node on face
4727
4728                 // Find out nb of nodes on edges and faces
4729                 // Collect corresponding sub-meshes
4730                 int nbEdgeNodes = 0, nbFaceNodes = 0;
4731                 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4732                 // loop on SMESHDS_SubMesh'es
4733                 while ( smIt->more() )
4734                 {
4735                   SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4736                   if ( aSubMesh->IsComplexSubmesh() )
4737                     continue; // submesh containing other submeshs
4738                   int nbNodes = aSubMesh->NbNodes();
4739                   if ( nbNodes == 0 ) continue;
4740
4741                   int aShapeID = aSubMesh->GetID();
4742                   if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4743                     continue;
4744                   int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4745                   // write only SMDS_FacePosition and SMDS_EdgePosition
4746                   switch ( aShapeType ) {
4747                   case TopAbs_FACE:
4748                     nbFaceNodes += nbNodes;
4749                     aFaceSM.push_back( aSubMesh );
4750                     break;
4751                   case TopAbs_EDGE:
4752                     nbEdgeNodes += nbNodes;
4753                     aEdgeSM.push_back( aSubMesh );
4754                     break;
4755                   default:
4756                     continue;
4757                   }
4758                 }
4759                 // Treat positions on edges or faces
4760                 for ( int onFace = 0; onFace < 2; onFace++ )
4761                 {
4762                   // Create arrays to store in datasets
4763                   int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4764                   if (!nbNodes) continue;
4765                   int* aNodeIDs = new int [ nbNodes ];
4766                   double* aUPos = new double [ nbNodes ];
4767                   double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4768
4769                   // Fill arrays
4770                   // loop on sub-meshes
4771                   list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4772                   list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4773                   for ( ; itSM != pListSM->end(); itSM++ )
4774                   {
4775                     SMESHDS_SubMesh* aSubMesh = (*itSM);
4776
4777                     SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4778                     // loop on nodes in aSubMesh
4779                     while ( itNode->more() )
4780                     {
4781                       //node ID
4782                       const SMDS_MeshNode* node = itNode->next();
4783                       aNodeIDs [ iNode ] = node->GetID();
4784
4785                       // Position
4786                       const SMDS_PositionPtr pos = node->GetPosition();
4787                       if ( onFace ) { // on FACE
4788                         SMDS_FacePositionPtr fPos = pos;
4789                         if ( fPos ) {
4790                           aUPos[ iNode ] = fPos->GetUParameter();
4791                           aVPos[ iNode ] = fPos->GetVParameter();
4792                           iNode++;
4793                         }
4794                         else
4795                           nbNodes--;
4796                       }
4797                       else { // on EDGE
4798                         SMDS_EdgePositionPtr ePos = pos;
4799                         if ( ePos ) {
4800                           aUPos[ iNode ] = ePos->GetUParameter();
4801                           iNode++;
4802                         }
4803                         else
4804                           nbNodes--;
4805                       }
4806                     } // loop on nodes in aSubMesh
4807                   } // loop on sub-meshes
4808
4809                   // Write datasets
4810                   if ( nbNodes )
4811                   {
4812                     aSize[ 0 ] = nbNodes;
4813                     // IDS
4814                     string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
4815                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4816                     aDataset->CreateOnDisk();
4817                     aDataset->WriteOnDisk( aNodeIDs );
4818                     aDataset->CloseOnDisk();
4819
4820                     // U Positions
4821                     aDSName = ( onFace ? "Face U positions" : "Edge positions");
4822                     aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
4823                     aDataset->CreateOnDisk();
4824                     aDataset->WriteOnDisk( aUPos );
4825                     aDataset->CloseOnDisk();
4826                     // V Positions
4827                     if ( onFace ) {
4828                       aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
4829                       aDataset->CreateOnDisk();
4830                       aDataset->WriteOnDisk( aVPos );
4831                       aDataset->CloseOnDisk();
4832                     }
4833                   }
4834                   delete [] aNodeIDs;
4835                   delete [] aUPos;
4836                   if ( aVPos ) delete [] aVPos;
4837
4838                 } // treat positions on edges or faces
4839
4840                 // close "Node Positions" group
4841                 aGroup->CloseOnDisk();
4842
4843               } // if ( there are submeshes in SMESHDS_Mesh )
4844             } // if ( hasData )
4845
4846             // close mesh HDF group
4847             aTopGroup->CloseOnDisk();
4848           }
4849         }
4850       }
4851     }
4852   }
4853
4854   // close HDF file
4855   aFile->CloseOnDisk();
4856   delete aFile;
4857
4858   // Convert temporary files to stream
4859   aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
4860
4861   // Remove temporary files and directory
4862   if ( !isMultiFile )
4863     SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
4864
4865   return aStreamFile._retn();
4866 }
4867
4868 //=============================================================================
4869 /*!
4870  *  SMESH_Gen_i::SaveASCII
4871  *
4872  *  Save SMESH module's data in ASCII format
4873  */
4874 //=============================================================================
4875
4876 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
4877                                            const char*              theURL,
4878                                            bool                     isMultiFile ) {
4879   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
4880   SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
4881   return aStreamFile._retn();
4882
4883   //after usual saving needs to encipher binary to text string
4884   //Any binary symbol will be represent as "|xx" () hexadecimal format number
4885   int size = aStreamFile.in().length();
4886   _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
4887   for ( int i = 0; i < size; i++ )
4888     sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
4889
4890   buffer[size * 3] = '\0';
4891
4892   SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
4893
4894   return anAsciiStreamFile._retn();
4895 }
4896
4897 //=============================================================================
4898 /*!
4899  *  SMESH_Gen_i::loadGeomData
4900  *
4901  *  Load GEOM module data
4902  */
4903 //=============================================================================
4904
4905 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
4906 {
4907   if ( theCompRoot->_is_nil() )
4908     return;
4909
4910   SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
4911   aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
4912 }
4913
4914 //=============================================================================
4915 /*!
4916  *  SMESH_Gen_i::Load
4917  *
4918  *  Load SMESH module's data
4919  */
4920 //=============================================================================
4921
4922 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
4923                         const SALOMEDS::TMPFile& theStream,
4924                         const char*              theURL,
4925                         bool                     isMultiFile )
4926 {
4927   //if (!myStudyContext)
4928     UpdateStudy();
4929   SALOMEDS::Study_var aStudy = getStudyServant();
4930   /*  if( !theComponent->_is_nil() )
4931       {
4932       if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
4933       loadGeomData( aStudy->FindComponent( "GEOM" ) );
4934       }*/
4935
4936   // Get temporary files location
4937   TCollection_AsciiString tmpDir =
4938     ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
4939
4940   // Convert the stream into sequence of files to process
4941   SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
4942                                                                          tmpDir.ToCString(),
4943                                                                          isMultiFile );
4944   TCollection_AsciiString aStudyName( "" );
4945   if ( isMultiFile ) {
4946     CORBA::WString_var url = aStudy->URL();
4947     aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
4948   }
4949   // Set names of temporary files
4950   TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4951   TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4952
4953   int size;
4954   HDFfile*    aFile;
4955   HDFdataset* aDataset;
4956   HDFgroup*   aTopGroup;
4957   HDFgroup*   aGroup;
4958   HDFgroup*   aSubGroup;
4959   HDFgroup*   aSubSubGroup;
4960
4961   // Read data
4962   // ---> open HDF file
4963   aFile = new HDFfile( (char*) filename.ToCString() );
4964   try {
4965     aFile->OpenOnDisk( HDF_RDONLY );
4966   }
4967   catch ( HDFexception ) {
4968     INFOS( "Load(): " << filename << " not found!" );
4969     return false;
4970   }
4971
4972   TPythonDump pd; // prevent dump during loading
4973
4974   // DriverMED_R_SMESHDS_Mesh myReader;
4975   // myReader.SetFile( meshfile.ToCString() );
4976
4977   // For PAL13473 ("Repetitive mesh") implementation.
4978   // New dependencies between SMESH objects are established:
4979   // now hypotheses can refer to meshes, shapes and other hypotheses.
4980   // To keep data consistent, the following order of data restoration
4981   // imposed:
4982   // 1. Create hypotheses
4983   // 2. Create all meshes
4984   // 3. Load hypotheses' data
4985   // 4. All the rest
4986
4987   list< pair< SMESH_Hypothesis_i*, string > >    hypDataList;
4988   list< pair< SMESH_Mesh_i*,       HDFgroup* > > meshGroupList;
4989   list< SMESH::Filter_var >                      filters;
4990
4991   // get total number of top-level groups
4992   int aNbGroups = aFile->nInternalObjects();
4993   if ( aNbGroups > 0 ) {
4994     // --> in first turn we should read&create hypotheses
4995     if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4996       // open hypotheses root HDF group
4997       aTopGroup = new HDFgroup( "Hypotheses", aFile );
4998       aTopGroup->OpenOnDisk();
4999
5000       // get number of hypotheses
5001       int aNbObjects = aTopGroup->nInternalObjects();
5002       for ( int j = 0; j < aNbObjects; j++ ) {
5003         // try to identify hypothesis
5004         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5005         aTopGroup->InternalObjectIndentify( j, hypGrpName );
5006
5007         if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5008           // open hypothesis group
5009           aGroup = new HDFgroup( hypGrpName, aTopGroup );
5010           aGroup->OpenOnDisk();
5011
5012           // --> get hypothesis id
5013           int    id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5014           string hypname;
5015           string libname;
5016           string hypdata;
5017
5018           // get number of datasets
5019           int aNbSubObjects = aGroup->nInternalObjects();
5020           for ( int k = 0; k < aNbSubObjects; k++ ) {
5021             // identify dataset
5022             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5023             aGroup->InternalObjectIndentify( k, name_of_subgroup );
5024             // --> get hypothesis name
5025             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
5026               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5027               aDataset->OpenOnDisk();
5028               size = aDataset->GetSize();
5029               char* hypname_str = new char[ size ];
5030               aDataset->ReadFromDisk( hypname_str );
5031               hypname = string( hypname_str );
5032               delete [] hypname_str;
5033               aDataset->CloseOnDisk();
5034             }
5035             // --> get hypothesis plugin library name
5036             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
5037               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5038               aDataset->OpenOnDisk();
5039               size = aDataset->GetSize();
5040               char* libname_str = new char[ size ];
5041               aDataset->ReadFromDisk( libname_str );
5042               if(MYDEBUG) SCRUTE( libname_str );
5043               libname = string( libname_str );
5044               delete [] libname_str;
5045               aDataset->CloseOnDisk();
5046             }
5047             // --> get hypothesis data
5048             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
5049               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5050               aDataset->OpenOnDisk();
5051               size = aDataset->GetSize();
5052               char* hypdata_str = new char[ size ];
5053               aDataset->ReadFromDisk( hypdata_str );
5054               hypdata = string( hypdata_str );
5055               delete [] hypdata_str;
5056               aDataset->CloseOnDisk();
5057             }
5058           }
5059           // close hypothesis HDF group
5060           aGroup->CloseOnDisk();
5061
5062           // --> restore hypothesis from data
5063           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5064             if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5065                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5066             SMESH::SMESH_Hypothesis_var myHyp;
5067
5068             try { // protect persistence mechanism against exceptions
5069               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5070             }
5071             catch (...) {
5072               INFOS( "Exception during hypothesis creation" );
5073             }
5074
5075             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5076             if ( myImpl ) {
5077               // myImpl->LoadFrom( hypdata.c_str() );
5078               hypDataList.push_back( make_pair( myImpl, hypdata ));
5079               CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5080               int newId = myStudyContext->findId( iorString.in() );
5081               myStudyContext->mapOldToNew( id, newId );
5082             }
5083             else
5084               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5085           }
5086         }
5087       }
5088       // close hypotheses root HDF group
5089       aTopGroup->CloseOnDisk();
5090       aTopGroup = 0;
5091     }
5092
5093     // --> then we should read&create algorithms
5094     if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5095       // open algorithms root HDF group
5096       aTopGroup = new HDFgroup( "Algorithms", aFile );
5097       aTopGroup->OpenOnDisk();
5098
5099       // get number of algorithms
5100       int aNbObjects = aTopGroup->nInternalObjects();
5101       for ( int j = 0; j < aNbObjects; j++ ) {
5102         // try to identify algorithm
5103         char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5104         aTopGroup->InternalObjectIndentify( j, hypGrpName );
5105
5106         if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5107           // open algorithm group
5108           aGroup = new HDFgroup( hypGrpName, aTopGroup );
5109           aGroup->OpenOnDisk();
5110
5111           // --> get algorithm id
5112           int    id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5113           string hypname;
5114           string libname;
5115           string hypdata;
5116
5117           // get number of datasets
5118           int aNbSubObjects = aGroup->nInternalObjects();
5119           for ( int k = 0; k < aNbSubObjects; k++ ) {
5120             // identify dataset
5121             char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5122             aGroup->InternalObjectIndentify( k, name_of_subgroup );
5123             // --> get algorithm name
5124             if ( strcmp( name_of_subgroup, "Name"  ) == 0 ) {
5125               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5126               aDataset->OpenOnDisk();
5127               size = aDataset->GetSize();
5128               char* hypname_str = new char[ size ];
5129               aDataset->ReadFromDisk( hypname_str );
5130               hypname = string( hypname_str );
5131               delete [] hypname_str;
5132               aDataset->CloseOnDisk();
5133             }
5134             // --> get algorithm plugin library name
5135             if ( strcmp( name_of_subgroup, "LibName"  ) == 0 ) {
5136               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5137               aDataset->OpenOnDisk();
5138               size = aDataset->GetSize();
5139               char* libname_str = new char[ size ];
5140               aDataset->ReadFromDisk( libname_str );
5141               if(MYDEBUG) SCRUTE( libname_str );
5142               libname = string( libname_str );
5143               delete [] libname_str;
5144               aDataset->CloseOnDisk();
5145             }
5146             // --> get algorithm data
5147             if ( strcmp( name_of_subgroup, "Data"  ) == 0 ) {
5148               aDataset = new HDFdataset( name_of_subgroup, aGroup );
5149               aDataset->OpenOnDisk();
5150               size = aDataset->GetSize();
5151               char* hypdata_str = new char[ size ];
5152               aDataset->ReadFromDisk( hypdata_str );
5153               if(MYDEBUG) SCRUTE( hypdata_str );
5154               hypdata = string( hypdata_str );
5155               delete [] hypdata_str;
5156               aDataset->CloseOnDisk();
5157             }
5158           }
5159           // close algorithm HDF group
5160           aGroup->CloseOnDisk();
5161
5162           // --> restore algorithm from data
5163           if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5164             if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5165                                 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5166             SMESH::SMESH_Hypothesis_var myHyp;
5167
5168             try { // protect persistence mechanism against exceptions
5169               myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5170             }
5171             catch (...) {
5172               INFOS( "Exception during hypothesis creation" );
5173             }
5174
5175             SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5176             if ( myImpl ) {
5177               //myImpl->LoadFrom( hypdata.c_str() );
5178               hypDataList.push_back( make_pair( myImpl, hypdata ));
5179               CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5180               int newId = myStudyContext->findId( iorString.in() );
5181               myStudyContext->mapOldToNew( id, newId );
5182             }
5183             else
5184               if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5185           }
5186         }
5187       }
5188       // close algorithms root HDF group
5189       aTopGroup->CloseOnDisk();
5190       aTopGroup = 0;
5191     }
5192
5193     // --> the rest groups should be meshes
5194     for ( int i = 0; i < aNbGroups; i++ ) {
5195       // identify next group
5196       char meshName[ HDF_NAME_MAX_LEN+1 ];
5197       aFile->InternalObjectIndentify( i, meshName );
5198
5199       if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5200         // --> get mesh id
5201         int id = atoi( string( meshName ).substr( 4 ).c_str() );
5202         if ( id <= 0 )
5203           continue;
5204
5205         // open mesh HDF group
5206         aTopGroup = new HDFgroup( meshName, aFile );
5207         aTopGroup->OpenOnDisk();
5208
5209         // get number of child HDF objects
5210         int aNbObjects = aTopGroup->nInternalObjects();
5211         if ( aNbObjects > 0 ) {
5212           // create mesh
5213           if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5214           SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5215           SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5216           if ( !myNewMeshImpl )
5217             continue;
5218           meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5219
5220           CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5221           int newId = myStudyContext->findId( iorString.in() );
5222           myStudyContext->mapOldToNew( id, newId );
5223
5224           // ouv : NPAL12872
5225           // try to read and set auto color flag
5226           char aMeshAutoColorName[ 30 ];
5227           sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5228           if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5229           {
5230             aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5231             aDataset->OpenOnDisk();
5232             size = aDataset->GetSize();
5233             int* anAutoColor = new int[ size ];
5234             aDataset->ReadFromDisk( anAutoColor );
5235             aDataset->CloseOnDisk();
5236             myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5237             delete [] anAutoColor;
5238           }
5239
5240           // try to read and set reference to shape
5241           GEOM::GEOM_Object_var aShapeObject;
5242           if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5243             // load mesh "Ref on shape" - it's an entry to SObject
5244             aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5245             aDataset->OpenOnDisk();
5246             size = aDataset->GetSize();
5247             char* refFromFile = new char[ size ];
5248             aDataset->ReadFromDisk( refFromFile );
5249             aDataset->CloseOnDisk();
5250             if ( strlen( refFromFile ) > 0 ) {
5251               SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5252
5253               // Make sure GEOM data are loaded first
5254               //loadGeomData( shapeSO->GetFatherComponent() );
5255
5256               CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5257               if ( !CORBA::is_nil( shapeObject ) ) {
5258                 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5259                 if ( !aShapeObject->_is_nil() )
5260                   myNewMeshImpl->SetShape( aShapeObject );
5261               }
5262             }
5263             delete [] refFromFile;
5264           }
5265
5266           // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5267           if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5268           {
5269             aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5270             aDataset->OpenOnDisk();
5271             size = aDataset->GetSize();
5272             int* meshPersistentId = new int[ size ];
5273             aDataset->ReadFromDisk( meshPersistentId );
5274             aDataset->CloseOnDisk();
5275             myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5276             delete [] meshPersistentId;
5277           }
5278
5279           // Restore file info
5280           if ( aTopGroup->ExistInternalObject( "file info" ))
5281           {
5282             aDataset = new HDFdataset( "file info", aTopGroup );
5283             aDataset->OpenOnDisk();
5284             size = aDataset->GetSize();
5285             std::string info( size, ' ');
5286             aDataset->ReadFromDisk( (char*) info.data() );
5287             aDataset->CloseOnDisk();
5288             myNewMeshImpl->FileInfoFromString( info );
5289           }
5290         }
5291       }
5292     } // reading MESHes
5293
5294     // As all object that can be referred by hypothesis are created,
5295     // we can restore hypothesis data
5296
5297     list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5298     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5299     {
5300       SMESH_Hypothesis_i* hyp  = hyp_data->first;
5301       string &            data = hyp_data->second;
5302       hyp->LoadFrom( data.c_str() );
5303     }
5304
5305     // Restore the rest mesh data
5306
5307     list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5308     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5309     {
5310       aTopGroup                   = meshi_group->second;
5311       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5312       //::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
5313       //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5314
5315       GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5316       bool hasData = false;
5317
5318       // get mesh old id
5319       CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5320       int newId = myStudyContext->findId( iorString.in() );
5321       int id = myStudyContext->getOldId( newId );
5322
5323       // try to find mesh data dataset
5324       if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5325         // load mesh "has data" flag
5326         aDataset = new HDFdataset( "Has data", aTopGroup );
5327         aDataset->OpenOnDisk();
5328         size = aDataset->GetSize();
5329         char* strHasData = new char[ size ];
5330         aDataset->ReadFromDisk( strHasData );
5331         aDataset->CloseOnDisk();
5332         if ( strcmp( strHasData, "1") == 0 ) {
5333           // read mesh data from MED file
5334           // myReader.SetMesh( mySMESHDSMesh );
5335           // myReader.SetMeshId( id );
5336           // myReader.Perform();
5337           hasData = true;
5338         }
5339         delete [] strHasData;
5340       }
5341
5342       // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5343       // nodes and elements are not yet put into sub-meshes)
5344       if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5345         aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5346         aGroup->OpenOnDisk();
5347         // get number of applied algorithms
5348         int aNbSubObjects = aGroup->nInternalObjects();
5349         if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5350         for ( int j = 0; j < aNbSubObjects; j++ ) {
5351           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5352           aGroup->InternalObjectIndentify( j, name_dataset );
5353           // check if it is an algorithm
5354           if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5355             aDataset = new HDFdataset( name_dataset, aGroup );
5356             aDataset->OpenOnDisk();
5357             size = aDataset->GetSize();
5358             char* refFromFile = new char[ size ];
5359             aDataset->ReadFromDisk( refFromFile );
5360             aDataset->CloseOnDisk();
5361             // san - it is impossible to recover applied algorithms using their entries within Load() method
5362             //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5363             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5364             int id = atoi( refFromFile );
5365             delete [] refFromFile;
5366             string anIOR = myStudyContext->getIORbyOldId( id );
5367             if ( !anIOR.empty() ) {
5368               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5369               if ( !CORBA::is_nil( hypObject ) ) {
5370                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5371                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5372                                            || !myNewMeshImpl->HasShapeToMesh()) )
5373                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5374               }
5375             }
5376           }
5377         }
5378         aGroup->CloseOnDisk();
5379       }
5380
5381       // try to get applied hypotheses
5382       if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5383         aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5384         aGroup->OpenOnDisk();
5385         // get number of applied hypotheses
5386         int aNbSubObjects = aGroup->nInternalObjects();
5387         for ( int j = 0; j < aNbSubObjects; j++ ) {
5388           char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5389           aGroup->InternalObjectIndentify( j, name_dataset );
5390           // check if it is a hypothesis
5391           if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5392             aDataset = new HDFdataset( name_dataset, aGroup );
5393             aDataset->OpenOnDisk();
5394             size = aDataset->GetSize();
5395             char* refFromFile = new char[ size ];
5396             aDataset->ReadFromDisk( refFromFile );
5397             aDataset->CloseOnDisk();
5398             // san - it is impossible to recover applied hypotheses using their entries within Load() method
5399             //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5400             //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5401             int id = atoi( refFromFile );
5402             delete [] refFromFile;
5403             string anIOR = myStudyContext->getIORbyOldId( id );
5404             if ( !anIOR.empty() ) {
5405               CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5406               if ( !CORBA::is_nil( hypObject ) ) {
5407                 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5408                 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5409                                            || !myNewMeshImpl->HasShapeToMesh()) )
5410                   myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5411               }
5412             }
5413           }
5414         }
5415         aGroup->CloseOnDisk();
5416       }
5417
5418       // --> try to find SUB-MESHES containers for each type of submesh
5419       for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5420         const char* name_meshgroup = 0;
5421         if ( j == GetSubMeshOnVertexTag() )
5422           name_meshgroup = "SubMeshes On Vertex";
5423         else if ( j == GetSubMeshOnEdgeTag() )
5424           name_meshgroup = "SubMeshes On Edge";
5425         else if ( j == GetSubMeshOnWireTag() )
5426           name_meshgroup = "SubMeshes On Wire";
5427         else if ( j == GetSubMeshOnFaceTag() )
5428           name_meshgroup = "SubMeshes On Face";
5429         else if ( j == GetSubMeshOnShellTag() )
5430           name_meshgroup = "SubMeshes On Shell";
5431         else if ( j == GetSubMeshOnSolidTag() )
5432           name_meshgroup = "SubMeshes On Solid";
5433         else if ( j == GetSubMeshOnCompoundTag() )
5434           name_meshgroup = "SubMeshes On Compound";
5435
5436         // try to get submeshes container HDF group
5437         if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5438           // open submeshes containers HDF group
5439           aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5440           aGroup->OpenOnDisk();
5441
5442           // get number of submeshes
5443           int aNbSubMeshes = aGroup->nInternalObjects();
5444           for ( int k = 0; k < aNbSubMeshes; k++ ) {
5445             // identify submesh
5446             char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5447             aGroup->InternalObjectIndentify( k, name_submeshgroup );
5448             if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5449               // --> get submesh id
5450               int subid = atoi( name_submeshgroup + 7 );
5451               if ( subid <= 0 )
5452                 continue;
5453               // open submesh HDF group
5454               aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5455               aSubGroup->OpenOnDisk();
5456
5457               // try to read and set reference to subshape
5458               GEOM::GEOM_Object_var aSubShapeObject;
5459               SMESH::SMESH_subMesh_var aSubMesh;
5460
5461               if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5462                 // load submesh "Ref on shape" - it's an entry to SObject
5463                 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5464                 aDataset->OpenOnDisk();
5465                 size = aDataset->GetSize();
5466                 char* refFromFile = new char[ size ];
5467                 aDataset->ReadFromDisk( refFromFile );
5468                 aDataset->CloseOnDisk();
5469                 if ( strlen( refFromFile ) > 0 ) {
5470                   SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5471                   CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5472                   if ( !CORBA::is_nil( subShapeObject ) ) {
5473                     aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5474                     if ( !aSubShapeObject->_is_nil() )
5475                       aSubMesh = SMESH::SMESH_subMesh::_duplicate
5476                         ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5477                     if ( aSubMesh->_is_nil() )
5478                       continue;
5479                     string iorSubString = GetORB()->object_to_string( aSubMesh );
5480                     int newSubId = myStudyContext->findId( iorSubString );
5481                     myStudyContext->mapOldToNew( subid, newSubId );
5482                   }
5483                 }
5484                 delete [] refFromFile;
5485               }
5486
5487               if ( aSubMesh->_is_nil() )
5488                 continue;
5489
5490               // try to get applied algorithms
5491               if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5492                 // open "applied algorithms" HDF group
5493                 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5494                 aSubSubGroup->OpenOnDisk();
5495                 // get number of applied algorithms
5496                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5497                 for ( int l = 0; l < aNbSubObjects; l++ ) {
5498                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5499                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5500                   // check if it is an algorithm
5501                   if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5502                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5503                     aDataset->OpenOnDisk();
5504                     size = aDataset->GetSize();
5505                     char* refFromFile = new char[ size ];
5506                     aDataset->ReadFromDisk( refFromFile );
5507                     aDataset->CloseOnDisk();
5508
5509                     int id = atoi( refFromFile );
5510                     string anIOR = myStudyContext->getIORbyOldId( id );
5511                     if ( !anIOR.empty() ) {
5512                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5513                       if ( !CORBA::is_nil( hypObject ) ) {
5514                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5515                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5516                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5517                       }
5518                     }
5519                     delete [] refFromFile;
5520                   }
5521                 }
5522                 // close "applied algorithms" HDF group
5523                 aSubSubGroup->CloseOnDisk();
5524               }
5525
5526               // try to get applied hypotheses
5527               if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5528                 // open "applied hypotheses" HDF group
5529                 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5530                 aSubSubGroup->OpenOnDisk();
5531                 // get number of applied hypotheses
5532                 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5533                 for ( int l = 0; l < aNbSubObjects; l++ ) {
5534                   char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5535                   aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5536                   // check if it is a hypothesis
5537                   if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5538                     aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5539                     aDataset->OpenOnDisk();
5540                     size = aDataset->GetSize();
5541                     char* refFromFile = new char[ size ];
5542                     aDataset->ReadFromDisk( refFromFile );
5543                     aDataset->CloseOnDisk();
5544
5545                     int id = atoi( refFromFile );
5546                     string anIOR = myStudyContext->getIORbyOldId( id );
5547                     if ( !anIOR.empty() ) {
5548                       CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5549                       if ( !CORBA::is_nil( hypObject ) ) {
5550                         SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5551                         if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5552                           myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5553                       }
5554                     }
5555                     delete [] refFromFile;
5556                   }
5557                 }
5558                 // close "APPLIED HYPOTHESES" hdf group
5559                 aSubSubGroup->CloseOnDisk();
5560               }
5561
5562               // close SUB-MESH hdf group
5563               aSubGroup->CloseOnDisk();
5564             }
5565           }
5566           // close SUB-MESHES containers hdf group
5567           aGroup->CloseOnDisk();
5568         }
5569       }
5570
5571       // try to get GROUPS
5572       for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5573         char name_group[ 30 ];
5574         if ( ii == GetNodeGroupsTag() )
5575           strcpy( name_group, "Groups of Nodes" );
5576         else if ( ii == GetEdgeGroupsTag() )
5577           strcpy( name_group, "Groups of Edges" );
5578         else if ( ii == GetFaceGroupsTag() )
5579           strcpy( name_group, "Groups of Faces" );
5580         else if ( ii == GetVolumeGroupsTag() )
5581           strcpy( name_group, "Groups of Volumes" );
5582         else if ( ii == Get0DElementsGroupsTag() )
5583           strcpy( name_group, "Groups of 0D Elements" );
5584         else if ( ii == GetBallElementsGroupsTag() )
5585           strcpy( name_group, "Groups of Balls" );
5586
5587         if ( aTopGroup->ExistInternalObject( name_group ) ) {
5588           aGroup = new HDFgroup( name_group, aTopGroup );
5589           aGroup->OpenOnDisk();
5590           // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5591           // within aGroup->ExistInternalObject( name )
5592           std::vector< std::string > subNames;
5593           TColStd_MapOfAsciiString mapOfNames;
5594           aGroup->GetAllObjects( subNames );
5595           for ( size_t iN = 0; iN < subNames.size(); ++iN )
5596             mapOfNames.Add( subNames[ iN ].c_str() );
5597           // loop on groups
5598           for ( size_t j = 0; j < subNames.size(); j++ ) {
5599             const std::string& name_dataset = subNames[ j ];
5600             // check if it is a group
5601             if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5602               // --> get group id
5603               int subid = atoi( name_dataset.substr( 5 ).c_str() );
5604               if ( subid <= 0 )
5605                 continue;
5606               aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5607               aDataset->OpenOnDisk();
5608
5609               // Retrieve actual group name
5610               size = aDataset->GetSize();
5611               char* nameFromFile = new char[ size ];
5612               aDataset->ReadFromDisk( nameFromFile );
5613               aDataset->CloseOnDisk();
5614
5615               // Try to find a shape reference
5616               TopoDS_Shape aShape;
5617               char aRefName[ 30 ];
5618               sprintf( aRefName, "Ref on shape %d", subid);
5619               if ( mapOfNames.Contains( aRefName ))
5620               {
5621                 // load mesh "Ref on shape" - it's an entry to SObject
5622                 aDataset = new HDFdataset( aRefName, aGroup );
5623                 aDataset->OpenOnDisk();
5624                 size = aDataset->GetSize();
5625                 char* refFromFile = new char[ size ];
5626                 aDataset->ReadFromDisk( refFromFile );
5627                 aDataset->CloseOnDisk();
5628                 if ( strlen( refFromFile ) > 0 ) {
5629                   SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5630                   CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5631                   if ( !CORBA::is_nil( shapeObject ) ) {
5632                     aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5633                     if ( !aShapeObject->_is_nil() )
5634                       aShape = GeomObjectToShape( aShapeObject );
5635                   }
5636                 }
5637                 delete [] refFromFile;
5638               }
5639               // Try to read a filter of SMESH_GroupOnFilter
5640               SMESH::Filter_var filter;
5641               SMESH_PredicatePtr predicate;
5642               std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5643               if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5644               {
5645                 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5646                 aDataset->OpenOnDisk();
5647                 size = aDataset->GetSize();
5648                 char* persistStr = new char[ size ];
5649                 aDataset->ReadFromDisk( persistStr );
5650                 aDataset->CloseOnDisk();
5651                 if ( strlen( persistStr ) > 0 ) {
5652                   filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5653                   predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5654                   filters.push_back( filter );
5655                 }
5656                 delete [] persistStr;
5657               }
5658
5659               // Create group servant
5660               SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5661               SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5662                 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
5663               delete [] nameFromFile;
5664               // Obtain a SMESHDS_Group object
5665               if ( aNewGroup->_is_nil() )
5666                 continue;
5667
5668               string iorSubString = GetORB()->object_to_string( aNewGroup );
5669               int        newSubId = myStudyContext->findId( iorSubString );
5670               myStudyContext->mapOldToNew( subid, newSubId );
5671
5672               SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5673               if ( !aGroupImpl )
5674                 continue;
5675
5676               if ( SMESH_GroupOnFilter_i* aFilterGroup =
5677                    dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5678               {
5679                 aFilterGroup->SetFilter( filter );
5680                 filter->UnRegister();
5681               }
5682               SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5683               if ( !aGroupBaseDS )
5684                 continue;
5685
5686               aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5687
5688               // ouv : NPAL12872
5689               // Read color of the group
5690               char aGroupColorName[ 30 ];
5691               sprintf( aGroupColorName, "ColorGroup %d", subid);
5692               if ( mapOfNames.Contains( aGroupColorName ))
5693               {
5694                 aDataset = new HDFdataset( aGroupColorName, aGroup );
5695                 aDataset->OpenOnDisk();
5696                 size = aDataset->GetSize();
5697                 double* anRGB = new double[ size ];
5698                 aDataset->ReadFromDisk( anRGB );
5699                 aDataset->CloseOnDisk();
5700                 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5701                 aGroupBaseDS->SetColor( aColor );
5702                 delete [] anRGB;
5703               }
5704             }
5705           }
5706           aGroup->CloseOnDisk();
5707         }
5708       } // reading GROUPs
5709
5710       // instead of reading mesh data, we read only brief information of all
5711       // objects: mesh, groups, sub-meshes (issue 0021208 )
5712       if ( hasData )
5713       {
5714         SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
5715                                          meshfile.ToCString(), filename.ToCString(),
5716                                          !isMultiFile );
5717       }
5718
5719       // read Sub-Mesh ORDER if any
5720       if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5721         aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5722         aDataset->OpenOnDisk();
5723         size = aDataset->GetSize();
5724         int* smIDs = new int[ size ];
5725         aDataset->ReadFromDisk( smIDs );
5726         aDataset->CloseOnDisk();
5727         TListOfListOfInt anOrderIds;
5728         anOrderIds.push_back( TListOfInt() );
5729         for ( int i = 0; i < size; i++ )
5730           if ( smIDs[ i ] < 0 ) // is separator
5731             anOrderIds.push_back( TListOfInt() );
5732           else
5733             anOrderIds.back().push_back(smIDs[ i ]);
5734
5735         myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5736         delete [] smIDs;
5737       }
5738     } // loop on meshes
5739
5740     // update hyps needing full mesh data restored (issue 20918)
5741     for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5742     {
5743       SMESH_Hypothesis_i* hyp  = hyp_data->first;
5744       hyp->UpdateAsMeshesRestored();
5745     }
5746
5747     // notify algos on completed restoration to set sub-mesh event listeners
5748     for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5749     {
5750       SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5751       ::SMESH_Mesh& myLocMesh     = myNewMeshImpl->GetImpl();
5752
5753       TopoDS_Shape myLocShape;
5754       if(myLocMesh.HasShapeToMesh())
5755         myLocShape = myLocMesh.GetShapeToMesh();
5756       else
5757         myLocShape = SMESH_Mesh::PseudoShape();
5758
5759       myLocMesh.GetSubMesh(myLocShape)->
5760         ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5761     }
5762
5763     // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5764     list< SMESH::Filter_var >::iterator f = filters.begin();
5765     for ( ; f != filters.end(); ++f )
5766       if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5767         fi->FindBaseObjects();
5768
5769
5770     // close mesh group
5771     if(aTopGroup)
5772       aTopGroup->CloseOnDisk();
5773   }
5774   // close HDF file
5775   aFile->CloseOnDisk();
5776   delete aFile;
5777
5778   // Remove temporary files created from the stream
5779   if ( !isMultiFile )
5780   {
5781     SMESH_File meshFile( meshfile.ToCString() );
5782     if ( !meshFile ) // no meshfile exists
5783     {
5784       SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5785     }
5786     else
5787     {
5788       Engines::Container_var container = GetContainerRef();
5789       if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5790       {
5791         container_i->registerTemporaryFile( filename.ToCString() );
5792         container_i->registerTemporaryFile( meshfile.ToCString() );
5793         container_i->registerTemporaryFile( tmpDir.ToCString() );
5794       }
5795     }
5796   }
5797   pd << ""; // prevent optimizing pd out
5798
5799   // creation of tree nodes for all data objects in the study
5800   // to support tree representation customization and drag-n-drop:
5801   SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
5802   if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5803     useCaseBuilder->SetRootCurrent();
5804     useCaseBuilder->Append( theComponent ); // component object is added as the top level item
5805     SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
5806     for (it->InitEx(true); it->More(); it->Next()) {
5807       useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
5808     }
5809   }
5810
5811   return true;
5812 }
5813
5814 //=============================================================================
5815 /*!
5816  *  SMESH_Gen_i::LoadASCII
5817  *
5818  *  Load SMESH module's data in ASCII format
5819  */
5820 //=============================================================================
5821
5822 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
5823                              const SALOMEDS::TMPFile& theStream,
5824                              const char*              theURL,
5825                              bool                     isMultiFile ) {
5826   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
5827   return Load( theComponent, theStream, theURL, isMultiFile );
5828
5829   //before call main ::Load method it's need for decipher text format to
5830   //binary ( "|xx" => x' )
5831   int size = theStream.length();
5832   if ( int((size / 3 )*3) != size ) //error size of buffer
5833     return false;
5834
5835   int real_size = int(size / 3);
5836
5837   _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
5838   char tmp[3];
5839   tmp[2]='\0';
5840   unsigned int c = -1;
5841   for ( int i = 0; i < real_size; i++ )
5842   {
5843     memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
5844     sscanf( tmp, "%x", &c );
5845     sprintf( (char*)&(buffer[i]), "%c", (char)c );
5846   }
5847
5848   SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
5849
5850   return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
5851 }
5852
5853 //=============================================================================
5854 /*!
5855  *  SMESH_Gen_i::Close
5856  *
5857  *  Clears study-connected data when it is closed
5858  */
5859 //=============================================================================
5860
5861 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
5862 {
5863   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
5864
5865   // Clear study contexts data
5866   myStudyContext->Clear();
5867
5868   // remove the tmp files meshes are loaded from
5869   SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
5870
5871   // Clean trace of API methods calls
5872   CleanPythonTrace();
5873
5874   return;
5875 }
5876
5877 //=============================================================================
5878 /*!
5879  *  SMESH_Gen_i::ComponentDataType
5880  *
5881  *  Get component data type
5882  */
5883 //=============================================================================
5884
5885 char* SMESH_Gen_i::ComponentDataType()
5886 {
5887   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
5888   return CORBA::string_dup( "SMESH" );
5889 }
5890
5891
5892 //=============================================================================
5893 /*!
5894  *  SMESH_Gen_i::IORToLocalPersistentID
5895  *
5896  *  Transform data from transient form to persistent
5897  */
5898 //=============================================================================
5899
5900 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
5901                                            const char*           IORString,
5902                                            CORBA::Boolean        /*isMultiFile*/,
5903                                            CORBA::Boolean        /*isASCII*/ )
5904 {
5905   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
5906
5907   if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
5908     int anId = myStudyContext->findId( IORString );
5909     if ( anId ) {
5910       if(MYDEBUG) MESSAGE( "VSR " << anId )
5911       char strId[ 20 ];
5912       sprintf( strId, "%d", anId );
5913       return  CORBA::string_dup( strId );
5914     }
5915   }
5916   return CORBA::string_dup( "" );
5917 }
5918
5919 //=============================================================================
5920 /*!
5921  *  SMESH_Gen_i::LocalPersistentIDToIOR
5922  *
5923  *  Transform data from persistent form to transient
5924  */
5925 //=============================================================================
5926
5927 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
5928                                            const char*           aLocalPersistentID,
5929                                            CORBA::Boolean        /*isMultiFile*/,
5930                                            CORBA::Boolean        /*isASCII*/ )
5931 {
5932   if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
5933
5934   if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
5935     int anId = atoi( aLocalPersistentID );
5936     return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
5937   }
5938   return CORBA::string_dup( "" );
5939 }
5940
5941 //=======================================================================
5942 //function : RegisterObject
5943 //purpose  :
5944 //=======================================================================
5945
5946 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
5947 {
5948   if ( myStudyContext && !CORBA::is_nil( theObject )) {
5949     CORBA::String_var iorString = GetORB()->object_to_string( theObject );
5950     return myStudyContext->addObject( string( iorString.in() ) );
5951   }
5952   return 0;
5953 }
5954
5955 //================================================================================
5956 /*!
5957  * \brief Return id of registered object
5958   * \param theObject - the Object
5959   * \retval int - Object id
5960  */
5961 //================================================================================
5962
5963 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5964 {
5965   if ( myStudyContext && !CORBA::is_nil( theObject )) {
5966     string iorString = GetORB()->object_to_string( theObject );
5967     return myStudyContext->findId( iorString );
5968   }
5969   return 0;
5970 }
5971
5972 //=============================================================================
5973 /*!
5974  *  SMESH_Gen_i::SetName
5975  *
5976  *  Set a new object name
5977  */
5978 //=============================================================================
5979 void SMESH_Gen_i::SetName(const char* theIOR,
5980                           const char* theName)
5981 {
5982   if ( theIOR && strcmp( theIOR, "" ) ) {
5983     CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5984     SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
5985     if ( !aSO->_is_nil() ) {
5986       SetName( aSO, theName );
5987     }
5988   }
5989 }
5990
5991 // Version information
5992 char* SMESH_Gen_i::getVersion()
5993 {
5994 #if SMESH_DEVELOPMENT
5995   return CORBA::string_dup(SMESH_VERSION_STR"dev");
5996 #else
5997   return CORBA::string_dup(SMESH_VERSION_STR);
5998 #endif
5999 }
6000
6001 //=================================================================================
6002 // function : Move()
6003 // purpose  : Moves objects to the specified position.
6004 //            Is used in the drag-n-drop functionality.
6005 //=================================================================================
6006 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6007                         SALOMEDS::SObject_ptr      where,
6008                         CORBA::Long                row )
6009 {
6010   if ( CORBA::is_nil( where ) ) return;
6011
6012   SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6013   SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6014   SALOMEDS::SComponent_var father = where->GetFatherComponent();
6015   std::string dataType = father->ComponentDataType();
6016   if ( dataType != "SMESH" ) return; // not a SMESH component
6017
6018   SALOMEDS::SObject_var objAfter;
6019   if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6020     // insert at given row -> find insertion position
6021     SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6022     int i;
6023     for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6024     if ( i == row && useCaseIt->More() ) {
6025       objAfter = useCaseIt->Value();
6026     }
6027   }
6028
6029   for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6030     SALOMEDS::SObject_var sobj = what[i];
6031     if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6032     // insert the object to the use case tree
6033     if ( !CORBA::is_nil( objAfter ) )
6034       useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6035     else
6036       useCaseBuilder->AppendTo( where, sobj );        // append to the end of list
6037   }
6038 }
6039 //================================================================================
6040 /*!
6041  * \brief Returns true if algorithm can be used to mesh a given geometry
6042  *  \param [in] theAlgoType - the algorithm type
6043  *  \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6044  *  \param [in] theGeomObject - the geometry to mesh
6045  *  \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6046  *         else, returns \c True if at least one shape is meshable
6047  *  \return CORBA::Boolean - can or can't
6048  */
6049 //================================================================================
6050
6051 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char*           theAlgoType,
6052                                            const char*           theLibName,
6053                                            GEOM::GEOM_Object_ptr theGeomObject,
6054                                            CORBA::Boolean        toCheckAll)
6055 {
6056   SMESH_TRY;
6057
6058   std::string aPlatformLibName;
6059   typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6060   GenericHypothesisCreator_i* aCreator =
6061     getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6062   if (aCreator)
6063   {
6064     TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6065     return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
6066   }
6067   else
6068   {
6069     return false;
6070   }
6071
6072   SMESH_CATCH( SMESH::doNothing );
6073
6074 #ifdef _DEBUG_
6075   cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6076 #endif
6077   return true;
6078 }
6079
6080 //=================================================================================
6081 // function : GetInsideSphere
6082 // purpose  : Collect indices of elements, which are located inside the sphere
6083 //=================================================================================
6084 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6085                                                  SMESH::ElementType     theElemType,
6086                                                  CORBA::Double         theX,
6087                                                  CORBA::Double         theY,
6088                                                  CORBA::Double         theZ,
6089                                                  CORBA::Double         theR)
6090 {
6091   SMESH::long_array_var aResult = new SMESH::long_array();
6092   if ( meshPart->_is_nil() )
6093     return aResult._retn();
6094
6095   // 1. Create geometrical object
6096   gp_Pnt aP( theX, theY, theZ );
6097   TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6098
6099   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6100
6101   if ( lst.size() > 0 ) {
6102     aResult->length( lst.size() );
6103     for ( size_t i = 0; i < lst.size(); i++ ) {
6104       aResult[i] = lst[i];
6105     }
6106   }
6107   return aResult._retn();
6108 }
6109
6110 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6111                                               SMESH::ElementType        theElemType,
6112                                               CORBA::Double             theX1,
6113                                               CORBA::Double             theY1,
6114                                               CORBA::Double             theZ1,
6115                                               CORBA::Double             theX2,
6116                                               CORBA::Double             theY2,
6117                                               CORBA::Double             theZ2) {
6118   SMESH::long_array_var aResult = new SMESH::long_array();
6119   if( meshPart->_is_nil() )
6120     return aResult._retn();
6121
6122   TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6123
6124   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6125
6126   if( lst.size() > 0 ) {
6127     aResult->length( lst.size() );
6128     for ( size_t i = 0; i < lst.size(); i++ ) {
6129       aResult[i] = lst[i];
6130     }
6131   }
6132   return aResult._retn();
6133 }
6134
6135 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6136                                                    SMESH::ElementType        theElemType,
6137                                                    CORBA::Double             theX,
6138                                                    CORBA::Double             theY,
6139                                                    CORBA::Double             theZ,
6140                                                    CORBA::Double             theDX,
6141                                                    CORBA::Double             theDY,
6142                                                    CORBA::Double             theDZ,
6143                                                    CORBA::Double             theH,
6144                                                    CORBA::Double             theR ){
6145   SMESH::long_array_var aResult = new SMESH::long_array();
6146   if( meshPart->_is_nil() )
6147     return aResult._retn();
6148
6149   gp_Pnt aP( theX, theY, theZ );
6150   gp_Vec aV( theDX, theDY, theDZ );
6151   gp_Ax2 anAxes (aP, aV);
6152
6153   TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6154
6155   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6156
6157   if( lst.size() > 0 ) {
6158     aResult->length( lst.size() );
6159     for ( size_t i = 0; i < lst.size(); i++ ) {
6160       aResult[i] = lst[i];
6161     }
6162   }
6163   return aResult._retn();
6164 }
6165
6166 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6167                                            SMESH::ElementType        theElemType,
6168                                            GEOM::GEOM_Object_ptr     theGeom,
6169                                            CORBA::Double             theTolerance ) {
6170   SMESH::long_array_var aResult = new SMESH::long_array();
6171   if( meshPart->_is_nil() || theGeom->_is_nil() )
6172     return aResult._retn();
6173
6174   TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6175
6176   std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6177
6178   if( lst.size() > 0 ) {
6179     aResult->length( lst.size() );
6180     for ( size_t i = 0; i < lst.size(); i++ ) {
6181       aResult[i] = lst[i];
6182     }
6183   }
6184   return aResult._retn();
6185 }
6186
6187
6188
6189 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6190                                            SMESH::ElementType theElemType,
6191                                            TopoDS_Shape& aShape,
6192                                            double* theTolerance) {
6193
6194   std::vector<long> res;
6195   SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6196
6197   if ( mesh->_is_nil() )
6198     return res;
6199
6200   SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6201   if ( !anImpl )
6202     return res;
6203
6204   const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6205
6206   if ( !meshDS )
6207     return res;
6208
6209   SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6210   SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6211   anElementsOnShape->SetAllNodes( true );
6212   anElementsOnShape->SetMesh( meshDS );
6213   anElementsOnShape->SetShape( aShape, aType );
6214
6215   if(theTolerance)
6216     anElementsOnShape->SetTolerance(*theTolerance);
6217
6218   SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6219   if ( !msource->_is_nil() ) { // Mesh case
6220     SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6221     if ( elemIt ) {
6222       while ( elemIt->more() ) {
6223         const SMDS_MeshElement* anElem = elemIt->next();
6224         long anId = anElem->GetID();
6225         if ( anElementsOnShape->IsSatisfy( anId ) )
6226           res.push_back( anId );
6227       }
6228     }
6229   }
6230   SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6231   if ( !gsource->_is_nil() ) {
6232     if(theElemType == SMESH::NODE) {
6233       SMESH::long_array_var nodes = gsource->GetNodeIDs();
6234       for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6235         if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6236           long anId = node->GetID();
6237           if ( anElementsOnShape->IsSatisfy( anId ) )
6238             res.push_back( anId );
6239         }
6240       }
6241     } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6242       SMESH::long_array_var elems = gsource->GetListOfID();
6243       for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6244         if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6245           long anId = elem->GetID();
6246           if ( anElementsOnShape->IsSatisfy( anId ) )
6247             res.push_back( anId );
6248         }
6249       }
6250     }
6251   }
6252   SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6253   if ( !smsource->_is_nil() ) {
6254     SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6255     for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6256       const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6257       if (elem) {
6258         long anId = elem->GetID();
6259         if ( anElementsOnShape->IsSatisfy( anId ) )
6260           res.push_back( anId );
6261       }
6262     }
6263   }
6264   return res;
6265 }
6266
6267
6268 //=============================================================================
6269 /*!
6270  *  SMESHEngine_factory
6271  *
6272  *  C factory, accessible with dlsym, after dlopen
6273  */
6274 //=============================================================================
6275
6276 extern "C"
6277 { SMESH_I_EXPORT
6278   PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr            orb,
6279                                                  PortableServer::POA_ptr   poa,
6280                                                  PortableServer::ObjectId* contId,
6281                                                  const char*               instanceName,
6282                                                  const char*               interfaceName )
6283   {
6284     if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6285     if(MYDEBUG) SCRUTE(interfaceName);
6286     SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6287     return aSMESHGen->getId() ;
6288   }
6289 }