1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
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.
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.
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
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
27 #include <TopExp_Explorer.hxx>
29 #include <TopoDS_Iterator.hxx>
30 #include <TopoDS_Compound.hxx>
31 #include <TopoDS_CompSolid.hxx>
32 #include <TopoDS_Solid.hxx>
33 #include <TopoDS_Shell.hxx>
34 #include <TopoDS_Face.hxx>
35 #include <TopoDS_Wire.hxx>
36 #include <TopoDS_Edge.hxx>
37 #include <TopoDS_Vertex.hxx>
38 #include <TopoDS_Shape.hxx>
39 #include <TopTools_MapOfShape.hxx>
40 #include <TopTools_IndexedMapOfShape.hxx>
41 #include <TopTools_ListOfShape.hxx>
42 #include <TopTools_ListIteratorOfListOfShape.hxx>
44 #include <BRep_Tool.hxx>
45 #include <TCollection_AsciiString.hxx>
47 #include <BRepPrimAPI_MakeSphere.hxx>
48 #include <BRepPrimAPI_MakeCylinder.hxx>
49 #include <BRepPrimAPI_MakeBox.hxx>
57 #include <libgen.h> // for basename function
61 #define LibHandle HMODULE
62 #define LoadLib( name ) LoadLibrary( name )
63 #define GetProc GetProcAddress
64 #define UnLoadLib( handle ) FreeLibrary( handle );
66 #define LibHandle void*
67 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
69 #define UnLoadLib( handle ) dlclose( handle );
72 #include "SMESH_Gen_i.hxx"
73 #include "SMESH_version.h"
75 #include "DriverMED_W_SMESHDS_Mesh.h"
76 #include "DriverMED_R_SMESHDS_Mesh.h"
78 #include "DriverCGNS_Read.hxx"
80 #include "MED_Factory.hxx"
81 #include "SMDS_EdgePosition.hxx"
82 #include "SMDS_FacePosition.hxx"
83 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
84 #include "SMDS_SetIterator.hxx"
85 #include "SMDS_SpacePosition.hxx"
86 #include "SMDS_VertexPosition.hxx"
87 #include "SMESHDS_Document.hxx"
88 #include "SMESHDS_Group.hxx"
89 #include "SMESHDS_GroupOnGeom.hxx"
90 #include "SMESH_Algo_i.hxx"
91 #include "SMESH_File.hxx"
92 #include "SMESH_Group.hxx"
93 #include "SMESH_Group_i.hxx"
94 #include "SMESH_Hypothesis.hxx"
95 #include "SMESH_Hypothesis_i.hxx"
96 #include "SMESH_Mesh.hxx"
97 #include "SMESH_MeshEditor.hxx"
98 #include "SMESH_Mesh_i.hxx"
99 #include "SMESH_PreMeshInfo.hxx"
100 #include "SMESH_PythonDump.hxx"
101 #include "SMESH_ControlsDef.hxx"
102 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
104 #include CORBA_SERVER_HEADER(SMESH_Group)
105 #include CORBA_SERVER_HEADER(SMESH_Filter)
106 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
109 #include <GEOM_Client.hxx>
111 #include <Basics_Utils.hxx>
112 #include <Basics_DirUtils.hxx>
114 #include <OpUtil.hxx>
115 #include <SALOMEDS_Tool.hxx>
116 #include <SALOME_Container_i.hxx>
117 #include <SALOME_LifeCycleCORBA.hxx>
118 #include <SALOME_NamingService.hxx>
119 #include <Utils_CorbaException.hxx>
120 #include <Utils_ExceptHandlers.hxx>
121 #include <Utils_SINGLETON.hxx>
122 #include <utilities.h>
124 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
125 #include CORBA_CLIENT_HEADER(SALOME_Session)
127 // helpers about SALOME::GenericObj
128 #include <SALOMEDS_wrap.hxx>
129 #include <SALOMEDS_Attributes_wrap.hxx>
130 #include <GEOM_wrap.hxx>
139 using SMESH::TPythonDump;
142 #define NUM_TMP_FILES 2
145 static int MYDEBUG = 0;
147 static int MYDEBUG = 0;
150 // Static variables definition
151 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
152 CORBA::ORB_var SMESH_Gen_i::myOrb;
153 PortableServer::POA_var SMESH_Gen_i::myPoa;
154 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
155 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
156 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
159 const int nbElemPerDiagonal = 10;
161 //=============================================================================
163 * GetServant [ static ]
165 * Get servant of the CORBA object
167 //=============================================================================
169 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
171 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
174 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
178 INFOS( "GetServant - Unknown exception was caught!!!" );
183 //=============================================================================
185 * SObjectToObject [ static ]
187 * Get CORBA object corresponding to the SALOMEDS::SObject
189 //=============================================================================
191 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
193 SALOMEDS::GenericAttribute_wrap anAttr;
194 CORBA::Object_var anObj;
195 if ( !theSObject->_is_nil() ) {
197 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
198 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
199 CORBA::String_var aValue = anIOR->Value();
200 if( strcmp( aValue, "" ) != 0 )
201 anObj = GetORB()->string_to_object( aValue );
205 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
211 //=============================================================================
215 * Get SALOME_NamingService object
217 //=============================================================================
219 SALOME_NamingService* SMESH_Gen_i::GetNS()
221 if ( myNS == NULL ) {
222 myNS = SINGLETON_<SALOME_NamingService>::Instance();
223 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
224 myNS->init_orb( GetORB() );
229 //=============================================================================
233 * Get SALOME_LifeCycleCORBA object
235 //=============================================================================
236 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
237 if ( myLCC == NULL ) {
238 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
244 //=============================================================================
246 * GetGeomEngine [ static ]
248 * Get GEOM::GEOM_Gen reference
250 //=============================================================================
251 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
252 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
253 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
254 //CCRT return aGeomEngine._retn();
255 if(CORBA::is_nil(myGeomGen))
257 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
258 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
263 //=============================================================================
265 * SMESH_Gen_i::SMESH_Gen_i
267 * Default constructor: not for use
269 //=============================================================================
271 SMESH_Gen_i::SMESH_Gen_i()
275 //=============================================================================
277 * SMESH_Gen_i::SMESH_Gen_i
279 * Standard constructor, used with Container
281 //=============================================================================
283 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
284 PortableServer::POA_ptr poa,
285 PortableServer::ObjectId* contId,
286 const char* instanceName,
287 const char* interfaceName )
288 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
291 myOrb = CORBA::ORB::_duplicate(orb);
292 myPoa = PortableServer::POA::_duplicate(poa);
295 _id = myPoa->activate_object( _thisObj );
297 myStudyContext = new StudyContext;
299 myIsEmbeddedMode = false;
300 myIsEnablePublish = true;
301 myShapeReader = NULL; // shape reader
303 myIsHistoricalPythonDump = true;
304 myToForgetMeshDataOnHypModif = false;
306 // set it in standalone mode only
307 //OSD::SetSignal( true );
309 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
310 // find out mode (embedded or standalone) here else
311 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
312 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
313 if ( SALOME_NamingService* ns = GetNS() )
315 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
316 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
317 if ( !session->_is_nil() )
319 CORBA::String_var str_host = session->getHostname();
320 CORBA::Long s_pid = session->getPID();
321 string my_host = Kernel_Utils::GetHostname();
323 long my_pid = (long)_getpid();
325 long my_pid = (long) getpid();
327 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
332 //=============================================================================
334 * SMESH_Gen_i::~SMESH_Gen_i
338 //=============================================================================
340 SMESH_Gen_i::~SMESH_Gen_i()
342 // delete hypothesis creators
343 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
344 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
346 // same creator can be mapped under different names
347 GenericHypothesisCreator_i* creator = (*itHyp).second;
351 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
352 if ( creator == (*itHyp2).second )
353 (*itHyp2).second = 0;
355 myHypCreatorMap.clear();
357 // Clear study contexts data
358 delete myStudyContext;
360 // delete shape reader
362 delete myShapeReader;
364 //=============================================================================
366 * SMESH_Gen_i::getHypothesisCreator
368 * Get hypothesis creator
370 //=============================================================================
371 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
372 const char* theLibName,
373 std::string& thePlatformLibName)
374 throw (SALOME::SALOME_Exception)
376 std::string aPlatformLibName;
377 /* It's Need to tranlate lib name for WIN32 or X platform */
378 if ( theLibName && theLibName[0] != '\0' )
380 int libNameLen = strlen(theLibName);
381 //check for old format "libXXXXXXX.so"
382 if (libNameLen > 7 &&
383 !strncmp( theLibName, "lib", 3 ) &&
384 !strcmp( theLibName+libNameLen-3, ".so" ))
388 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
389 #elif defined(__APPLE__)
390 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
392 aPlatformLibName = theLibName;
397 //try to use new format
399 aPlatformLibName = theLibName;
400 aPlatformLibName += ".dll";
401 #elif defined(__APPLE__)
402 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
404 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
408 thePlatformLibName = aPlatformLibName;
410 Unexpect aCatch(SALOME_SalomeException);
411 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
413 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
414 GenericHypothesisCreator_i* aCreator;
417 // check, if creator for this hypothesis type already exists
418 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
420 // load plugin library
421 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
422 LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
425 // report any error, if occurred
427 const char* anError = dlerror();
428 throw(SALOME_Exception(anError));
430 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
434 // get method, returning hypothesis creator
435 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
436 GetHypothesisCreator procHandle =
437 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
440 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
441 UnLoadLib(libHandle);
444 // get hypothesis creator
445 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
446 aCreator = procHandle(theHypName);
449 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
451 // map hypothesis creator to a hypothesis name
452 myHypCreatorMap[string(theHypName)] = aCreator;
457 return myHypCreatorMap[string(theHypName)];
460 catch (SALOME_Exception& S_ex)
462 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
467 //=============================================================================
469 * SMESH_Gen_i::createHypothesis
471 * Create hypothesis of given type
473 //=============================================================================
474 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
475 const char* theLibName)
477 SMESH_Hypothesis_i* myHypothesis_i = 0;
478 SMESH::SMESH_Hypothesis_var hypothesis_i;
479 std::string aPlatformLibName;
480 GenericHypothesisCreator_i* aCreator =
481 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
483 // create a new hypothesis object, store its ref. in studyContext
484 myHypothesis_i = aCreator->Create(myPoa, &myGen);
487 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
488 CORBA::String_var hypName = myHypothesis_i->GetName();
489 myHypCreatorMap[ hypName.in() ] = aCreator;
491 // activate the CORBA servant of hypothesis
492 hypothesis_i = myHypothesis_i->_this();
493 int nextId = RegisterObject( hypothesis_i );
494 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
495 else { nextId = 0; } // avoid "unused variable" warning in release mode
497 return hypothesis_i._retn();
500 //=============================================================================
502 * SMESH_Gen_i::createMesh
504 * Create empty mesh on shape
506 //=============================================================================
507 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
508 throw ( SALOME::SALOME_Exception )
510 Unexpect aCatch(SALOME_SalomeException);
511 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
513 // Get or create the GEOM_Client instance
515 // create a new mesh object servant, store it in a map in study context
516 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
517 // create a new mesh object
518 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
519 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
521 // activate the CORBA servant of Mesh
522 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
523 int nextId = RegisterObject( mesh );
524 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
525 else { nextId = 0; } // avoid "unused variable" warning in release mode
528 catch (SALOME_Exception& S_ex) {
529 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
531 return SMESH::SMESH_Mesh::_nil();
534 //=============================================================================
536 * SMESH_Gen_i::GetShapeReader
540 //=============================================================================
541 GEOM_Client* SMESH_Gen_i::GetShapeReader()
543 // create shape reader if necessary
544 if ( !myShapeReader )
545 myShapeReader = new GEOM_Client(GetContainerRef());
546 ASSERT( myShapeReader );
547 return myShapeReader;
550 //=============================================================================
552 * SMESH_Gen_i::SetGeomEngine
554 * Set GEOM::GEOM_Gen reference
556 //=============================================================================
557 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
558 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
560 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
561 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
562 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
566 //=============================================================================
568 * SMESH_Gen_i::SetEmbeddedMode
572 //=============================================================================
574 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
576 myIsEmbeddedMode = theMode;
578 if ( !myIsEmbeddedMode ) {
579 //PAL10867: disable signals catching with "noexcepthandler" option
580 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
581 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
586 char* envDisableFPE = getenv("DISABLE_FPE");
587 if (envDisableFPE && atoi(envDisableFPE))
592 OSD::SetSignal( raiseFPE );
594 // else OSD::SetSignal() is called in GUI
598 //=============================================================================
600 * SMESH_Gen_i::IsEmbeddedMode
604 //=============================================================================
606 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
608 return myIsEmbeddedMode;
611 //=============================================================================
613 * SMESH_Gen_i::SetEnablePublish
615 * Set enable publishing in the study
617 //=============================================================================
618 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
620 myIsEnablePublish = theIsEnablePublish;
623 //=============================================================================
625 * SMESH_Gen_i::IsEnablePublish
627 * Check enable publishing
629 //=============================================================================
631 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
633 return myIsEnablePublish;
636 //=============================================================================
638 * SMESH_Gen_i::UpdateStudy
640 * Update study (needed at switching GEOM->SMESH)
642 //=============================================================================
644 void SMESH_Gen_i::UpdateStudy()
646 if ( !myStudyContext )
647 myStudyContext = new StudyContext;
649 SALOMEDS::Study_var aStudy = getStudyServant();
650 if ( !CORBA::is_nil( aStudy ) ) {
651 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
652 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
653 if( !GEOM_var->_is_nil() )
654 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
655 // NPAL16168, issue 0020210
656 // Let meshes update their data depending on GEOM groups that could change
657 CORBA::String_var compDataType = ComponentDataType();
658 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
659 if ( !me->_is_nil() ) {
660 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
661 for ( ; anIter->More(); anIter->Next() ) {
662 SALOMEDS::SObject_wrap so = anIter->Value();
663 CORBA::Object_var ior = SObjectToObject( so );
664 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
665 mesh->CheckGeomModif();
671 //=============================================================================
673 * SMESH_Gen_i::GetStudyContext
677 //=============================================================================
678 StudyContext* SMESH_Gen_i::GetStudyContext()
680 return myStudyContext;
683 //=============================================================================
685 * SMESH_Gen_i::CreateHypothesis
687 * Create hypothesis/algorothm of given type and publish it in the study
689 //=============================================================================
691 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
692 const char* theLibName )
693 throw ( SALOME::SALOME_Exception )
695 Unexpect aCatch(SALOME_SalomeException);
696 // Create hypothesis/algorithm
697 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
699 // Publish hypothesis/algorithm in the study
700 if ( CanPublishInStudy( hyp ) ) {
701 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
702 if ( !aSO->_is_nil() ) {
703 // Update Python script
704 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
705 << theHypName << "', '" << theLibName << "')";
712 //================================================================================
714 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
715 * existing on the given geometry or to size of the geometry.
716 * \param theHypType - hypothesis type name
717 * \param theLibName - plugin library name
718 * \param theMesh - The mesh of interest
719 * \param theGeom - The shape to get parameter values from
720 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
721 * in a study and used to compute the mesh, or a temporary one created just to pass
724 //================================================================================
726 SMESH::SMESH_Hypothesis_ptr
727 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
728 const char* theLibName,
729 SMESH::SMESH_Mesh_ptr theMesh,
730 GEOM::GEOM_Object_ptr theGeom,
731 CORBA::Boolean byMesh)
732 throw ( SALOME::SALOME_Exception )
734 Unexpect aCatch(SALOME_SalomeException);
735 if ( byMesh && CORBA::is_nil( theMesh ) )
736 return SMESH::SMESH_Hypothesis::_nil();
737 if ( byMesh && CORBA::is_nil( theGeom ) )
738 return SMESH::SMESH_Hypothesis::_nil();
740 // -----------------------------------------------
741 // find hypothesis used to mesh theGeom
742 // -----------------------------------------------
744 // get mesh and shape
745 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
746 TopoDS_Shape shape = GeomObjectToShape( theGeom );
747 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
748 return SMESH::SMESH_Hypothesis::_nil();
749 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
751 // create a temporary hypothesis to know its dimension
752 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
753 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
755 return SMESH::SMESH_Hypothesis::_nil();
756 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
759 // look for a hypothesis of theHypType used to mesh the shape
760 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
763 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
764 int nbLocalHyps = aHypList->length();
765 for ( int i = 0; i < nbLocalHyps; i++ ) {
766 CORBA::String_var hypName = aHypList[i]->GetName();
767 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
768 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
770 // check super shapes
771 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
772 while ( nbLocalHyps == 0 && itShape.More() ) {
773 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
774 if ( ! CORBA::is_nil( geomObj )) {
775 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
776 nbLocalHyps = aHypList->length();
777 for ( int i = 0; i < nbLocalHyps; i++ )
778 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
779 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
785 // let the temporary hypothesis find out somehow parameter values by mesh
786 if ( hyp->SetParametersByMesh( mesh, shape ))
787 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
792 diagonal = mesh->GetShapeDiagonalSize();
794 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
795 ::SMESH_Hypothesis::TDefaults dflts;
796 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
797 dflts._nbSegments = myGen.GetDefaultNbSegments();
798 dflts._shape = &shape;
799 // let the temporary hypothesis initialize it's values
800 if ( hyp->SetParametersByDefaults( dflts, mesh ))
801 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
804 return SMESH::SMESH_Hypothesis::_nil();
807 //=============================================================================
809 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
810 * \param [in] theHyp - the hypothesis of interest
811 * \param [out] theMesh - the sole mesh using \a theHyp
812 * \param [out] theShape - the sole geometry \a theHyp is assigned to
813 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
815 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
816 * considered as SAME sub-mesh => result is \c true.
817 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
818 * a shape to which an hyp being edited is assigned.
820 //=============================================================================
822 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
823 SMESH::SMESH_Mesh_out theMesh,
824 GEOM::GEOM_Object_out theShape)
826 if ( CORBA::is_nil( theHyp ))
829 // get Mesh component SO
830 CORBA::String_var compDataType = ComponentDataType();
831 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
832 if ( CORBA::is_nil( comp ))
835 // look for child SO of meshes
836 SMESH::SMESH_Mesh_var foundMesh;
837 TopoDS_Shape foundShape;
839 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
840 for ( ; meshIter->More() && isSole; meshIter->Next() )
842 SALOMEDS::SObject_wrap curSO = meshIter->Value();
843 CORBA::Object_var obj = SObjectToObject( curSO );
844 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
848 // look for a sole shape where theHyp is assigned
849 bool isHypFound = false;
850 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
851 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
852 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
854 const THypList& hyps = s2hypsIt.Value();
855 THypList::const_iterator h = hyps.begin();
856 for ( ; h != hyps.end(); ++h )
857 if ( (*h)->GetID() == theHyp->GetId() )
859 if ( h != hyps.end()) // theHyp found
862 if ( ! foundShape.IsNull() &&
863 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
865 foundShape.Nullify();
869 foundShape = s2hypsIt.Key();
871 } // loop on assigned hyps
873 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
875 if ( !foundMesh->_is_nil() ) // not a sole mesh
877 if ( !foundMesh->HasShapeToMesh() ||
878 !mesh_i ->HasShapeToMesh() )
880 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
884 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
885 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
886 isSole = s1->IsSame( s2 );
889 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
895 ! foundMesh->_is_nil() &&
896 ! foundShape.IsNull() )
898 theMesh = foundMesh._retn();
899 theShape = ShapeToGeomObject( foundShape );
900 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
905 //=============================================================================
907 * Sets number of segments per diagonal of boundary box of geometry by which
908 * default segment length of appropriate 1D hypotheses is defined
910 //=============================================================================
912 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
913 throw ( SALOME::SALOME_Exception )
915 if ( theNbSegments > 0 )
916 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
918 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
920 //=============================================================================
922 * \brief Sets default number of segments per edge
924 //=============================================================================
925 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
926 throw ( SALOME::SALOME_Exception )
928 if ( theNbSegments > 0 )
929 myGen.SetDefaultNbSegments( int(theNbSegments) );
931 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
934 //=============================================================================
938 //=============================================================================
940 void SMESH_Gen_i::SetOption(const char* name, const char* value)
942 if ( name && value && strlen( value ) > 0 )
945 if ( strcmp(name, "historical_python_dump") == 0 )
947 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
948 msgToGUI = "preferences/SMESH/historical_python_dump/";
949 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
951 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
953 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
954 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
955 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
957 else if ( strcmp(name, "default_grp_color") == 0 )
961 // color must be presented as a string of following form:
962 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
964 for ( size_t i = 0; i < str.length()/2; i++ )
965 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
966 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
968 else if ( value ) { // rgb color ("255,170,0", for example)
969 string tempValue( value );
970 char* colorValue = strtok( &tempValue[0], "," );
971 while ( colorValue != NULL ) {
972 int c_value = atoi( colorValue );
973 if ( c_value >= 0 && c_value <= 255 )
974 color.push_back( c_value );
975 colorValue = strtok( NULL, "," );
978 if ( color.size() == 3 ) { // color must have three valid component
979 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
980 myDefaultGroupColor = value;
981 msgToGUI = "preferences/SMESH/default_grp_color/";
986 // update preferences in case if SetOption() is invoked from python console
987 if ( !msgToGUI.empty() )
989 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
990 SALOME::Session_var session = SALOME::Session::_narrow( obj );
991 if ( !CORBA::is_nil( session ) )
992 session->emitMessageOneWay(msgToGUI.c_str());
997 //=============================================================================
999 Return an option value
1001 //=============================================================================
1003 char* SMESH_Gen_i::GetOption(const char* name)
1007 if ( strcmp(name, "historical_python_dump") == 0 )
1009 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1011 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1013 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1015 if ( strcmp(name, "default_grp_color") == 0 )
1017 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1020 return CORBA::string_dup( "" );
1023 //=============================================================================
1025 * SMESH_Gen_i::CreateMesh
1027 * Create empty mesh on a shape and publish it in the study
1029 //=============================================================================
1031 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1032 throw ( SALOME::SALOME_Exception )
1034 Unexpect aCatch(SALOME_SalomeException);
1035 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1037 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1039 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1040 ASSERT( meshServant );
1041 meshServant->SetShape( theShapeObject );
1043 // publish mesh in the study
1044 if ( CanPublishInStudy( mesh ) ) {
1045 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1046 aStudyBuilder->NewCommand(); // There is a transaction
1047 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1048 aStudyBuilder->CommitCommand();
1049 if ( !aSO->_is_nil() ) {
1050 // Update Python script
1051 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1055 return mesh._retn();
1058 //=============================================================================
1060 * SMESH_Gen_i::CreateEmptyMesh
1064 //=============================================================================
1066 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1067 throw ( SALOME::SALOME_Exception )
1069 Unexpect aCatch(SALOME_SalomeException);
1070 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1072 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1074 // publish mesh in the study
1075 if ( CanPublishInStudy( mesh ) ) {
1076 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1077 aStudyBuilder->NewCommand(); // There is a transaction
1078 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1079 aStudyBuilder->CommitCommand();
1080 if ( !aSO->_is_nil() ) {
1081 // Update Python script
1082 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1086 return mesh._retn();
1091 //================================================================================
1093 * \brief Throws an exception in case if the file can't be read
1095 //================================================================================
1097 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1099 SMESH_File f ( theFileName );
1102 if ( !f.error().empty() )
1103 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1105 THROW_SALOME_CORBA_EXCEPTION
1106 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1107 SALOME::BAD_PARAM );
1112 //=============================================================================
1114 * SMESH_Gen_i::CreateMeshFromUNV
1116 * Create mesh and import data from UNV file
1118 //=============================================================================
1120 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1121 throw ( SALOME::SALOME_Exception )
1123 Unexpect aCatch(SALOME_SalomeException);
1125 checkFileReadable( theFileName );
1127 SMESH::SMESH_Mesh_var aMesh = createMesh();
1129 // publish mesh in the study
1130 if ( CanPublishInStudy( aMesh ) ) {
1131 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1132 aStudyBuilder->NewCommand(); // There is a transaction
1133 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1134 aStudyBuilder->CommitCommand();
1135 if ( !aSO->_is_nil() ) {
1136 // Update Python script
1137 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1141 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1143 aServant->ImportUNVFile( theFileName );
1145 // Dump creation of groups
1146 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1148 aServant->GetImpl().GetMeshDS()->Modified();
1149 return aMesh._retn();
1152 //=============================================================================
1154 * SMESH_Gen_i::CreateMeshFromMED
1156 * Create mesh and import data from MED file
1158 //=============================================================================
1160 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1161 SMESH::DriverMED_ReadStatus& theStatus,
1162 const char* theCommandNameForPython,
1163 const char* theFileNameForPython)
1166 char bname[ _MAX_FNAME ];
1167 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1168 string aFileName = bname;
1170 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1172 // Retrieve mesh names from the file
1173 DriverMED_R_SMESHDS_Mesh myReader;
1174 myReader.SetFile( theFileName );
1175 myReader.SetMeshId( -1 );
1176 Driver_Mesh::Status aStatus;
1177 list<string> aNames = myReader.GetMeshNames(aStatus);
1178 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1179 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1181 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1184 TPythonDump aPythonDump;
1185 aPythonDump << "([";
1187 if (theStatus == SMESH::DRS_OK) {
1188 SALOMEDS::StudyBuilder_var aStudyBuilder;
1189 aStudyBuilder = getStudyServant()->NewBuilder();
1190 aStudyBuilder->NewCommand(); // There is a transaction
1192 aResult->length( aNames.size() );
1195 // Iterate through all meshes and create mesh objects
1196 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1199 if (i > 0) aPythonDump << ", ";
1202 SMESH::SMESH_Mesh_var mesh = createMesh();
1204 // publish mesh in the study
1205 SALOMEDS::SObject_wrap aSO;
1206 if ( CanPublishInStudy( mesh ) )
1207 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1208 // - as names of meshes are stored in MED file, we use them for data publishing
1209 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1210 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1213 if ( !aSO->_is_nil() ) {
1216 aPythonDump << "mesh_" << i;
1219 // Read mesh data (groups are published automatically by ImportMEDFile())
1220 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1221 ASSERT( meshServant );
1222 SMESH::DriverMED_ReadStatus status1 =
1223 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1224 if (status1 > theStatus)
1225 theStatus = status1;
1227 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1228 meshServant->GetImpl().GetMeshDS()->Modified();
1230 if ( !aStudyBuilder->_is_nil() )
1231 aStudyBuilder->CommitCommand();
1234 // Update Python script
1235 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1237 // Dump creation of groups
1238 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1239 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1241 return aResult._retn();
1244 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1245 SMESH::DriverMED_ReadStatus& theStatus)
1246 throw ( SALOME::SALOME_Exception )
1248 Unexpect aCatch(SALOME_SalomeException);
1249 checkFileReadable( theFileName );
1251 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1255 //=============================================================================
1257 * SMESH_Gen_i::CreateMeshFromSAUV
1259 * Create mesh and import data from SAUV file
1261 //=============================================================================
1263 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1264 SMESH::DriverMED_ReadStatus& theStatus)
1265 throw ( SALOME::SALOME_Exception )
1267 Unexpect aCatch(SALOME_SalomeException);
1268 checkFileReadable( theFileName );
1270 std::string sauvfilename(theFileName);
1271 std::string medfilename(theFileName);
1272 medfilename += ".med";
1275 cmd = "%PYTHONBIN% ";
1280 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1282 system(cmd.c_str());
1283 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1285 cmd = "%PYTHONBIN% ";
1290 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1292 system(cmd.c_str());
1296 //=============================================================================
1298 * SMESH_Gen_i::CreateMeshFromSTL
1300 * Create mesh and import data from STL file
1302 //=============================================================================
1304 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1305 throw ( SALOME::SALOME_Exception )
1307 Unexpect aCatch(SALOME_SalomeException);
1308 checkFileReadable( theFileName );
1310 SMESH::SMESH_Mesh_var aMesh = createMesh();
1313 char bname[ _MAX_FNAME ];
1314 _splitpath( theFileName, NULL, NULL, bname, NULL );
1315 string aFileName = bname;
1317 string aFileName = basename( const_cast<char *>(theFileName) );
1319 // publish mesh in the study
1320 if ( CanPublishInStudy( aMesh ) ) {
1321 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1322 aStudyBuilder->NewCommand(); // There is a transaction
1323 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1324 aStudyBuilder->CommitCommand();
1325 if ( !aSO->_is_nil() ) {
1326 // Update Python script
1327 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1331 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1333 aServant->ImportSTLFile( theFileName );
1334 aServant->GetImpl().GetMeshDS()->Modified();
1335 return aMesh._retn();
1338 //================================================================================
1340 * \brief Create meshes and import data from the CGSN file
1342 //================================================================================
1344 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1345 SMESH::DriverMED_ReadStatus& theStatus)
1346 throw ( SALOME::SALOME_Exception )
1348 Unexpect aCatch(SALOME_SalomeException);
1349 checkFileReadable( theFileName );
1351 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1354 // Retrieve nb meshes from the file
1355 DriverCGNS_Read myReader;
1356 myReader.SetFile( theFileName );
1357 Driver_Mesh::Status aStatus;
1358 int nbMeshes = myReader.GetNbMeshes(aStatus);
1359 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1361 aResult->length( nbMeshes );
1363 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1366 TPythonDump aPythonDump;
1367 aPythonDump << "([";
1369 if (theStatus == SMESH::DRS_OK)
1371 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1372 aStudyBuilder->NewCommand(); // There is a transaction
1376 // Iterate through all meshes and create mesh objects
1377 for ( ; i < nbMeshes; ++i )
1380 if (i > 0) aPythonDump << ", ";
1383 SMESH::SMESH_Mesh_var mesh = createMesh();
1384 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1386 // Read mesh data (groups are published automatically by ImportMEDFile())
1387 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1388 ASSERT( meshServant );
1390 SMESH::DriverMED_ReadStatus status1 =
1391 meshServant->ImportCGNSFile( theFileName, i, meshName );
1392 if (status1 > theStatus)
1393 theStatus = status1;
1395 meshServant->GetImpl().GetMeshDS()->Modified();
1396 // publish mesh in the study
1397 SALOMEDS::SObject_wrap aSO;
1398 if ( CanPublishInStudy( mesh ) )
1399 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1402 if ( !aSO->_is_nil() ) {
1406 aPythonDump << "mesh_" << i;
1409 aStudyBuilder->CommitCommand();
1412 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1414 // Dump creation of groups
1415 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1416 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1418 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1421 return aResult._retn();
1424 //================================================================================
1426 * \brief Create a mesh and import data from a GMF file
1428 //================================================================================
1430 SMESH::SMESH_Mesh_ptr
1431 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1432 CORBA::Boolean theMakeRequiredGroups,
1433 SMESH::ComputeError_out theError)
1434 throw ( SALOME::SALOME_Exception )
1436 Unexpect aCatch(SALOME_SalomeException);
1437 checkFileReadable( theFileName );
1439 SMESH::SMESH_Mesh_var aMesh = createMesh();
1441 char bname[ _MAX_FNAME ];
1442 _splitpath( theFileName, NULL, NULL, bname, NULL );
1443 string aFileName = bname;
1445 string aFileName = basename( const_cast<char *>(theFileName) );
1447 // publish mesh in the study
1448 if ( CanPublishInStudy( aMesh ) ) {
1449 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1450 aStudyBuilder->NewCommand(); // There is a transaction
1451 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1452 aStudyBuilder->CommitCommand();
1453 if ( !aSO->_is_nil() ) {
1454 // Update Python script
1455 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1456 << theFileName << "', "
1457 << theMakeRequiredGroups << " )";
1460 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1462 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1463 aServant->GetImpl().GetMeshDS()->Modified();
1464 return aMesh._retn();
1468 //=============================================================================
1470 * SMESH_Gen_i::IsReadyToCompute
1472 * Returns true if mesh contains enough data to be computed
1474 //=============================================================================
1476 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1477 GEOM::GEOM_Object_ptr theShapeObject )
1478 throw ( SALOME::SALOME_Exception )
1480 Unexpect aCatch(SALOME_SalomeException);
1481 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1483 if ( CORBA::is_nil( theShapeObject ) )
1484 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1485 SALOME::BAD_PARAM );
1487 if ( CORBA::is_nil( theMesh ) )
1488 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1489 SALOME::BAD_PARAM );
1493 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1494 ASSERT( meshServant );
1495 if ( meshServant ) {
1496 // get local TopoDS_Shape
1497 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1498 // call implementation
1499 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1500 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1503 catch ( SALOME_Exception& S_ex ) {
1504 INFOS( "catch exception "<< S_ex.what() );
1509 //================================================================================
1511 * \brief Find SObject for an algo
1513 //================================================================================
1515 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1518 SALOMEDS::Study_var aStudy = getStudyServant();
1519 if ( !aStudy->_is_nil() ) {
1520 // find algo in the study
1521 CORBA::String_var compDataType = ComponentDataType();
1522 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1523 if ( !father->_is_nil() ) {
1524 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1525 for ( ; itBig->More(); itBig->Next() ) {
1526 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1527 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1528 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1529 for ( ; algoIt->More(); algoIt->Next() ) {
1530 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1531 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1532 if ( !CORBA::is_nil( algoIOR )) {
1533 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1534 if ( impl && impl->GetImpl() == algo )
1535 return algoSO._retn();
1537 } // loop on algo SO's
1540 } // SMESH component iterator
1544 return SALOMEDS::SObject::_nil();
1547 //================================================================================
1549 * \brief Return errors of mesh computation
1551 //================================================================================
1553 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1554 GEOM::GEOM_Object_ptr theSubObject )
1555 throw ( SALOME::SALOME_Exception )
1557 Unexpect aCatch(SALOME_SalomeException);
1558 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1560 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1561 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1563 if ( CORBA::is_nil( theMesh ) )
1564 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1566 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1568 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1571 if(theMesh->HasShapeToMesh())
1572 shape = GeomObjectToShape( theSubObject );
1574 shape = SMESH_Mesh::PseudoShape();
1576 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1578 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1581 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1582 const bool includeSelf = true, complexShapeFirst = true;
1583 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1585 while ( smIt->more() )
1588 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1590 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1591 if ( error && !error->IsOK() )
1593 if ( !( error->myAlgo ) &&
1594 !( error->myAlgo = sm->GetAlgo() ))
1596 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1597 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1598 errStruct.comment = error->myComment.c_str();
1599 errStruct.subShapeID = sm->GetId();
1600 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1601 if ( !algoSO->_is_nil() ) {
1602 CORBA::String_var algoName = algoSO->GetName();
1603 errStruct.algoName = algoName;
1606 errStruct.algoName = error->myAlgo->GetName();
1608 errStruct.hasBadMesh = !error->myBadElements.empty();
1611 error_array->length( nbErr );
1614 catch ( SALOME_Exception& S_ex ) {
1615 INFOS( "catch exception "<< S_ex.what() );
1618 return error_array._retn();
1621 //================================================================================
1623 * \brief Return mesh elements preventing computation of a subshape
1625 //================================================================================
1627 SMESH::MeshPreviewStruct*
1628 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1629 CORBA::Short theSubShapeID )
1630 throw ( SALOME::SALOME_Exception )
1632 Unexpect aCatch(SALOME_SalomeException);
1633 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1635 if ( CORBA::is_nil( theMesh ) )
1636 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1638 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1641 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1643 // mesh implementation
1644 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1645 // submesh by subshape id
1646 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1649 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1650 if ( error && !error->myBadElements.empty())
1652 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1653 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1655 // get nodes of elements and count elements
1656 TNode2LocalIDMap mapNode2LocalID;
1657 list< TNodeLocalID > connectivity;
1658 int i, nbElements = 0, nbConnNodes = 0;
1660 list<const SMDS_MeshElement*>::iterator elemIt = error->myBadElements.begin();
1661 list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1662 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1664 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1665 while ( nIt->more() )
1666 connectivity.push_back
1667 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1669 // fill node coords and assign local ids to the nodes
1670 int nbNodes = mapNode2LocalID.size();
1671 result->nodesXYZ.length( nbNodes );
1672 TNodeLocalID node2ID = mapNode2LocalID.begin();
1673 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1674 node2ID->second = i;
1675 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1676 result->nodesXYZ[i].x = node->X();
1677 result->nodesXYZ[i].y = node->Y();
1678 result->nodesXYZ[i].z = node->Z();
1680 // fill connectivity
1681 result->elementConnectivities.length( nbConnNodes );
1682 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1683 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1684 result->elementConnectivities[i] = (*connIt)->second;
1686 // fill element types
1687 result->elementTypes.length( nbElements );
1688 for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1690 const SMDS_MeshElement* elem = *elemIt;
1691 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1692 result->elementTypes[i].isPoly = elem->IsPoly();
1693 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1699 catch ( SALOME_Exception& S_ex ) {
1700 INFOS( "catch exception "<< S_ex.what() );
1703 return result._retn();
1706 //================================================================================
1708 * \brief Create a group of elements preventing computation of a sub-shape
1710 //================================================================================
1712 SMESH::ListOfGroups*
1713 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1714 CORBA::Short theSubShapeID,
1715 const char* theGroupName )
1716 throw ( SALOME::SALOME_Exception )
1718 Unexpect aCatch(SALOME_SalomeException);
1720 SMESH::ListOfGroups_var groups;
1722 if ( CORBA::is_nil( theMesh ) )
1723 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1726 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1728 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1729 TPythonDump() << groups << " = " << this
1730 << ".MakeGroupsOfBadInputElements( "
1731 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1734 catch ( SALOME_Exception& S_ex ) {
1735 INFOS( "catch exception "<< S_ex.what() );
1737 return groups._retn();
1740 //================================================================================
1742 * \brief Returns errors of hypotheses definintion
1743 * \param theMesh - the mesh
1744 * \param theSubObject - the main or sub- shape
1745 * \retval SMESH::algo_error_array* - sequence of errors
1747 //================================================================================
1749 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1750 GEOM::GEOM_Object_ptr theSubObject )
1751 throw ( SALOME::SALOME_Exception )
1753 Unexpect aCatch(SALOME_SalomeException);
1754 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1756 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1757 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1759 if ( CORBA::is_nil( theMesh ) )
1760 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1762 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1764 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1765 ASSERT( meshServant );
1766 if ( meshServant ) {
1767 TopoDS_Shape myLocShape;
1768 if(theMesh->HasShapeToMesh())
1769 myLocShape = GeomObjectToShape( theSubObject );
1771 myLocShape = SMESH_Mesh::PseudoShape();
1773 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1774 list< ::SMESH_Gen::TAlgoStateError > error_list;
1775 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1776 // call ::SMESH_Gen::GetAlgoState()
1777 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1778 error_array->length( error_list.size() );
1780 for ( error = error_list.begin(); error != error_list.end(); ++error )
1782 // fill AlgoStateError structure
1783 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1784 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1785 errStruct.algoDim = error->_algoDim;
1786 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1787 errStruct.algoName = "";
1788 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1789 if ( !algoSO->_is_nil() ) {
1790 CORBA::String_var algoName = algoSO->GetName();
1791 errStruct.algoName = algoName.in();
1796 catch ( SALOME_Exception& S_ex ) {
1797 INFOS( "catch exception "<< S_ex.what() );
1799 return error_array._retn();
1802 //=============================================================================
1804 * SMESH_Gen_i::GetSubShapesId
1806 * Get sub-shapes unique ID's list
1808 //=============================================================================
1811 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1812 const SMESH::object_array& theListOfSubShapeObject )
1813 throw ( SALOME::SALOME_Exception )
1815 Unexpect aCatch(SALOME_SalomeException);
1816 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1818 SMESH::long_array_var shapesId = new SMESH::long_array;
1821 if ( CORBA::is_nil( theMainShapeObject ) )
1822 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1826 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1827 TopTools_IndexedMapOfShape myIndexToShape;
1828 TopExp::MapShapes(myMainShape,myIndexToShape);
1830 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1832 GEOM::GEOM_Object_var aShapeObject
1833 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1834 if ( CORBA::is_nil( aShapeObject ) )
1835 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1836 SALOME::BAD_PARAM );
1838 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1839 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1841 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1842 setId.insert(myIndexToShape.FindIndex(F));
1843 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1845 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1847 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1848 setId.insert(myIndexToShape.FindIndex(E));
1849 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1851 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1853 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1854 setId.insert(myIndexToShape.FindIndex(V));
1855 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1858 shapesId->length(setId.size());
1859 set<int>::iterator iind;
1861 for (iind = setId.begin(); iind != setId.end(); iind++)
1863 if(MYDEBUG) SCRUTE((*iind));
1864 shapesId[i] = (*iind);
1865 if(MYDEBUG) SCRUTE(shapesId[i]);
1869 catch (SALOME_Exception& S_ex)
1871 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1874 return shapesId._retn();
1877 //=============================================================================
1879 * SMESH_Gen_i::Compute
1881 * Compute mesh on a shape
1883 //=============================================================================
1885 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1886 GEOM::GEOM_Object_ptr theShapeObject )
1887 throw ( SALOME::SALOME_Exception )
1890 Unexpect aCatch(SALOME_SalomeException);
1891 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1893 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1894 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1895 SALOME::BAD_PARAM );
1897 if ( CORBA::is_nil( theMesh ) )
1898 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1899 SALOME::BAD_PARAM );
1901 // Update Python script
1902 TPythonDump() << "isDone = " << this << ".Compute( "
1903 << theMesh << ", " << theShapeObject << ")";
1907 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1908 ASSERT( meshServant );
1909 if ( meshServant ) {
1910 meshServant->Load();
1911 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1912 meshServant->CheckGeomModif();
1913 // get local TopoDS_Shape
1914 TopoDS_Shape myLocShape;
1915 if(theMesh->HasShapeToMesh())
1916 myLocShape = GeomObjectToShape( theShapeObject );
1918 myLocShape = SMESH_Mesh::PseudoShape();
1919 // call implementation compute
1920 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1921 myGen.PrepareCompute( myLocMesh, myLocShape );
1922 int how = ::SMESH_Gen::COMPACT_MESH;
1923 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1924 how |= ::SMESH_Gen::SHAPE_ONLY;
1925 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1926 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1927 myLocMesh.GetMeshDS()->Modified();
1931 catch ( std::bad_alloc ) {
1932 INFOS( "Compute(): lack of memory" );
1934 catch ( SALOME_Exception& S_ex ) {
1935 INFOS( "Compute(): catch exception "<< S_ex.what() );
1938 INFOS( "Compute(): unknown exception " );
1943 //=============================================================================
1945 * SMESH_Gen_i::CancelCompute
1947 * Cancel Compute mesh on a shape
1949 //=============================================================================
1951 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1952 GEOM::GEOM_Object_ptr theShapeObject )
1954 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1955 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1956 TopoDS_Shape myLocShape;
1957 if(theMesh->HasShapeToMesh())
1958 myLocShape = GeomObjectToShape( theShapeObject );
1960 myLocShape = SMESH_Mesh::PseudoShape();
1961 myGen.CancelCompute( myLocMesh, myLocShape);
1964 //=============================================================================
1966 * SMESH_Gen_i::Precompute
1968 * Compute mesh as preview till indicated dimension on shape
1970 //=============================================================================
1972 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1973 GEOM::GEOM_Object_ptr theShapeObject,
1974 SMESH::Dimension theDimension,
1975 SMESH::long_array& theShapesId)
1976 throw ( SALOME::SALOME_Exception )
1978 Unexpect aCatch(SALOME_SalomeException);
1979 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
1981 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1982 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1983 SALOME::BAD_PARAM );
1985 if ( CORBA::is_nil( theMesh ) )
1986 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1987 SALOME::BAD_PARAM );
1989 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1992 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1993 meshServant->Load();
1994 ASSERT( meshServant );
1995 if ( meshServant ) {
1996 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1997 meshServant->CheckGeomModif();
1998 // get local TopoDS_Shape
1999 TopoDS_Shape myLocShape;
2000 if(theMesh->HasShapeToMesh())
2001 myLocShape = GeomObjectToShape( theShapeObject );
2003 return result._retn();;
2005 // call implementation compute
2006 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2008 ::MeshDimension aDim = (MeshDimension)theDimension;
2009 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2011 int nbShapeId = shapeIds.size();
2012 theShapesId.length( nbShapeId );
2013 // iterates on shapes and collect mesh entities into mesh preview
2014 TSetOfInt::const_iterator idIt = shapeIds.begin();
2015 TSetOfInt::const_iterator idEnd = shapeIds.end();
2016 std::map< int, int > mapOfShIdNb;
2017 std::set< SMESH_TLink > setOfEdge;
2018 std::list< SMDSAbs_ElementType > listOfElemType;
2019 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2020 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2021 TNode2LocalIDMap mapNode2LocalID;
2022 list< TNodeLocalID > connectivity;
2023 int i, nbConnNodes = 0;
2024 std::set< const SMESH_subMesh* > setOfVSubMesh;
2025 // iterates on shapes
2026 for ( ; idIt != idEnd; idIt++ )
2028 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2030 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2031 if ( !sm || !sm->IsMeshComputed() )
2034 const TopoDS_Shape& aSh = sm->GetSubShape();
2035 const int shDim = myGen.GetShapeDim( aSh );
2036 if ( shDim < 1 || shDim > theDimension )
2039 mapOfShIdNb[ *idIt ] = 0;
2040 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2042 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2043 if ( !smDS ) continue;
2045 if ( theDimension == SMESH::DIM_2D )
2047 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2048 while ( faceIt->more() )
2050 const SMDS_MeshElement* face = faceIt->next();
2051 int aNbNode = face->NbNodes();
2053 aNbNode /= 2; // do not take into account additional middle nodes
2055 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2056 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2058 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2059 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2061 listOfElemType.push_back( SMDSAbs_Edge );
2062 connectivity.push_back
2063 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2064 connectivity.push_back
2065 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2071 else if ( theDimension == SMESH::DIM_1D )
2073 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2074 while ( nodeIt->more() )
2076 listOfElemType.push_back( SMDSAbs_Node );
2077 connectivity.push_back
2078 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2080 // add corner nodes by first vertex from edge
2081 SMESH_subMeshIteratorPtr edgeSmIt =
2082 sm->getDependsOnIterator(/*includeSelf*/false,
2083 /*complexShapeFirst*/false);
2084 while ( edgeSmIt->more() )
2086 SMESH_subMesh* vertexSM = edgeSmIt->next();
2087 // check that vertex is not already treated
2088 if ( !setOfVSubMesh.insert( vertexSM ).second )
2090 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2093 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2094 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2095 while ( nodeIt->more() )
2097 listOfElemType.push_back( SMDSAbs_Node );
2098 connectivity.push_back
2099 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2105 // fill node coords and assign local ids to the nodes
2106 int nbNodes = mapNode2LocalID.size();
2107 result->nodesXYZ.length( nbNodes );
2108 TNodeLocalID node2ID = mapNode2LocalID.begin();
2109 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2110 node2ID->second = i;
2111 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2112 result->nodesXYZ[i].x = node->X();
2113 result->nodesXYZ[i].y = node->Y();
2114 result->nodesXYZ[i].z = node->Z();
2116 // fill connectivity
2117 result->elementConnectivities.length( nbConnNodes );
2118 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2119 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2120 result->elementConnectivities[i] = (*connIt)->second;
2123 // fill element types
2124 result->elementTypes.length( listOfElemType.size() );
2125 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2126 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2127 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2129 SMDSAbs_ElementType elemType = *typeIt;
2130 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2131 result->elementTypes[i].isPoly = false;
2132 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2135 // correct number of shapes
2136 theShapesId.length( mapOfShIdNb.size() );
2140 catch ( std::bad_alloc ) {
2141 INFOS( "Precompute(): lack of memory" );
2143 catch ( SALOME_Exception& S_ex ) {
2144 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2147 INFOS( "Precompute(): unknown exception " );
2149 return result._retn();
2153 //=============================================================================
2155 * SMESH_Gen_i::Evaluate
2157 * Evaluate mesh on a shape
2159 //=============================================================================
2161 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2162 GEOM::GEOM_Object_ptr theShapeObject)
2163 // SMESH::long_array& theNbElems)
2164 throw ( SALOME::SALOME_Exception )
2166 Unexpect aCatch(SALOME_SalomeException);
2167 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2169 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2170 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2171 SALOME::BAD_PARAM );
2173 if ( CORBA::is_nil( theMesh ) )
2174 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2175 SALOME::BAD_PARAM );
2177 SMESH::long_array_var nbels = new SMESH::long_array;
2178 nbels->length(SMESH::Entity_Last);
2179 int i = SMESH::Entity_Node;
2180 for (; i < SMESH::Entity_Last; i++)
2183 // Update Python script
2184 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2185 << theMesh << ", " << theShapeObject << ")";
2189 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2190 ASSERT( meshServant );
2191 if ( meshServant ) {
2192 meshServant->Load();
2193 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2194 meshServant->CheckGeomModif();
2195 // get local TopoDS_Shape
2196 TopoDS_Shape myLocShape;
2197 if(theMesh->HasShapeToMesh())
2198 myLocShape = GeomObjectToShape( theShapeObject );
2200 myLocShape = SMESH_Mesh::PseudoShape();
2201 // call implementation compute
2202 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2203 MapShapeNbElems aResMap;
2204 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2205 MapShapeNbElemsItr anIt = aResMap.begin();
2206 for(; anIt!=aResMap.end(); anIt++) {
2207 const vector<int>& aVec = (*anIt).second;
2208 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2209 int nbElem = aVec[i];
2210 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2212 SMESH_subMesh* sm = anIt->first;
2213 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2214 const SMESH_Algo* algo = sm->GetAlgo();
2215 if ( (algo && !error.get()) || error->IsOK() )
2216 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2220 nbels[i] += aVec[i];
2224 return nbels._retn();
2227 catch ( std::bad_alloc ) {
2228 INFOS( "Evaluate(): lack of memory" );
2230 catch ( SALOME_Exception& S_ex ) {
2231 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2234 INFOS( "Evaluate(): unknown exception " );
2237 return nbels._retn();
2240 //================================================================================
2242 * \brief Return geometrical object the given element is built on
2243 * \param theMesh - the mesh the element is in
2244 * \param theElementID - the element ID
2245 * \param theGeomName - the name of the result geom object if it is not yet published
2246 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2248 //================================================================================
2250 GEOM::GEOM_Object_ptr
2251 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2252 CORBA::Long theElementID,
2253 const char* theGeomName)
2254 throw ( SALOME::SALOME_Exception )
2256 Unexpect aCatch(SALOME_SalomeException);
2258 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2259 if ( !geom->_is_nil() ) {
2260 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2261 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2263 // try to find the corresponding SObject
2264 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2265 if ( SObj->_is_nil() ) // submesh can be not found even if published
2267 // try to find published submesh
2268 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2269 if ( !geom->IsMainShape() && list->length() == 1 ) {
2270 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2271 SALOMEDS::ChildIterator_wrap it;
2272 if ( !mainSO->_is_nil() ) {
2273 it = getStudyServant()->NewChildIterator( mainSO );
2275 if ( !it->_is_nil() ) {
2276 for ( it->InitEx(true); it->More(); it->Next() ) {
2277 SALOMEDS::SObject_wrap so = it->Value();
2278 CORBA::Object_var obj = SObjectToObject( so );
2279 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2280 if ( !subGeom->_is_nil() ) {
2281 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2282 if ( subList->length() == 1 && list[0] == subList[0] ) {
2292 if ( SObj->_is_nil() ) // publish a new subshape
2293 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2295 // return only published geometry
2296 if ( !SObj->_is_nil() ) {
2297 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2298 CORBA::Object_var obj = SObjectToObject( SObj );
2299 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2303 return GEOM::GEOM_Object::_nil();
2306 //================================================================================
2308 * \brief Return geometrical object the given element is built on.
2309 * \param theMesh - the mesh the element is in
2310 * \param theElementID - the element ID
2311 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2313 //================================================================================
2315 GEOM::GEOM_Object_ptr
2316 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2317 CORBA::Long theElementID)
2318 throw ( SALOME::SALOME_Exception )
2320 Unexpect aCatch(SALOME_SalomeException);
2321 if ( CORBA::is_nil( theMesh ) )
2322 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2324 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2325 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2327 // get a core mesh DS
2328 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2329 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2331 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2332 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2333 // find the element in mesh
2334 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2335 // find a shape id by the element
2336 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2337 // get a geom object by the shape id
2338 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2339 if ( geom->_is_nil() ) {
2340 // try to find a published sub-shape
2341 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2342 SALOMEDS::ChildIterator_wrap it;
2343 if ( !mainSO->_is_nil() ) {
2344 it = getStudyServant()->NewChildIterator( mainSO );
2346 if ( !it->_is_nil() ) {
2347 for ( it->InitEx(true); it->More(); it->Next() ) {
2348 SALOMEDS::SObject_wrap so = it->Value();
2349 CORBA::Object_var obj = SObjectToObject( so );
2350 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2351 if ( !subGeom->_is_nil() ) {
2352 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2353 if ( subList->length() == 1 && shapeID == subList[0] ) {
2361 if ( geom->_is_nil() ) {
2363 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2364 if ( !op->_is_nil() )
2365 geom = op->GetSubShape( mainShape, shapeID );
2370 if ( !geom->_is_nil() ) {
2371 GeomObjectToShape( geom ); // let geom client remember the found shape
2372 return geom._retn();
2377 return GEOM::GEOM_Object::_nil();
2380 //================================================================================
2382 * SMESH_Gen_i::Concatenate
2384 * Concatenate the given meshes into one mesh
2386 //================================================================================
2388 SMESH::SMESH_Mesh_ptr
2389 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2390 CORBA::Boolean theUniteIdenticalGroups,
2391 CORBA::Boolean theMergeNodesAndElements,
2392 CORBA::Double theMergeTolerance)
2393 throw ( SALOME::SALOME_Exception )
2395 return ConcatenateCommon(theMeshesArray,
2396 theUniteIdenticalGroups,
2397 theMergeNodesAndElements,
2402 //================================================================================
2404 * SMESH_Gen_i::ConcatenateWithGroups
2406 * Concatenate the given meshes into one mesh
2407 * Create the groups of all elements from initial meshes
2409 //================================================================================
2411 SMESH::SMESH_Mesh_ptr
2412 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2413 CORBA::Boolean theUniteIdenticalGroups,
2414 CORBA::Boolean theMergeNodesAndElements,
2415 CORBA::Double theMergeTolerance)
2416 throw ( SALOME::SALOME_Exception )
2418 return ConcatenateCommon(theMeshesArray,
2419 theUniteIdenticalGroups,
2420 theMergeNodesAndElements,
2425 //================================================================================
2427 * SMESH_Gen_i::ConcatenateCommon
2429 * Concatenate the given meshes into one mesh
2431 //================================================================================
2433 SMESH::SMESH_Mesh_ptr
2434 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2435 CORBA::Boolean theUniteIdenticalGroups,
2436 CORBA::Boolean theMergeNodesAndElements,
2437 CORBA::Double theMergeTolerance,
2438 CORBA::Boolean theCommonGroups)
2439 throw ( SALOME::SALOME_Exception )
2441 typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
2442 typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
2444 TPythonDump* pPythonDump = new TPythonDump;
2445 TPythonDump& aPythonDump = *pPythonDump; // prevent dump of called methods
2448 SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
2450 if ( aNewMesh->_is_nil() )
2451 return aNewMesh._retn();
2453 SMESH_Mesh_i* aNewImpl = SMESH::DownCast<SMESH_Mesh_i*>( aNewMesh );
2455 return aNewMesh._retn();
2457 ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
2458 SMESHDS_Mesh* aNewMeshDS = aLocMesh.GetMeshDS();
2460 TGroupsMap aGroupsMap;
2461 TListOfNewGroups aListOfNewGroups;
2462 ::SMESH_MeshEditor aNewEditor(&aLocMesh);
2463 SMESH::ListOfGroups_var aListOfGroups;
2465 ::SMESH_MeshEditor::ElemFeatures elemType;
2466 std::vector<const SMDS_MeshNode*> aNodesArray;
2468 // loop on sub-meshes
2469 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++)
2471 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2472 SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i]->GetMesh();
2473 if ( anInitMesh->_is_nil() ) continue;
2474 SMESH_Mesh_i* anInitImpl = SMESH::DownCast<SMESH_Mesh_i*>( anInitMesh );
2475 if ( !anInitImpl ) continue;
2478 //::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
2479 //SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
2481 // remember nb of elements before filling in
2482 SMESH::long_array_var prevState = aNewMesh->GetNbElementsByType();
2484 typedef std::map<const SMDS_MeshElement*, const SMDS_MeshElement*, TIDCompare > TEEMap;
2485 TEEMap elemsMap, nodesMap;
2487 // loop on elements of a sub-mesh
2488 SMDS_ElemIteratorPtr itElems = anInitImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2489 const SMDS_MeshElement* anElem;
2490 const SMDS_MeshElement* aNewElem;
2491 const SMDS_MeshNode* aNode;
2492 const SMDS_MeshNode* aNewNode;
2495 while ( itElems->more() )
2497 anElem = itElems->next();
2498 anElemNbNodes = anElem->NbNodes();
2499 aNodesArray.resize( anElemNbNodes );
2501 // loop on nodes of an element
2502 SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
2503 for ( int k = 0; itNodes->more(); k++)
2505 aNode = static_cast<const SMDS_MeshNode*>( itNodes->next() );
2506 TEEMap::iterator n2nnIt = nodesMap.find( aNode );
2507 if ( n2nnIt == nodesMap.end() )
2509 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2510 nodesMap.insert( make_pair( aNode, aNewNode ));
2514 aNewNode = static_cast<const SMDS_MeshNode*>( n2nnIt->second );
2516 aNodesArray[k] = aNewNode;
2519 // creates a corresponding element on existent nodes in new mesh
2520 if ( anElem->GetType() == SMDSAbs_Node )
2524 aNewEditor.AddElement( aNodesArray, elemType.Init( anElem, /*basicOnly=*/false ));
2527 elemsMap.insert( make_pair( anElem, aNewElem ));
2531 aNewEditor.ClearLastCreated(); // forget the history
2534 // create groups of just added elements
2535 SMESH::SMESH_Group_var aNewGroup;
2536 SMESH::ElementType aGroupType;
2537 if ( theCommonGroups )
2539 SMESH::long_array_var curState = aNewMesh->GetNbElementsByType();
2541 for( aGroupType = SMESH::NODE;
2542 aGroupType < SMESH::NB_ELEMENT_TYPES;
2543 aGroupType = (SMESH::ElementType)( aGroupType + 1 ))
2545 if ( curState[ aGroupType ] <= prevState[ aGroupType ])
2548 // make a group name
2549 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2550 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2551 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2552 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2554 string groupName = "Gr";
2555 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( theMeshesArray[i] );
2557 CORBA::String_var name = aMeshSObj->GetName();
2561 groupName += typeNames[ aGroupType ];
2563 // make and fill a group
2564 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2565 aNewGroup = aNewImpl->CreateGroup( aGroupType, groupName.c_str() );
2566 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( aNewGroup ))
2568 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2570 TEEMap::iterator e2neIt = e2neMap.begin();
2571 for ( ; e2neIt != e2neMap.end(); ++e2neIt )
2573 aNewElem = e2neIt->second;
2574 if ( aNewElem->GetType() == grpDS->GetType() )
2576 grpDS->Add( aNewElem );
2578 if ( prevState[ aGroupType ]++ >= curState[ aGroupType ] )
2584 aListOfNewGroups.clear();
2585 aListOfNewGroups.push_back(aNewGroup);
2586 aGroupsMap.insert(make_pair( make_pair(groupName, aGroupType), aListOfNewGroups ));
2590 if ( SMESH_Mesh_i* anSrcImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2592 // copy orphan nodes
2593 if ( anSrcImpl->NbNodes() > (int)nodesMap.size() )
2595 SMDS_ElemIteratorPtr itNodes = anInitImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2596 while ( itNodes->more() )
2598 const SMDS_MeshNode* aNode = static_cast< const SMDS_MeshNode* >( itNodes->next() );
2599 if ( aNode->NbInverseElements() == 0 )
2601 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2602 nodesMap.insert( make_pair( aNode, aNewNode ));
2609 SMESH::SMESH_GroupBase_ptr aGroup;
2610 CORBA::String_var aGroupName;
2611 SMESH::long_array_var anNewIDs = new SMESH::long_array();
2613 // loop on groups of a source mesh
2614 aListOfGroups = anSrcImpl->GetGroups();
2615 for ( CORBA::ULong iG = 0; iG < aListOfGroups->length(); iG++ )
2617 aGroup = aListOfGroups[iG];
2618 aGroupType = aGroup->GetType();
2619 aGroupName = aGroup->GetName();
2620 string aName = aGroupName.in();
2622 // convert a list of IDs
2623 anNewIDs->length( aGroup->Size() );
2624 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2625 SMDS_ElemIteratorPtr itGrElems = anSrcImpl->GetElements( aGroup, SMESH::ALL );
2627 while ( itGrElems->more() )
2629 anElem = itGrElems->next();
2630 TEEMap::iterator e2neIt = e2neMap.find( anElem );
2631 if ( e2neIt != e2neMap.end() )
2632 anNewIDs[ iElem++ ] = e2neIt->second->GetID();
2634 anNewIDs->length( iElem );
2636 // check a current group name and type don't have identical ones in final mesh
2637 aListOfNewGroups.clear();
2638 TGroupsMap::iterator anIter = aGroupsMap.find( make_pair( aName, aGroupType ));
2639 if ( anIter == aGroupsMap.end() ) {
2640 // add a new group in the mesh
2641 aNewGroup = aNewImpl->CreateGroup( aGroupType, aGroupName.in() );
2642 // add elements into new group
2643 aNewGroup->Add( anNewIDs );
2645 aListOfNewGroups.push_back(aNewGroup);
2646 aGroupsMap.insert(make_pair( make_pair(aName, aGroupType), aListOfNewGroups ));
2649 else if ( theUniteIdenticalGroups ) {
2650 // unite identical groups
2651 TListOfNewGroups& aNewGroups = anIter->second;
2652 aNewGroups.front()->Add( anNewIDs );
2656 // rename identical groups
2657 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName.in());
2658 aNewGroup->Add( anNewIDs );
2660 TListOfNewGroups& aNewGroups = anIter->second;
2661 string aNewGroupName;
2662 if (aNewGroups.size() == 1) {
2663 aNewGroupName = aName + "_1";
2664 aNewGroups.front()->SetName(aNewGroupName.c_str());
2666 char aGroupNum[128];
2667 sprintf(aGroupNum, "%u", (unsigned int)aNewGroups.size()+1);
2668 aNewGroupName = aName + "_" + string(aGroupNum);
2669 aNewGroup->SetName(aNewGroupName.c_str());
2670 aNewGroups.push_back(aNewGroup);
2673 } // if an IDSource is a mesh
2676 if (theMergeNodesAndElements) // merge nodes
2678 TIDSortedNodeSet aMeshNodes; // no input nodes
2679 SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
2680 aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes,
2681 /*SeparateCornersAndMedium=*/ false );
2682 aNewEditor.MergeNodes( aGroupsOfNodes );
2684 aNewEditor.MergeEqualElements();
2687 // Update Python script
2688 aPythonDump << aNewMesh << " = " << this << "."
2689 << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" )
2691 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++) {
2692 if (i > 0) aPythonDump << ", ";
2693 aPythonDump << theMeshesArray[i];
2695 aPythonDump << "], ";
2696 aPythonDump << theUniteIdenticalGroups << ", "
2697 << theMergeNodesAndElements << ", "
2698 << TVar( theMergeTolerance ) << ")";
2700 delete pPythonDump; // enable python dump from GetGroups()
2702 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2703 if ( !aNewMesh->_is_nil() )
2705 SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
2708 // IPAL21468 Change icon of compound because it need not be computed.
2709 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( aNewMesh );
2710 SetPixMap( aMeshSObj, "ICON_SMESH_TREE_MESH" );
2713 aNewMeshDS->Modified();
2715 return aNewMesh._retn();
2718 //================================================================================
2720 * \brief Create a mesh by copying a part of another mesh
2721 * \param meshPart - a part of mesh to copy
2722 * \param toCopyGroups - to create in the new mesh groups
2723 * the copied elements belongs to
2724 * \param toKeepIDs - to preserve IDs of the copied elements or not
2725 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2727 //================================================================================
2729 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2730 const char* meshName,
2731 CORBA::Boolean toCopyGroups,
2732 CORBA::Boolean toKeepIDs)
2734 Unexpect aCatch(SALOME_SalomeException);
2736 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2738 // 1. Get source mesh
2740 if ( CORBA::is_nil( meshPart ))
2741 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2743 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2744 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2746 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2748 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2750 // 2. Make a new mesh
2752 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2753 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2755 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2756 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2757 if ( !meshSO->_is_nil() )
2759 SetName( meshSO, meshName, "Mesh" );
2760 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2762 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2763 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2764 ::SMESH_MeshEditor::ElemFeatures elemType;
2766 // 3. Get elements to copy
2768 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2769 TIDSortedElemSet srcElems;
2770 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2771 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2774 srcElemIt = srcMeshDS->elementsIterator();
2775 srcNodeIt = srcMeshDS->nodesIterator();
2779 SMESH::long_array_var ids = meshPart->GetIDs();
2780 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2782 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2783 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2784 srcElems.insert( elem );
2788 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2789 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2790 srcElems.insert( elem );
2792 if ( srcElems.empty() )
2793 return newMesh._retn();
2795 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2796 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2801 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2802 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2803 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2805 const SMDS_MeshNode *nSrc, *nTgt;
2806 vector< const SMDS_MeshNode* > nodes;
2807 while ( srcElemIt->more() )
2809 const SMDS_MeshElement * elem = srcElemIt->next();
2811 nodes.resize( elem->NbNodes());
2812 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2814 for ( iN = 0; nIt->more(); ++iN )
2816 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2817 nTgt = newMeshDS->FindNode( nSrc->GetID());
2819 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2824 for ( iN = 0; nIt->more(); ++iN )
2826 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2827 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2829 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2830 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2834 if ( elem->GetType() != SMDSAbs_Node )
2836 elemType.Init( elem, /*basicOnly=*/false );
2837 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2839 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2840 if ( toCopyGroups && !toKeepIDs )
2841 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2843 } // while ( srcElemIt->more() )
2845 // 4(b). Copy free nodes
2847 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2849 while ( srcNodeIt->more() )
2851 nSrc = srcNodeIt->next();
2852 if ( nSrc->NbInverseElements() == 0 )
2855 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2857 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2864 int nbNewGroups = 0;
2867 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2868 while ( gIt->more() )
2870 SMESH_Group* group = gIt->next();
2871 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2873 // Check group type. We copy nodal groups containing nodes of copied element
2874 SMDSAbs_ElementType groupType = groupDS->GetType();
2875 if ( groupType != SMDSAbs_Node &&
2876 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2877 continue; // group type differs from types of meshPart
2879 // Find copied elements in the group
2880 vector< const SMDS_MeshElement* > groupElems;
2881 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2884 const SMDS_MeshElement* foundElem;
2885 if ( groupType == SMDSAbs_Node )
2887 while ( eIt->more() )
2888 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2889 groupElems.push_back( foundElem );
2893 while ( eIt->more() )
2894 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2895 groupElems.push_back( foundElem );
2900 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2901 if ( e2eMap.empty() ) continue;
2902 int minID = e2eMap.begin()->first->GetID();
2903 int maxID = e2eMap.rbegin()->first->GetID();
2904 TE2EMap::iterator e2e;
2905 while ( eIt->more() && groupElems.size() < e2eMap.size())
2907 const SMDS_MeshElement* e = eIt->next();
2908 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2909 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2910 groupElems.push_back( e2e->second );
2914 if ( !groupElems.empty() )
2916 SMESH::SMESH_Group_var newGroupObj =
2917 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2918 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2920 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2921 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2922 for ( unsigned i = 0; i < groupElems.size(); ++i )
2923 smdsGroup.Add( groupElems[i] );
2931 newMeshDS->Modified();
2933 *pyDump << newMesh << " = " << this
2934 << ".CopyMesh( " << meshPart << ", "
2935 << "'" << meshName << "', "
2936 << toCopyGroups << ", "
2937 << toKeepIDs << ")";
2939 delete pyDump; pyDump = 0; // allow dump in GetGroups()
2941 if ( nbNewGroups > 0 ) // dump created groups
2942 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2944 return newMesh._retn();
2947 //================================================================================
2949 * \brief Get version of MED format being used.
2951 //================================================================================
2953 char* SMESH_Gen_i::GetMEDFileVersion()
2955 MED::TInt majeur, mineur, release;
2956 majeur = mineur = release = 0;
2957 MED::GetVersionRelease(majeur, mineur, release);
2958 std::ostringstream version;
2959 version << majeur << "." << mineur << "." << release;
2960 return CORBA::string_dup( version.str().c_str() );
2963 //================================================================================
2965 * SMESH_Gen_i::GetMEDVersion
2967 * Get MED version of the file by its name
2969 //================================================================================
2970 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
2972 std::string version = MED::GetMEDVersion( theFileName );
2973 return CORBA::string_dup( version.c_str() );
2976 //================================================================================
2978 * SMESH_Gen_i::CheckCompatibility
2980 * Check compatibility of file with MED format being used.
2982 //================================================================================
2983 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
2985 return MED::CheckCompatibility( theFileName );
2988 //================================================================================
2990 * SMESH_Gen_i::GetMeshNames
2992 * Get names of meshes defined in file with the specified name
2994 //================================================================================
2995 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2997 SMESH::string_array_var aResult = new SMESH::string_array();
2998 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
3000 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
3002 aResult->length( aNbMeshes );
3003 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
3004 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
3005 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
3008 return aResult._retn();
3011 //=============================================================================
3015 * Save SMESH module's data
3017 //=============================================================================
3018 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
3022 if (!myStudyContext)
3025 // Store study contents as a set of python commands
3028 SALOMEDS::Study_var aStudy = getStudyServant();
3030 // Declare a byte stream
3031 SALOMEDS::TMPFile_var aStreamFile;
3033 // Obtain a temporary dir
3034 TCollection_AsciiString tmpDir =
3035 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3037 // Create a sequence of files processed
3038 SALOMEDS_Tool::ListOfFiles aFileSeq;
3039 aFileSeq.reserve( NUM_TMP_FILES );
3041 TCollection_AsciiString aStudyName( "" );
3043 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
3045 // Set names of temporary files
3046 TCollection_AsciiString filename =
3047 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
3048 TCollection_AsciiString meshfile =
3049 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
3050 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
3051 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
3052 filename = tmpDir + filename;
3053 meshfile = tmpDir + meshfile;
3056 HDFdataset* aDataset;
3057 HDFgroup* aTopGroup;
3059 HDFgroup* aSubGroup;
3060 HDFgroup* aSubSubGroup;
3061 hdf_size aSize[ 1 ];
3064 //Remove the files if they exist: BugID: 11225
3065 #ifndef WIN32 /* unix functionality */
3066 TCollection_AsciiString cmd("rm -f \"");
3068 TCollection_AsciiString cmd("del /F \"");
3075 system(cmd.ToCString());
3077 // MED writer to be used by storage process
3078 DriverMED_W_SMESHDS_Mesh myWriter;
3079 myWriter.SetFile( meshfile.ToCString() );
3082 // SetStoreName() to groups before storing hypotheses to let them refer to
3083 // groups using "store name", which is "Group <group_persistent_id>"
3085 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
3086 for ( ; itBig->More(); itBig->Next() ) {
3087 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3088 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3089 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3090 if ( !CORBA::is_nil( anObject ) ) {
3091 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3092 if ( !myMesh->_is_nil() ) {
3093 myMesh->Load(); // load from study file if not yet done
3094 TPythonDump pd; // not to dump GetGroups()
3095 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3096 pd << ""; // to avoid optimizing pd out
3097 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
3099 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3102 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3103 int anId = myStudyContext->findId( string( objStr.in() ) );
3105 sprintf( grpName, "Group %d", anId );
3106 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3107 aGrpBaseDS->SetStoreName( grpName );
3117 // ---> create HDF file
3118 aFile = new HDFfile( (char*) filename.ToCString() );
3119 aFile->CreateOnDisk();
3121 // --> iterator for top-level objects
3122 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
3123 for ( ; itBig->More(); itBig->Next() ) {
3124 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3126 // --> hypotheses root branch (only one for the study)
3127 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3128 // create hypotheses root HDF group
3129 aTopGroup = new HDFgroup( "Hypotheses", aFile );
3130 aTopGroup->CreateOnDisk();
3132 // iterator for all hypotheses
3133 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
3134 for ( ; it->More(); it->Next() ) {
3135 SALOMEDS::SObject_wrap mySObject = it->Value();
3136 CORBA::Object_var anObject = SObjectToObject( mySObject );
3137 if ( !CORBA::is_nil( anObject ) ) {
3138 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3139 if ( !myHyp->_is_nil() ) {
3140 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3142 string hypname = string( myHyp->GetName() );
3143 string libname = string( myHyp->GetLibName() );
3145 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3146 // WIN32 and ".so" for X-system) must be deleted
3147 int libname_len = libname.length();
3149 if( libname_len > 4 )
3150 libname.resize( libname_len - 4 );
3152 // PAL17753 (Regression: missing hypothesis in restored study)
3153 // "lib" also should be removed from the beginning
3154 //if( libname_len > 3 )
3155 //libname.resize( libname_len - 3 );
3156 if( libname_len > 6 )
3157 libname = libname.substr( 3, libname_len - 3 - 3 );
3159 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3160 int id = myStudyContext->findId( string( objStr.in() ) );
3161 string hypdata = string( myImpl->SaveTo() );
3163 // for each hypothesis create HDF group basing on its id
3164 char hypGrpName[30];
3165 sprintf( hypGrpName, "Hypothesis %d", id );
3166 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3167 aGroup->CreateOnDisk();
3168 // --> type name of hypothesis
3169 aSize[ 0 ] = hypname.length() + 1;
3170 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3171 aDataset->CreateOnDisk();
3172 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3173 aDataset->CloseOnDisk();
3174 // --> server plugin library name of hypothesis
3175 aSize[ 0 ] = libname.length() + 1;
3176 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3177 aDataset->CreateOnDisk();
3178 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3179 aDataset->CloseOnDisk();
3180 // --> persistent data of hypothesis
3181 aSize[ 0 ] = hypdata.length() + 1;
3182 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3183 aDataset->CreateOnDisk();
3184 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3185 aDataset->CloseOnDisk();
3186 // close hypothesis HDF group
3187 aGroup->CloseOnDisk();
3192 // close hypotheses root HDF group
3193 aTopGroup->CloseOnDisk();
3195 // --> algorithms root branch (only one for the study)
3196 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
3197 // create algorithms root HDF group
3198 aTopGroup = new HDFgroup( "Algorithms", aFile );
3199 aTopGroup->CreateOnDisk();
3201 // iterator for all algorithms
3202 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
3203 for ( ; it->More(); it->Next() ) {
3204 SALOMEDS::SObject_wrap mySObject = it->Value();
3205 CORBA::Object_var anObject = SObjectToObject( mySObject );
3206 if ( !CORBA::is_nil( anObject ) ) {
3207 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3208 if ( !myHyp->_is_nil() ) {
3209 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3211 string hypname = string( myHyp->GetName() );
3212 string libname = string( myHyp->GetLibName() );
3214 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3215 // WIN32 and ".so" for X-system) must be deleted
3216 int libname_len = libname.length();
3218 if( libname_len > 4 )
3219 libname.resize( libname_len - 4 );
3221 // PAL17753 (Regression: missing hypothesis in restored study)
3222 // "lib" also should be removed from the beginning
3223 //if( libname_len > 3 )
3224 //libname.resize( libname_len - 3 );
3225 if( libname_len > 6 )
3226 libname = libname.substr( 3, libname_len - 3 - 3 );
3228 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3229 int id = myStudyContext->findId( string( objStr.in() ) );
3230 string hypdata = string( myImpl->SaveTo() );
3232 // for each algorithm create HDF group basing on its id
3233 char hypGrpName[30];
3234 sprintf( hypGrpName, "Algorithm %d", id );
3235 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3236 aGroup->CreateOnDisk();
3237 // --> type name of algorithm
3238 aSize[0] = hypname.length() + 1;
3239 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3240 aDataset->CreateOnDisk();
3241 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3242 aDataset->CloseOnDisk();
3243 // --> server plugin library name of hypothesis
3244 aSize[0] = libname.length() + 1;
3245 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3246 aDataset->CreateOnDisk();
3247 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3248 aDataset->CloseOnDisk();
3249 // --> persistent data of algorithm
3250 aSize[0] = hypdata.length() + 1;
3251 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3252 aDataset->CreateOnDisk();
3253 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3254 aDataset->CloseOnDisk();
3255 // close algorithm HDF group
3256 aGroup->CloseOnDisk();
3261 // close algorithms root HDF group
3262 aTopGroup->CloseOnDisk();
3264 // --> mesh objects roots branches
3265 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3266 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3267 if ( !CORBA::is_nil( anObject ) ) {
3268 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3269 if ( !myMesh->_is_nil() ) {
3270 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3272 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3273 int id = myStudyContext->findId( string( objStr.in() ) );
3274 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3275 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3276 bool hasShape = myLocMesh.HasShapeToMesh();
3278 // for each mesh open the HDF group basing on its id
3279 char meshGrpName[ 30 ];
3280 sprintf( meshGrpName, "Mesh %d", id );
3281 aTopGroup = new HDFgroup( meshGrpName, aFile );
3282 aTopGroup->CreateOnDisk();
3284 // --> put dataset to hdf file which is a flag that mesh has data
3285 string strHasData = "0";
3286 // check if the mesh is not empty
3287 if ( mySMESHDSMesh->NbNodes() > 0 ) {
3288 // write mesh data to med file
3289 myWriter.SetMesh( mySMESHDSMesh );
3290 myWriter.SetMeshId( id );
3293 aSize[ 0 ] = strHasData.length() + 1;
3294 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3295 aDataset->CreateOnDisk();
3296 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3297 aDataset->CloseOnDisk();
3300 // for each mesh open the HDF group basing on its auto color parameter
3301 char meshAutoColorName[ 30 ];
3302 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3304 anAutoColor[0] = myImpl->GetAutoColor();
3306 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3307 aDataset->CreateOnDisk();
3308 aDataset->WriteOnDisk( anAutoColor );
3309 aDataset->CloseOnDisk();
3311 // issue 0020693. Store _isModified flag
3312 int isModified = myLocMesh.GetIsModified();
3314 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3315 aDataset->CreateOnDisk();
3316 aDataset->WriteOnDisk( &isModified );
3317 aDataset->CloseOnDisk();
3319 // issue 20918. Store Persistent Id of SMESHDS_Mesh
3320 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3322 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3323 aDataset->CreateOnDisk();
3324 aDataset->WriteOnDisk( &meshPersistentId );
3325 aDataset->CloseOnDisk();
3327 // write reference on a shape if exists
3328 SALOMEDS::SObject_wrap myRef;
3329 bool shapeRefFound = false;
3330 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
3332 SALOMEDS::SObject_wrap myShape;
3333 bool ok = myRef->ReferencedObject( myShape.inout() );
3335 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
3336 string myRefOnObject = myShape->GetID();
3337 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
3338 aSize[ 0 ] = myRefOnObject.length() + 1;
3339 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3340 aDataset->CreateOnDisk();
3341 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3342 aDataset->CloseOnDisk();
3347 // write applied hypotheses if exist
3348 SALOMEDS::SObject_wrap myHypBranch;
3349 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
3350 if ( found && !shapeRefFound && hasShape) { // remove applied hyps
3351 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3353 if ( found && (shapeRefFound || !hasShape) ) {
3354 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3355 aGroup->CreateOnDisk();
3357 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
3359 for ( ; it->More(); it->Next() ) {
3360 SALOMEDS::SObject_wrap mySObject = it->Value();
3361 SALOMEDS::SObject_wrap myRefOnHyp;
3362 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
3364 // san - it is impossible to recover applied hypotheses
3365 // using their entries within Load() method,
3366 // for there are no AttributeIORs in the study when Load() is working.
3367 // Hence, it is better to store persistent IDs of hypotheses as references to them
3369 //string myRefOnObject = myRefOnHyp->GetID();
3370 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3371 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3372 int id = myStudyContext->findId( string( objStr.in() ) );
3373 //if ( myRefOnObject.length() > 0 ) {
3374 //aSize[ 0 ] = myRefOnObject.length() + 1;
3375 char hypName[ 30 ], hypId[ 30 ];
3376 sprintf( hypName, "Hyp %d", ++hypNb );
3377 sprintf( hypId, "%d", id );
3378 aSize[ 0 ] = strlen( hypId ) + 1;
3379 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3380 aDataset->CreateOnDisk();
3381 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3382 aDataset->WriteOnDisk( hypId );
3383 aDataset->CloseOnDisk();
3387 aGroup->CloseOnDisk();
3390 // write applied algorithms if exist
3391 SALOMEDS::SObject_wrap myAlgoBranch;
3392 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3393 myAlgoBranch.inout() );
3394 if ( found && !shapeRefFound && hasShape) { // remove applied algos
3395 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3397 if ( found && (shapeRefFound || !hasShape)) {
3398 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3399 aGroup->CreateOnDisk();
3401 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
3403 for ( ; it->More(); it->Next() ) {
3404 SALOMEDS::SObject_wrap mySObject = it->Value();
3405 SALOMEDS::SObject_wrap myRefOnAlgo;
3406 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
3408 // san - it is impossible to recover applied algorithms
3409 // using their entries within Load() method,
3410 // for there are no AttributeIORs in the study when Load() is working.
3411 // Hence, it is better to store persistent IDs of algorithms as references to them
3413 //string myRefOnObject = myRefOnAlgo->GetID();
3414 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3415 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3416 int id = myStudyContext->findId( string( objStr.in() ) );
3417 //if ( myRefOnObject.length() > 0 ) {
3418 //aSize[ 0 ] = myRefOnObject.length() + 1;
3419 char algoName[ 30 ], algoId[ 30 ];
3420 sprintf( algoName, "Algo %d", ++algoNb );
3421 sprintf( algoId, "%d", id );
3422 aSize[ 0 ] = strlen( algoId ) + 1;
3423 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3424 aDataset->CreateOnDisk();
3425 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3426 aDataset->WriteOnDisk( algoId );
3427 aDataset->CloseOnDisk();
3431 aGroup->CloseOnDisk();
3434 // --> submesh objects sub-branches
3436 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3437 SALOMEDS::SObject_wrap mySubmeshBranch;
3438 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
3440 if ( found ) // check if there is shape reference in submeshes
3442 bool hasShapeRef = false;
3443 SALOMEDS::ChildIterator_wrap itSM =
3444 aStudy->NewChildIterator( mySubmeshBranch );
3445 for ( ; itSM->More(); itSM->Next() ) {
3446 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
3447 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3448 mySubRef->ReferencedObject( myShape.inout() );
3449 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3452 { // remove one submesh
3453 if ( shapeRefFound )
3454 { // unassign hypothesis
3455 SMESH::SMESH_subMesh_var mySubMesh =
3456 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3457 if ( !mySubMesh->_is_nil() ) {
3458 int shapeID = mySubMesh->GetId();
3459 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3460 const list<const SMESHDS_Hypothesis*>& hypList =
3461 mySMESHDSMesh->GetHypothesis( S );
3462 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3463 while ( hyp != hypList.end() ) {
3464 int hypID = (*hyp++)->GetID(); // goto next hyp here because
3465 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3469 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3471 } // loop on submeshes of a type
3472 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3473 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3476 } // end check if there is shape reference in submeshes
3478 char name_meshgroup[ 30 ];
3479 if ( i == GetSubMeshOnVertexTag() )
3480 strcpy( name_meshgroup, "SubMeshes On Vertex" );
3481 else if ( i == GetSubMeshOnEdgeTag() )
3482 strcpy( name_meshgroup, "SubMeshes On Edge" );
3483 else if ( i == GetSubMeshOnWireTag() )
3484 strcpy( name_meshgroup, "SubMeshes On Wire" );
3485 else if ( i == GetSubMeshOnFaceTag() )
3486 strcpy( name_meshgroup, "SubMeshes On Face" );
3487 else if ( i == GetSubMeshOnShellTag() )
3488 strcpy( name_meshgroup, "SubMeshes On Shell" );
3489 else if ( i == GetSubMeshOnSolidTag() )
3490 strcpy( name_meshgroup, "SubMeshes On Solid" );
3491 else if ( i == GetSubMeshOnCompoundTag() )
3492 strcpy( name_meshgroup, "SubMeshes On Compound" );
3494 // for each type of submeshes create container HDF group
3495 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3496 aGroup->CreateOnDisk();
3498 // iterator for all submeshes of given type
3499 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
3500 for ( ; itSM->More(); itSM->Next() ) {
3501 SALOMEDS::SObject_wrap mySObject = itSM->Value();
3502 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3503 if ( !CORBA::is_nil( anSubObject ))
3505 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3506 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3507 int subid = myStudyContext->findId( string( objStr.in() ) );
3509 // for each mesh open the HDF group basing on its id
3510 char submeshGrpName[ 30 ];
3511 sprintf( submeshGrpName, "SubMesh %d", subid );
3512 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3513 aSubGroup->CreateOnDisk();
3515 // write reference on a shape, already checked if it exists
3516 SALOMEDS::SObject_wrap mySubRef, myShape;
3517 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3518 mySubRef->ReferencedObject( myShape.inout() );
3519 string myRefOnObject = myShape->GetID();
3520 if ( myRefOnObject.length() > 0 ) {
3521 aSize[ 0 ] = myRefOnObject.length() + 1;
3522 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3523 aDataset->CreateOnDisk();
3524 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3525 aDataset->CloseOnDisk();
3528 // write applied hypotheses if exist
3529 SALOMEDS::SObject_wrap mySubHypBranch;
3530 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
3531 mySubHypBranch.inout() );
3533 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
3534 aSubSubGroup->CreateOnDisk();
3536 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
3538 for ( ; it->More(); it->Next() ) {
3539 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3540 SALOMEDS::SObject_wrap myRefOnHyp;
3541 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
3543 //string myRefOnObject = myRefOnHyp->GetID();
3544 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3545 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3546 int id = myStudyContext->findId( string( objStr.in() ) );
3547 //if ( myRefOnObject.length() > 0 ) {
3548 //aSize[ 0 ] = myRefOnObject.length() + 1;
3549 char hypName[ 30 ], hypId[ 30 ];
3550 sprintf( hypName, "Hyp %d", ++hypNb );
3551 sprintf( hypId, "%d", id );
3552 aSize[ 0 ] = strlen( hypId ) + 1;
3553 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
3554 aDataset->CreateOnDisk();
3555 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3556 aDataset->WriteOnDisk( hypId );
3557 aDataset->CloseOnDisk();
3561 aSubSubGroup->CloseOnDisk();
3564 // write applied algorithms if exist
3565 SALOMEDS::SObject_wrap mySubAlgoBranch;
3566 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3567 mySubAlgoBranch.inout() );
3569 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
3570 aSubSubGroup->CreateOnDisk();
3572 SALOMEDS::ChildIterator_wrap it =
3573 aStudy->NewChildIterator( mySubAlgoBranch );
3575 for ( ; it->More(); it->Next() ) {
3576 SALOMEDS::SObject_wrap mySubSObject = it->Value();
3577 SALOMEDS::SObject_wrap myRefOnAlgo;
3578 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
3580 //string myRefOnObject = myRefOnAlgo->GetID();
3581 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3582 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3583 int id = myStudyContext->findId( string( objStr.in() ) );
3584 //if ( myRefOnObject.length() > 0 ) {
3585 //aSize[ 0 ] = myRefOnObject.length() + 1;
3586 char algoName[ 30 ], algoId[ 30 ];
3587 sprintf( algoName, "Algo %d", ++algoNb );
3588 sprintf( algoId, "%d", id );
3589 aSize[ 0 ] = strlen( algoId ) + 1;
3590 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
3591 aDataset->CreateOnDisk();
3592 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3593 aDataset->WriteOnDisk( algoId );
3594 aDataset->CloseOnDisk();
3598 aSubSubGroup->CloseOnDisk();
3600 // close submesh HDF group
3601 aSubGroup->CloseOnDisk();
3604 // close container of submeshes by type HDF group
3605 aGroup->CloseOnDisk();
3608 // All sub-meshes will be stored in MED file
3609 // .. will NOT (PAL 12992)
3610 //if ( shapeRefFound )
3611 //myWriter.AddAllSubMeshes();
3613 // store submesh order if any
3614 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
3615 if ( theOrderIds.size() ) {
3616 char order_list[ 30 ];
3617 strcpy( order_list, "Mesh Order" );
3618 // count number of submesh ids
3620 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
3621 for ( ; idIt != theOrderIds.end(); idIt++ )
3622 nbIDs += (*idIt).size();
3623 // number of values = number of IDs +
3624 // number of lists (for separators) - 1
3625 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
3626 idIt = theOrderIds.begin();
3627 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
3628 const TListOfInt& idList = *idIt;
3629 if (idIt != theOrderIds.begin()) // not first list
3630 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
3631 // dump submesh ids from current list
3632 TListOfInt::const_iterator id_smId = idList.begin();
3633 for( ; id_smId != idList.end(); id_smId++ )
3634 smIDs[ i++ ] = *id_smId;
3637 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
3639 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
3640 aDataset->CreateOnDisk();
3641 aDataset->WriteOnDisk( smIDs );
3642 aDataset->CloseOnDisk();
3647 // groups root sub-branch
3648 SALOMEDS::SObject_wrap myGroupsBranch;
3649 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
3650 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
3652 char name_group[ 30 ];
3653 if ( i == GetNodeGroupsTag() )
3654 strcpy( name_group, "Groups of Nodes" );
3655 else if ( i == GetEdgeGroupsTag() )
3656 strcpy( name_group, "Groups of Edges" );
3657 else if ( i == GetFaceGroupsTag() )
3658 strcpy( name_group, "Groups of Faces" );
3659 else if ( i == GetVolumeGroupsTag() )
3660 strcpy( name_group, "Groups of Volumes" );
3661 else if ( i == Get0DElementsGroupsTag() )
3662 strcpy( name_group, "Groups of 0D Elements" );
3663 else if ( i == GetBallElementsGroupsTag() )
3664 strcpy( name_group, "Groups of Balls" );
3666 aGroup = new HDFgroup( name_group, aTopGroup );
3667 aGroup->CreateOnDisk();
3669 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
3670 for ( ; it->More(); it->Next() ) {
3671 SALOMEDS::SObject_wrap mySObject = it->Value();
3672 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
3673 if ( !CORBA::is_nil( aSubObject ) ) {
3674 SMESH_GroupBase_i* myGroupImpl =
3675 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
3678 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
3682 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
3683 int anId = myStudyContext->findId( string( objStr.in() ) );
3685 // For each group, create a dataset named "Group <group_persistent_id>"
3686 // and store the group's user name into it
3687 const char* grpName = aGrpBaseDS->GetStoreName();
3688 char* aUserName = myGroupImpl->GetName();
3689 aSize[ 0 ] = strlen( aUserName ) + 1;
3691 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
3692 aDataset->CreateOnDisk();
3693 aDataset->WriteOnDisk( aUserName );
3694 aDataset->CloseOnDisk();
3697 // For each group, create a dataset named "Group <group_persistent_id> Color"
3698 // and store the group's color into it
3699 char grpColorName[ 30 ];
3700 sprintf( grpColorName, "ColorGroup %d", anId );
3701 SALOMEDS::Color aColor = myGroupImpl->GetColor();
3703 anRGB[ 0 ] = aColor.R;
3704 anRGB[ 1 ] = aColor.G;
3705 anRGB[ 2 ] = aColor.B;
3707 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
3708 aDataset->CreateOnDisk();
3709 aDataset->WriteOnDisk( anRGB );
3710 aDataset->CloseOnDisk();
3712 // Pass SMESHDS_Group to MED writer
3713 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
3715 myWriter.AddGroup( aGrpDS );
3717 // write reference on a shape if exists
3718 SMESHDS_GroupOnGeom* aGeomGrp =
3719 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
3721 SALOMEDS::SObject_wrap mySubRef, myShape;
3722 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
3723 mySubRef->ReferencedObject( myShape.inout() ) &&
3724 !CORBA::is_nil( myShape->GetObject() ))
3726 string myRefOnObject = myShape->GetID();
3727 if ( myRefOnObject.length() > 0 ) {
3728 char aRefName[ 30 ];
3729 sprintf( aRefName, "Ref on shape %d", anId);
3730 aSize[ 0 ] = myRefOnObject.length() + 1;
3731 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
3732 aDataset->CreateOnDisk();
3733 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3734 aDataset->CloseOnDisk();
3737 else // shape ref is invalid:
3739 // save a group on geometry as ordinary group
3740 myWriter.AddGroup( aGeomGrp );
3743 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
3744 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
3746 std::string str = aFilterGrp_i->FilterToString();
3747 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
3748 aSize[ 0 ] = str.length() + 1;
3749 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
3750 aDataset->CreateOnDisk();
3751 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
3752 aDataset->CloseOnDisk();
3756 aGroup->CloseOnDisk();
3760 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
3762 // Flush current mesh information into MED file
3765 // save info on nb of elements
3766 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
3768 // maybe a shape was deleted in the study
3769 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
3770 TopoDS_Shape nullShape;
3771 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
3774 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
3779 aGroup = new HDFgroup( "Submeshes", aTopGroup );
3780 aGroup->CreateOnDisk();
3782 // each element belongs to one or none submesh,
3783 // so for each node/element, we store a submesh ID
3785 // Store submesh IDs
3786 for ( int isNode = 0; isNode < 2; ++isNode )
3788 SMDS_ElemIteratorPtr eIt =
3789 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
3790 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
3793 std::vector<int> smIDs; smIDs.reserve( nbElems );
3794 while ( eIt->more() )
3795 if ( const SMDS_MeshElement* e = eIt->next())
3796 smIDs.push_back( e->getshapeId() );
3798 aSize[ 0 ] = nbElems;
3799 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
3800 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3801 aDataset->CreateOnDisk();
3802 aDataset->WriteOnDisk( & smIDs[0] );
3803 aDataset->CloseOnDisk();
3806 aGroup->CloseOnDisk();
3808 // Store node positions on sub-shapes (SMDS_Position):
3809 // ----------------------------------------------------
3811 aGroup = new HDFgroup( "Node Positions", aTopGroup );
3812 aGroup->CreateOnDisk();
3814 // in aGroup, create 5 datasets to contain:
3815 // "Nodes on Edges" - ID of node on edge
3816 // "Edge positions" - U parameter on node on edge
3817 // "Nodes on Faces" - ID of node on face
3818 // "Face U positions" - U parameter of node on face
3819 // "Face V positions" - V parameter of node on face
3821 // Find out nb of nodes on edges and faces
3822 // Collect corresponing sub-meshes
3823 int nbEdgeNodes = 0, nbFaceNodes = 0;
3824 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
3825 // loop on SMESHDS_SubMesh'es
3826 while ( smIt->more() )
3828 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
3829 if ( aSubMesh->IsComplexSubmesh() )
3830 continue; // submesh containing other submeshs
3831 int nbNodes = aSubMesh->NbNodes();
3832 if ( nbNodes == 0 ) continue;
3834 int aShapeID = aSubMesh->GetID();
3835 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
3837 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
3838 // write only SMDS_FacePosition and SMDS_EdgePosition
3839 switch ( aShapeType ) {
3841 nbFaceNodes += nbNodes;
3842 aFaceSM.push_back( aSubMesh );
3845 nbEdgeNodes += nbNodes;
3846 aEdgeSM.push_back( aSubMesh );
3852 // Treat positions on edges or faces
3853 for ( int onFace = 0; onFace < 2; onFace++ )
3855 // Create arrays to store in datasets
3856 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
3857 if (!nbNodes) continue;
3858 int* aNodeIDs = new int [ nbNodes ];
3859 double* aUPos = new double [ nbNodes ];
3860 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
3863 // loop on sub-meshes
3864 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
3865 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
3866 for ( ; itSM != pListSM->end(); itSM++ )
3868 SMESHDS_SubMesh* aSubMesh = (*itSM);
3870 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
3871 // loop on nodes in aSubMesh
3872 while ( itNode->more() )
3875 const SMDS_MeshNode* node = itNode->next();
3876 aNodeIDs [ iNode ] = node->GetID();
3879 const SMDS_PositionPtr pos = node->GetPosition();
3880 if ( onFace ) { // on FACE
3881 const SMDS_FacePosition* fPos =
3882 dynamic_cast<const SMDS_FacePosition*>( pos );
3884 aUPos[ iNode ] = fPos->GetUParameter();
3885 aVPos[ iNode ] = fPos->GetVParameter();
3892 const SMDS_EdgePosition* ePos =
3893 dynamic_cast<const SMDS_EdgePosition*>( pos );
3895 aUPos[ iNode ] = ePos->GetUParameter();
3901 } // loop on nodes in aSubMesh
3902 } // loop on sub-meshes
3907 aSize[ 0 ] = nbNodes;
3909 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
3910 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
3911 aDataset->CreateOnDisk();
3912 aDataset->WriteOnDisk( aNodeIDs );
3913 aDataset->CloseOnDisk();
3916 aDSName = ( onFace ? "Face U positions" : "Edge positions");
3917 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
3918 aDataset->CreateOnDisk();
3919 aDataset->WriteOnDisk( aUPos );
3920 aDataset->CloseOnDisk();
3923 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
3924 aDataset->CreateOnDisk();
3925 aDataset->WriteOnDisk( aVPos );
3926 aDataset->CloseOnDisk();
3931 if ( aVPos ) delete [] aVPos;
3933 } // treat positions on edges or faces
3935 // close "Node Positions" group
3936 aGroup->CloseOnDisk();
3938 } // if ( there are submeshes in SMESHDS_Mesh )
3941 // close mesh HDF group
3942 aTopGroup->CloseOnDisk();
3950 aFile->CloseOnDisk();
3953 // Convert temporary files to stream
3954 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
3956 // Remove temporary files and directory
3958 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
3960 return aStreamFile._retn();
3963 //=============================================================================
3965 * SMESH_Gen_i::SaveASCII
3967 * Save SMESH module's data in ASCII format
3969 //=============================================================================
3971 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
3973 bool isMultiFile ) {
3974 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
3975 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
3976 return aStreamFile._retn();
3978 //after usual saving needs to encipher binary to text string
3979 //Any binary symbol will be represent as "|xx" () hexadecimal format number
3980 int size = aStreamFile.in().length();
3981 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
3982 for ( int i = 0; i < size; i++ )
3983 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
3985 buffer[size * 3] = '\0';
3987 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
3989 return anAsciiStreamFile._retn();
3992 //=============================================================================
3994 * SMESH_Gen_i::loadGeomData
3996 * Load GEOM module data
3998 //=============================================================================
4000 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
4002 if ( theCompRoot->_is_nil() )
4005 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
4006 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
4009 //=============================================================================
4013 * Load SMESH module's data
4015 //=============================================================================
4017 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
4018 const SALOMEDS::TMPFile& theStream,
4022 if (!myStudyContext)
4024 SALOMEDS::Study_var aStudy = getStudyServant();
4025 /* if( !theComponent->_is_nil() )
4027 if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
4028 loadGeomData( aStudy->FindComponent( "GEOM" ) );
4031 // Get temporary files location
4032 TCollection_AsciiString tmpDir =
4033 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
4035 // Convert the stream into sequence of files to process
4036 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
4039 TCollection_AsciiString aStudyName( "" );
4040 if ( isMultiFile ) {
4041 CORBA::WString_var url = aStudy->URL();
4042 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
4044 // Set names of temporary files
4045 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4046 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4050 HDFdataset* aDataset;
4051 HDFgroup* aTopGroup;
4053 HDFgroup* aSubGroup;
4054 HDFgroup* aSubSubGroup;
4057 // ---> open HDF file
4058 aFile = new HDFfile( (char*) filename.ToCString() );
4060 aFile->OpenOnDisk( HDF_RDONLY );
4062 catch ( HDFexception ) {
4063 INFOS( "Load(): " << filename << " not found!" );
4067 TPythonDump pd; // prevent dump during loading
4069 // DriverMED_R_SMESHDS_Mesh myReader;
4070 // myReader.SetFile( meshfile.ToCString() );
4072 // For PAL13473 ("Repetitive mesh") implementation.
4073 // New dependencies between SMESH objects are established:
4074 // now hypotheses can refer to meshes, shapes and other hypotheses.
4075 // To keep data consistent, the following order of data restoration
4077 // 1. Create hypotheses
4078 // 2. Create all meshes
4079 // 3. Load hypotheses' data
4082 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
4083 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
4084 list< SMESH::Filter_var > filters;
4086 // get total number of top-level groups
4087 int aNbGroups = aFile->nInternalObjects();
4088 if ( aNbGroups > 0 ) {
4089 // --> in first turn we should read&create hypotheses
4090 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
4091 // open hypotheses root HDF group
4092 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4093 aTopGroup->OpenOnDisk();
4095 // get number of hypotheses
4096 int aNbObjects = aTopGroup->nInternalObjects();
4097 for ( int j = 0; j < aNbObjects; j++ ) {
4098 // try to identify hypothesis
4099 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4100 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4102 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
4103 // open hypothesis group
4104 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4105 aGroup->OpenOnDisk();
4107 // --> get hypothesis id
4108 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
4113 // get number of datasets
4114 int aNbSubObjects = aGroup->nInternalObjects();
4115 for ( int k = 0; k < aNbSubObjects; k++ ) {
4117 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4118 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4119 // --> get hypothesis name
4120 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4121 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4122 aDataset->OpenOnDisk();
4123 size = aDataset->GetSize();
4124 char* hypname_str = new char[ size ];
4125 aDataset->ReadFromDisk( hypname_str );
4126 hypname = string( hypname_str );
4127 delete [] hypname_str;
4128 aDataset->CloseOnDisk();
4130 // --> get hypothesis plugin library name
4131 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4132 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4133 aDataset->OpenOnDisk();
4134 size = aDataset->GetSize();
4135 char* libname_str = new char[ size ];
4136 aDataset->ReadFromDisk( libname_str );
4137 if(MYDEBUG) SCRUTE( libname_str );
4138 libname = string( libname_str );
4139 delete [] libname_str;
4140 aDataset->CloseOnDisk();
4142 // --> get hypothesis data
4143 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4144 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4145 aDataset->OpenOnDisk();
4146 size = aDataset->GetSize();
4147 char* hypdata_str = new char[ size ];
4148 aDataset->ReadFromDisk( hypdata_str );
4149 hypdata = string( hypdata_str );
4150 delete [] hypdata_str;
4151 aDataset->CloseOnDisk();
4154 // close hypothesis HDF group
4155 aGroup->CloseOnDisk();
4157 // --> restore hypothesis from data
4158 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4159 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
4160 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4161 SMESH::SMESH_Hypothesis_var myHyp;
4163 try { // protect persistence mechanism against exceptions
4164 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4167 INFOS( "Exception during hypothesis creation" );
4170 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4172 // myImpl->LoadFrom( hypdata.c_str() );
4173 hypDataList.push_back( make_pair( myImpl, hypdata ));
4174 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4175 int newId = myStudyContext->findId( iorString.in() );
4176 myStudyContext->mapOldToNew( id, newId );
4179 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4183 // close hypotheses root HDF group
4184 aTopGroup->CloseOnDisk();
4188 // --> then we should read&create algorithms
4189 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
4190 // open algorithms root HDF group
4191 aTopGroup = new HDFgroup( "Algorithms", aFile );
4192 aTopGroup->OpenOnDisk();
4194 // get number of algorithms
4195 int aNbObjects = aTopGroup->nInternalObjects();
4196 for ( int j = 0; j < aNbObjects; j++ ) {
4197 // try to identify algorithm
4198 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
4199 aTopGroup->InternalObjectIndentify( j, hypGrpName );
4201 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
4202 // open algorithm group
4203 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4204 aGroup->OpenOnDisk();
4206 // --> get algorithm id
4207 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
4212 // get number of datasets
4213 int aNbSubObjects = aGroup->nInternalObjects();
4214 for ( int k = 0; k < aNbSubObjects; k++ ) {
4216 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
4217 aGroup->InternalObjectIndentify( k, name_of_subgroup );
4218 // --> get algorithm name
4219 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
4220 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4221 aDataset->OpenOnDisk();
4222 size = aDataset->GetSize();
4223 char* hypname_str = new char[ size ];
4224 aDataset->ReadFromDisk( hypname_str );
4225 hypname = string( hypname_str );
4226 delete [] hypname_str;
4227 aDataset->CloseOnDisk();
4229 // --> get algorithm plugin library name
4230 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
4231 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4232 aDataset->OpenOnDisk();
4233 size = aDataset->GetSize();
4234 char* libname_str = new char[ size ];
4235 aDataset->ReadFromDisk( libname_str );
4236 if(MYDEBUG) SCRUTE( libname_str );
4237 libname = string( libname_str );
4238 delete [] libname_str;
4239 aDataset->CloseOnDisk();
4241 // --> get algorithm data
4242 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
4243 aDataset = new HDFdataset( name_of_subgroup, aGroup );
4244 aDataset->OpenOnDisk();
4245 size = aDataset->GetSize();
4246 char* hypdata_str = new char[ size ];
4247 aDataset->ReadFromDisk( hypdata_str );
4248 if(MYDEBUG) SCRUTE( hypdata_str );
4249 hypdata = string( hypdata_str );
4250 delete [] hypdata_str;
4251 aDataset->CloseOnDisk();
4254 // close algorithm HDF group
4255 aGroup->CloseOnDisk();
4257 // --> restore algorithm from data
4258 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
4259 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
4260 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
4261 SMESH::SMESH_Hypothesis_var myHyp;
4263 try { // protect persistence mechanism against exceptions
4264 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
4267 INFOS( "Exception during hypothesis creation" );
4270 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4272 //myImpl->LoadFrom( hypdata.c_str() );
4273 hypDataList.push_back( make_pair( myImpl, hypdata ));
4274 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
4275 int newId = myStudyContext->findId( iorString.in() );
4276 myStudyContext->mapOldToNew( id, newId );
4279 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
4283 // close algorithms root HDF group
4284 aTopGroup->CloseOnDisk();
4288 // --> the rest groups should be meshes
4289 for ( int i = 0; i < aNbGroups; i++ ) {
4290 // identify next group
4291 char meshName[ HDF_NAME_MAX_LEN+1 ];
4292 aFile->InternalObjectIndentify( i, meshName );
4294 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
4296 int id = atoi( string( meshName ).substr( 4 ).c_str() );
4300 // open mesh HDF group
4301 aTopGroup = new HDFgroup( meshName, aFile );
4302 aTopGroup->OpenOnDisk();
4304 // get number of child HDF objects
4305 int aNbObjects = aTopGroup->nInternalObjects();
4306 if ( aNbObjects > 0 ) {
4308 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
4309 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
4310 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
4311 if ( !myNewMeshImpl )
4313 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
4315 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
4316 int newId = myStudyContext->findId( iorString.in() );
4317 myStudyContext->mapOldToNew( id, newId );
4320 // try to read and set auto color flag
4321 char aMeshAutoColorName[ 30 ];
4322 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
4323 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
4325 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
4326 aDataset->OpenOnDisk();
4327 size = aDataset->GetSize();
4328 int* anAutoColor = new int[ size ];
4329 aDataset->ReadFromDisk( anAutoColor );
4330 aDataset->CloseOnDisk();
4331 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
4332 delete [] anAutoColor;
4335 // try to read and set reference to shape
4336 GEOM::GEOM_Object_var aShapeObject;
4337 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
4338 // load mesh "Ref on shape" - it's an entry to SObject
4339 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
4340 aDataset->OpenOnDisk();
4341 size = aDataset->GetSize();
4342 char* refFromFile = new char[ size ];
4343 aDataset->ReadFromDisk( refFromFile );
4344 aDataset->CloseOnDisk();
4345 if ( strlen( refFromFile ) > 0 ) {
4346 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
4348 // Make sure GEOM data are loaded first
4349 //loadGeomData( shapeSO->GetFatherComponent() );
4351 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4352 if ( !CORBA::is_nil( shapeObject ) ) {
4353 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4354 if ( !aShapeObject->_is_nil() )
4355 myNewMeshImpl->SetShape( aShapeObject );
4358 delete [] refFromFile;
4361 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
4362 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
4364 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
4365 aDataset->OpenOnDisk();
4366 size = aDataset->GetSize();
4367 int* meshPersistentId = new int[ size ];
4368 aDataset->ReadFromDisk( meshPersistentId );
4369 aDataset->CloseOnDisk();
4370 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
4371 delete [] meshPersistentId;
4377 // As all object that can be referred by hypothesis are created,
4378 // we can restore hypothesis data
4380 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
4381 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4383 SMESH_Hypothesis_i* hyp = hyp_data->first;
4384 string & data = hyp_data->second;
4385 hyp->LoadFrom( data.c_str() );
4388 // Restore the rest mesh data
4390 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
4391 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4393 aTopGroup = meshi_group->second;
4394 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4395 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4396 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4398 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
4399 bool hasData = false;
4402 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
4403 int newId = myStudyContext->findId( iorString.in() );
4404 int id = myStudyContext->getOldId( newId );
4406 // try to find mesh data dataset
4407 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
4408 // load mesh "has data" flag
4409 aDataset = new HDFdataset( "Has data", aTopGroup );
4410 aDataset->OpenOnDisk();
4411 size = aDataset->GetSize();
4412 char* strHasData = new char[ size ];
4413 aDataset->ReadFromDisk( strHasData );
4414 aDataset->CloseOnDisk();
4415 if ( strcmp( strHasData, "1") == 0 ) {
4416 // read mesh data from MED file
4417 // myReader.SetMesh( mySMESHDSMesh );
4418 // myReader.SetMeshId( id );
4419 // myReader.Perform();
4422 delete [] strHasData;
4425 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
4426 // nodes and elements are not yet put into sub-meshes)
4427 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4428 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4429 aGroup->OpenOnDisk();
4430 // get number of applied algorithms
4431 int aNbSubObjects = aGroup->nInternalObjects();
4432 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
4433 for ( int j = 0; j < aNbSubObjects; j++ ) {
4434 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4435 aGroup->InternalObjectIndentify( j, name_dataset );
4436 // check if it is an algorithm
4437 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
4438 aDataset = new HDFdataset( name_dataset, aGroup );
4439 aDataset->OpenOnDisk();
4440 size = aDataset->GetSize();
4441 char* refFromFile = new char[ size ];
4442 aDataset->ReadFromDisk( refFromFile );
4443 aDataset->CloseOnDisk();
4444 // san - it is impossible to recover applied algorithms using their entries within Load() method
4445 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
4446 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4447 int id = atoi( refFromFile );
4448 delete [] refFromFile;
4449 string anIOR = myStudyContext->getIORbyOldId( id );
4450 if ( !anIOR.empty() ) {
4451 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4452 if ( !CORBA::is_nil( hypObject ) ) {
4453 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4454 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4455 || !myNewMeshImpl->HasShapeToMesh()) )
4456 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4461 aGroup->CloseOnDisk();
4464 // try to get applied hypotheses
4465 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4466 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4467 aGroup->OpenOnDisk();
4468 // get number of applied hypotheses
4469 int aNbSubObjects = aGroup->nInternalObjects();
4470 for ( int j = 0; j < aNbSubObjects; j++ ) {
4471 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4472 aGroup->InternalObjectIndentify( j, name_dataset );
4473 // check if it is a hypothesis
4474 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4475 aDataset = new HDFdataset( name_dataset, aGroup );
4476 aDataset->OpenOnDisk();
4477 size = aDataset->GetSize();
4478 char* refFromFile = new char[ size ];
4479 aDataset->ReadFromDisk( refFromFile );
4480 aDataset->CloseOnDisk();
4481 // san - it is impossible to recover applied hypotheses using their entries within Load() method
4482 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
4483 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
4484 int id = atoi( refFromFile );
4485 delete [] refFromFile;
4486 string anIOR = myStudyContext->getIORbyOldId( id );
4487 if ( !anIOR.empty() ) {
4488 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4489 if ( !CORBA::is_nil( hypObject ) ) {
4490 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4491 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
4492 || !myNewMeshImpl->HasShapeToMesh()) )
4493 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
4498 aGroup->CloseOnDisk();
4501 // --> try to find SUB-MESHES containers for each type of submesh
4502 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
4503 const char* name_meshgroup = 0;
4504 if ( j == GetSubMeshOnVertexTag() )
4505 name_meshgroup = "SubMeshes On Vertex";
4506 else if ( j == GetSubMeshOnEdgeTag() )
4507 name_meshgroup = "SubMeshes On Edge";
4508 else if ( j == GetSubMeshOnWireTag() )
4509 name_meshgroup = "SubMeshes On Wire";
4510 else if ( j == GetSubMeshOnFaceTag() )
4511 name_meshgroup = "SubMeshes On Face";
4512 else if ( j == GetSubMeshOnShellTag() )
4513 name_meshgroup = "SubMeshes On Shell";
4514 else if ( j == GetSubMeshOnSolidTag() )
4515 name_meshgroup = "SubMeshes On Solid";
4516 else if ( j == GetSubMeshOnCompoundTag() )
4517 name_meshgroup = "SubMeshes On Compound";
4519 // try to get submeshes container HDF group
4520 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
4521 // open submeshes containers HDF group
4522 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4523 aGroup->OpenOnDisk();
4525 // get number of submeshes
4526 int aNbSubMeshes = aGroup->nInternalObjects();
4527 for ( int k = 0; k < aNbSubMeshes; k++ ) {
4529 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
4530 aGroup->InternalObjectIndentify( k, name_submeshgroup );
4531 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
4532 // --> get submesh id
4533 int subid = atoi( name_submeshgroup + 7 );
4536 // open submesh HDF group
4537 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
4538 aSubGroup->OpenOnDisk();
4540 // try to read and set reference to subshape
4541 GEOM::GEOM_Object_var aSubShapeObject;
4542 SMESH::SMESH_subMesh_var aSubMesh;
4544 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
4545 // load submesh "Ref on shape" - it's an entry to SObject
4546 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
4547 aDataset->OpenOnDisk();
4548 size = aDataset->GetSize();
4549 char* refFromFile = new char[ size ];
4550 aDataset->ReadFromDisk( refFromFile );
4551 aDataset->CloseOnDisk();
4552 if ( strlen( refFromFile ) > 0 ) {
4553 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
4554 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
4555 if ( !CORBA::is_nil( subShapeObject ) ) {
4556 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
4557 if ( !aSubShapeObject->_is_nil() )
4558 aSubMesh = SMESH::SMESH_subMesh::_duplicate
4559 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
4560 if ( aSubMesh->_is_nil() )
4562 string iorSubString = GetORB()->object_to_string( aSubMesh );
4563 int newSubId = myStudyContext->findId( iorSubString );
4564 myStudyContext->mapOldToNew( subid, newSubId );
4569 if ( aSubMesh->_is_nil() )
4572 // try to get applied algorithms
4573 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
4574 // open "applied algorithms" HDF group
4575 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4576 aSubSubGroup->OpenOnDisk();
4577 // get number of applied algorithms
4578 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4579 for ( int l = 0; l < aNbSubObjects; l++ ) {
4580 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4581 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4582 // check if it is an algorithm
4583 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
4584 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4585 aDataset->OpenOnDisk();
4586 size = aDataset->GetSize();
4587 char* refFromFile = new char[ size ];
4588 aDataset->ReadFromDisk( refFromFile );
4589 aDataset->CloseOnDisk();
4591 int id = atoi( refFromFile );
4592 string anIOR = myStudyContext->getIORbyOldId( id );
4593 if ( !anIOR.empty() ) {
4594 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4595 if ( !CORBA::is_nil( hypObject ) ) {
4596 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4597 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4598 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4603 // close "applied algorithms" HDF group
4604 aSubSubGroup->CloseOnDisk();
4607 // try to get applied hypotheses
4608 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
4609 // open "applied hypotheses" HDF group
4610 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4611 aSubSubGroup->OpenOnDisk();
4612 // get number of applied hypotheses
4613 int aNbSubObjects = aSubSubGroup->nInternalObjects();
4614 for ( int l = 0; l < aNbSubObjects; l++ ) {
4615 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4616 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
4617 // check if it is a hypothesis
4618 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
4619 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
4620 aDataset->OpenOnDisk();
4621 size = aDataset->GetSize();
4622 char* refFromFile = new char[ size ];
4623 aDataset->ReadFromDisk( refFromFile );
4624 aDataset->CloseOnDisk();
4626 int id = atoi( refFromFile );
4627 string anIOR = myStudyContext->getIORbyOldId( id );
4628 if ( !anIOR.empty() ) {
4629 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
4630 if ( !CORBA::is_nil( hypObject ) ) {
4631 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
4632 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
4633 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
4638 // close "APPLIED HYPOTHESES" hdf group
4639 aSubSubGroup->CloseOnDisk();
4642 // close SUB-MESH hdf group
4643 aSubGroup->CloseOnDisk();
4646 // close SUB-MESHES containers hdf group
4647 aGroup->CloseOnDisk();
4651 // try to get GROUPS
4652 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
4653 char name_group[ 30 ];
4654 if ( ii == GetNodeGroupsTag() )
4655 strcpy( name_group, "Groups of Nodes" );
4656 else if ( ii == GetEdgeGroupsTag() )
4657 strcpy( name_group, "Groups of Edges" );
4658 else if ( ii == GetFaceGroupsTag() )
4659 strcpy( name_group, "Groups of Faces" );
4660 else if ( ii == GetVolumeGroupsTag() )
4661 strcpy( name_group, "Groups of Volumes" );
4662 else if ( ii == Get0DElementsGroupsTag() )
4663 strcpy( name_group, "Groups of 0D Elements" );
4664 else if ( ii == GetBallElementsGroupsTag() )
4665 strcpy( name_group, "Groups of Balls" );
4667 if ( aTopGroup->ExistInternalObject( name_group ) ) {
4668 aGroup = new HDFgroup( name_group, aTopGroup );
4669 aGroup->OpenOnDisk();
4670 // get number of groups
4671 int aNbSubObjects = aGroup->nInternalObjects();
4672 for ( int j = 0; j < aNbSubObjects; j++ ) {
4673 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
4674 aGroup->InternalObjectIndentify( j, name_dataset );
4675 // check if it is an group
4676 if ( string( name_dataset ).substr( 0, 5 ) == string( "Group" ) ) {
4678 int subid = atoi( string( name_dataset ).substr( 5 ).c_str() );
4681 aDataset = new HDFdataset( name_dataset, aGroup );
4682 aDataset->OpenOnDisk();
4684 // Retrieve actual group name
4685 size = aDataset->GetSize();
4686 char* nameFromFile = new char[ size ];
4687 aDataset->ReadFromDisk( nameFromFile );
4688 aDataset->CloseOnDisk();
4690 // Try to find a shape reference
4691 TopoDS_Shape aShape;
4692 char aRefName[ 30 ];
4693 sprintf( aRefName, "Ref on shape %d", subid);
4694 if ( aGroup->ExistInternalObject( aRefName ) ) {
4695 // load mesh "Ref on shape" - it's an entry to SObject
4696 aDataset = new HDFdataset( aRefName, aGroup );
4697 aDataset->OpenOnDisk();
4698 size = aDataset->GetSize();
4699 char* refFromFile = new char[ size ];
4700 aDataset->ReadFromDisk( refFromFile );
4701 aDataset->CloseOnDisk();
4702 if ( strlen( refFromFile ) > 0 ) {
4703 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
4704 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
4705 if ( !CORBA::is_nil( shapeObject ) ) {
4706 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
4707 if ( !aShapeObject->_is_nil() )
4708 aShape = GeomObjectToShape( aShapeObject );
4712 // Try to read a filter of SMESH_GroupOnFilter
4713 SMESH::Filter_var filter;
4714 SMESH_PredicatePtr predicate;
4715 std::string hdfGrpName = "Filter " + SMESH_Comment(subid);
4716 if ( aGroup->ExistInternalObject( hdfGrpName.c_str() ))
4718 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
4719 aDataset->OpenOnDisk();
4720 size = aDataset->GetSize();
4721 char* persistStr = new char[ size ];
4722 aDataset->ReadFromDisk( persistStr );
4723 aDataset->CloseOnDisk();
4724 if ( strlen( persistStr ) > 0 ) {
4725 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
4726 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
4727 filters.push_back( filter );
4731 // Create group servant
4732 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
4733 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
4734 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
4735 // Obtain a SMESHDS_Group object
4736 if ( aNewGroup->_is_nil() )
4739 string iorSubString = GetORB()->object_to_string( aNewGroup );
4740 int newSubId = myStudyContext->findId( iorSubString );
4741 myStudyContext->mapOldToNew( subid, newSubId );
4743 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
4747 if ( SMESH_GroupOnFilter_i* aFilterGroup =
4748 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
4750 aFilterGroup->SetFilter( filter );
4751 filter->UnRegister();
4753 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
4754 if ( !aGroupBaseDS )
4757 aGroupBaseDS->SetStoreName( name_dataset );
4760 // Read color of the group
4761 char aGroupColorName[ 30 ];
4762 sprintf( aGroupColorName, "ColorGroup %d", subid);
4763 if ( aGroup->ExistInternalObject( aGroupColorName ) )
4765 aDataset = new HDFdataset( aGroupColorName, aGroup );
4766 aDataset->OpenOnDisk();
4767 size = aDataset->GetSize();
4768 double* anRGB = new double[ size ];
4769 aDataset->ReadFromDisk( anRGB );
4770 aDataset->CloseOnDisk();
4771 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
4772 aGroupBaseDS->SetColor( aColor );
4776 aGroup->CloseOnDisk();
4780 // instead of reading mesh data, we read only brief information of all
4781 // objects: mesh, groups, sub-meshes (issue 0021208 )
4784 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
4785 meshfile.ToCString(), filename.ToCString(),
4789 // read Sub-Mesh ORDER if any
4790 if( aTopGroup->ExistInternalObject( "Mesh Order" ) ) {
4791 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
4792 aDataset->OpenOnDisk();
4793 size = aDataset->GetSize();
4794 int* smIDs = new int[ size ];
4795 aDataset->ReadFromDisk( smIDs );
4796 aDataset->CloseOnDisk();
4797 TListOfListOfInt anOrderIds;
4798 anOrderIds.push_back( TListOfInt() );
4799 for ( int i = 0; i < size; i++ )
4800 if ( smIDs[ i ] < 0 ) // is separator
4801 anOrderIds.push_back( TListOfInt() );
4803 anOrderIds.back().push_back(smIDs[ i ]);
4805 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
4809 // update hyps needing full mesh data restored (issue 20918)
4810 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
4812 SMESH_Hypothesis_i* hyp = hyp_data->first;
4813 hyp->UpdateAsMeshesRestored();
4816 // notify algos on completed restoration to set sub-mesh event listeners
4817 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
4819 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
4820 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
4822 TopoDS_Shape myLocShape;
4823 if(myLocMesh.HasShapeToMesh())
4824 myLocShape = myLocMesh.GetShapeToMesh();
4826 myLocShape = SMESH_Mesh::PseudoShape();
4828 myLocMesh.GetSubMesh(myLocShape)->
4829 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
4832 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
4833 list< SMESH::Filter_var >::iterator f = filters.begin();
4834 for ( ; f != filters.end(); ++f )
4835 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
4836 fi->FindBaseObjects();
4841 aTopGroup->CloseOnDisk();
4844 aFile->CloseOnDisk();
4847 // Remove temporary files created from the stream
4850 SMESH_File meshFile( meshfile.ToCString() );
4851 if ( !meshFile ) // no meshfile exists
4853 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
4857 Engines::Container_var container = GetContainerRef();
4858 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
4860 container_i->registerTemporaryFile( filename.ToCString() );
4861 container_i->registerTemporaryFile( meshfile.ToCString() );
4862 container_i->registerTemporaryFile( tmpDir.ToCString() );
4866 pd << ""; // prevent optimizing pd out
4868 // creation of tree nodes for all data objects in the study
4869 // to support tree representation customization and drag-n-drop:
4870 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
4871 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
4872 useCaseBuilder->SetRootCurrent();
4873 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
4874 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
4875 for (it->InitEx(true); it->More(); it->Next()) {
4876 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
4883 //=============================================================================
4885 * SMESH_Gen_i::LoadASCII
4887 * Load SMESH module's data in ASCII format
4889 //=============================================================================
4891 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
4892 const SALOMEDS::TMPFile& theStream,
4894 bool isMultiFile ) {
4895 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
4896 return Load( theComponent, theStream, theURL, isMultiFile );
4898 //before call main ::Load method it's need for decipher text format to
4899 //binary ( "|xx" => x' )
4900 int size = theStream.length();
4901 if ( int((size / 3 )*3) != size ) //error size of buffer
4904 int real_size = int(size / 3);
4906 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
4909 unsigned int c = -1;
4910 for ( int i = 0; i < real_size; i++ )
4912 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
4913 sscanf( tmp, "%x", &c );
4914 sprintf( (char*)&(buffer[i]), "%c", (char)c );
4917 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
4919 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
4922 //=============================================================================
4924 * SMESH_Gen_i::Close
4926 * Clears study-connected data when it is closed
4928 //=============================================================================
4930 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
4932 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
4934 // Clear study contexts data
4935 delete myStudyContext;
4938 // remove the tmp files meshes are loaded from
4939 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
4944 //=============================================================================
4946 * SMESH_Gen_i::ComponentDataType
4948 * Get component data type
4950 //=============================================================================
4952 char* SMESH_Gen_i::ComponentDataType()
4954 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
4955 return CORBA::string_dup( "SMESH" );
4959 //=============================================================================
4961 * SMESH_Gen_i::IORToLocalPersistentID
4963 * Transform data from transient form to persistent
4965 //=============================================================================
4967 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
4968 const char* IORString,
4969 CORBA::Boolean /*isMultiFile*/,
4970 CORBA::Boolean /*isASCII*/ )
4972 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
4974 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
4975 int anId = myStudyContext->findId( IORString );
4977 if(MYDEBUG) MESSAGE( "VSR " << anId )
4979 sprintf( strId, "%d", anId );
4980 return CORBA::string_dup( strId );
4983 return CORBA::string_dup( "" );
4986 //=============================================================================
4988 * SMESH_Gen_i::LocalPersistentIDToIOR
4990 * Transform data from persistent form to transient
4992 //=============================================================================
4994 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
4995 const char* aLocalPersistentID,
4996 CORBA::Boolean /*isMultiFile*/,
4997 CORBA::Boolean /*isASCII*/ )
4999 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
5001 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
5002 int anId = atoi( aLocalPersistentID );
5003 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
5005 return CORBA::string_dup( "" );
5008 //=======================================================================
5009 //function : RegisterObject
5011 //=======================================================================
5013 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
5015 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5016 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
5017 return myStudyContext->addObject( string( iorString.in() ) );
5022 //================================================================================
5024 * \brief Return id of registered object
5025 * \param theObject - the Object
5026 * \retval int - Object id
5028 //================================================================================
5030 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5032 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5033 string iorString = GetORB()->object_to_string( theObject );
5034 return myStudyContext->findId( iorString );
5039 //=============================================================================
5041 * SMESH_Gen_i::SetName
5043 * Set a new object name
5045 //=============================================================================
5046 void SMESH_Gen_i::SetName(const char* theIOR,
5047 const char* theName)
5049 if ( theIOR && strcmp( theIOR, "" ) ) {
5050 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
5051 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
5052 if ( !aSO->_is_nil() ) {
5053 SetName( aSO, theName );
5058 // Version information
5059 char* SMESH_Gen_i::getVersion()
5061 #if SMESH_DEVELOPMENT
5062 return CORBA::string_dup(SMESH_VERSION_STR"dev");
5064 return CORBA::string_dup(SMESH_VERSION_STR);
5068 //=================================================================================
5069 // function : Move()
5070 // purpose : Moves objects to the specified position.
5071 // Is used in the drag-n-drop functionality.
5072 //=================================================================================
5073 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
5074 SALOMEDS::SObject_ptr where,
5077 if ( CORBA::is_nil( where ) ) return;
5079 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
5080 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
5081 SALOMEDS::SComponent_var father = where->GetFatherComponent();
5082 std::string dataType = father->ComponentDataType();
5083 if ( dataType != "SMESH" ) return; // not a SMESH component
5085 SALOMEDS::SObject_var objAfter;
5086 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
5087 // insert at given row -> find insertion position
5088 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
5090 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
5091 if ( i == row && useCaseIt->More() ) {
5092 objAfter = useCaseIt->Value();
5096 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
5097 SALOMEDS::SObject_var sobj = what[i];
5098 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
5099 // insert the object to the use case tree
5100 if ( !CORBA::is_nil( objAfter ) )
5101 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
5103 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
5106 //================================================================================
5108 * \brief Returns true if algorithm can be used to mesh a given geometry
5109 * \param [in] theAlgoType - the algorithm type
5110 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
5111 * \param [in] theGeomObject - the geometry to mesh
5112 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
5113 * else, returns \c True if at least one shape is meshable
5114 * \return CORBA::Boolean - can or can't
5116 //================================================================================
5118 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
5119 const char* theLibName,
5120 GEOM::GEOM_Object_ptr theGeomObject,
5121 CORBA::Boolean toCheckAll)
5125 std::string aPlatformLibName;
5126 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
5127 GenericHypothesisCreator_i* aCreator =
5128 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
5131 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
5132 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
5139 SMESH_CATCH( SMESH::doNothing );
5142 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
5147 //=================================================================================
5148 // function : GetInsideSphere
5149 // purpose : Collect indices of elements, which are located inside the sphere
5150 //=================================================================================
5151 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
5152 SMESH::ElementType theElemType,
5158 SMESH::long_array_var aResult = new SMESH::long_array();
5159 if ( meshPart->_is_nil() )
5160 return aResult._retn();
5162 // 1. Create geometrical object
5163 gp_Pnt aP( theX, theY, theZ );
5164 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
5166 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5168 if ( lst.size() > 0 ) {
5169 aResult->length( lst.size() );
5170 for ( size_t i = 0; i < lst.size(); i++ ) {
5171 aResult[i] = lst[i];
5174 return aResult._retn();
5177 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
5178 SMESH::ElementType theElemType,
5179 CORBA::Double theX1,
5180 CORBA::Double theY1,
5181 CORBA::Double theZ1,
5182 CORBA::Double theX2,
5183 CORBA::Double theY2,
5184 CORBA::Double theZ2) {
5185 SMESH::long_array_var aResult = new SMESH::long_array();
5186 if( meshPart->_is_nil() )
5187 return aResult._retn();
5189 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
5191 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5193 if( lst.size() > 0 ) {
5194 aResult->length( lst.size() );
5195 for ( size_t i = 0; i < lst.size(); i++ ) {
5196 aResult[i] = lst[i];
5199 return aResult._retn();
5202 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
5203 SMESH::ElementType theElemType,
5207 CORBA::Double theDX,
5208 CORBA::Double theDY,
5209 CORBA::Double theDZ,
5211 CORBA::Double theR ){
5212 SMESH::long_array_var aResult = new SMESH::long_array();
5213 if( meshPart->_is_nil() )
5214 return aResult._retn();
5216 gp_Pnt aP( theX, theY, theZ );
5217 gp_Vec aV( theDX, theDY, theDZ );
5218 gp_Ax2 anAxes (aP, aV);
5220 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
5222 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
5224 if( lst.size() > 0 ) {
5225 aResult->length( lst.size() );
5226 for ( size_t i = 0; i < lst.size(); i++ ) {
5227 aResult[i] = lst[i];
5230 return aResult._retn();
5233 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5234 SMESH::ElementType theElemType,
5235 GEOM::GEOM_Object_ptr theGeom,
5236 CORBA::Double theTolerance ) {
5237 SMESH::long_array_var aResult = new SMESH::long_array();
5238 if( meshPart->_is_nil() || theGeom->_is_nil() )
5239 return aResult._retn();
5241 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
5243 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
5245 if( lst.size() > 0 ) {
5246 aResult->length( lst.size() );
5247 for ( size_t i = 0; i < lst.size(); i++ ) {
5248 aResult[i] = lst[i];
5251 return aResult._retn();
5256 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
5257 SMESH::ElementType theElemType,
5258 TopoDS_Shape& aShape,
5259 double* theTolerance) {
5261 std::vector<long> res;
5262 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
5264 if ( mesh->_is_nil() )
5267 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
5271 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
5276 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
5277 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
5278 anElementsOnShape->SetAllNodes( true );
5279 anElementsOnShape->SetMesh( meshDS );
5280 anElementsOnShape->SetShape( aShape, aType );
5283 anElementsOnShape->SetTolerance(*theTolerance);
5285 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
5286 if ( !msource->_is_nil() ) { // Mesh case
5287 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
5289 while ( elemIt->more() ) {
5290 const SMDS_MeshElement* anElem = elemIt->next();
5291 long anId = anElem->GetID();
5292 if ( anElementsOnShape->IsSatisfy( anId ) )
5293 res.push_back( anId );
5297 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
5298 if ( !gsource->_is_nil() ) {
5299 if(theElemType == SMESH::NODE) {
5300 SMESH::long_array_var nodes = gsource->GetNodeIDs();
5301 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
5302 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
5303 long anId = node->GetID();
5304 if ( anElementsOnShape->IsSatisfy( anId ) )
5305 res.push_back( anId );
5308 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
5309 SMESH::long_array_var elems = gsource->GetListOfID();
5310 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5311 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
5312 long anId = elem->GetID();
5313 if ( anElementsOnShape->IsSatisfy( anId ) )
5314 res.push_back( anId );
5319 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
5320 if ( !smsource->_is_nil() ) {
5321 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
5322 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
5323 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
5325 long anId = elem->GetID();
5326 if ( anElementsOnShape->IsSatisfy( anId ) )
5327 res.push_back( anId );
5335 //=============================================================================
5337 * SMESHEngine_factory
5339 * C factory, accessible with dlsym, after dlopen
5341 //=============================================================================
5345 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
5346 PortableServer::POA_ptr poa,
5347 PortableServer::ObjectId* contId,
5348 const char* instanceName,
5349 const char* interfaceName )
5351 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
5352 if(MYDEBUG) SCRUTE(interfaceName);
5353 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
5354 return aSMESHGen->getId() ;