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>
60 #define LibHandle HMODULE
61 #define LoadLib( name ) LoadLibrary( name )
62 #define GetProc GetProcAddress
63 #define UnLoadLib( handle ) FreeLibrary( handle );
65 #define LibHandle void*
66 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
68 #define UnLoadLib( handle ) dlclose( handle );
71 #include "SMESH_Gen_i.hxx"
72 #include "SMESH_version.h"
74 #include "DriverMED_W_SMESHDS_Mesh.h"
75 #include "DriverMED_R_SMESHDS_Mesh.h"
77 #include "DriverCGNS_Read.hxx"
79 #include "MED_Factory.hxx"
80 #include "SMDS_EdgePosition.hxx"
81 #include "SMDS_FacePosition.hxx"
82 #include "SMDS_PolyhedralVolumeOfNodes.hxx"
83 #include "SMDS_SetIterator.hxx"
84 #include "SMDS_SpacePosition.hxx"
85 #include "SMDS_VertexPosition.hxx"
86 #include "SMESHDS_Document.hxx"
87 #include "SMESHDS_Group.hxx"
88 #include "SMESHDS_GroupOnGeom.hxx"
89 #include "SMESH_Algo_i.hxx"
90 #include "SMESH_File.hxx"
91 #include "SMESH_Group.hxx"
92 #include "SMESH_Group_i.hxx"
93 #include "SMESH_Hypothesis.hxx"
94 #include "SMESH_Hypothesis_i.hxx"
95 #include "SMESH_Mesh.hxx"
96 #include "SMESH_MeshEditor.hxx"
97 #include "SMESH_Mesh_i.hxx"
98 #include "SMESH_PreMeshInfo.hxx"
99 #include "SMESH_PythonDump.hxx"
100 #include "SMESH_ControlsDef.hxx"
101 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
103 #include CORBA_SERVER_HEADER(SMESH_Group)
104 #include CORBA_SERVER_HEADER(SMESH_Filter)
105 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
108 #include <GEOM_Client.hxx>
110 #include <Basics_Utils.hxx>
111 #include <Basics_DirUtils.hxx>
113 #include <OpUtil.hxx>
114 #include <SALOMEDS_Tool.hxx>
115 #include <SALOME_Container_i.hxx>
116 #include <SALOME_LifeCycleCORBA.hxx>
117 #include <SALOME_NamingService.hxx>
118 #include <Utils_CorbaException.hxx>
119 #include <Utils_ExceptHandlers.hxx>
120 #include <Utils_SINGLETON.hxx>
121 #include <utilities.h>
123 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
124 #include CORBA_CLIENT_HEADER(SALOME_Session)
126 // helpers about SALOME::GenericObj
127 #include <SALOMEDS_wrap.hxx>
128 #include <SALOMEDS_Attributes_wrap.hxx>
129 #include <GEOM_wrap.hxx>
137 using SMESH::TPythonDump;
140 #define NUM_TMP_FILES 2
143 static int MYDEBUG = 0;
145 static int MYDEBUG = 0;
148 // Static variables definition
149 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
150 CORBA::ORB_var SMESH_Gen_i::myOrb;
151 PortableServer::POA_var SMESH_Gen_i::myPoa;
152 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
153 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
154 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
157 const int nbElemPerDiagonal = 10;
159 //=============================================================================
161 * GetServant [ static ]
163 * Get servant of the CORBA object
165 //=============================================================================
167 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
169 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
172 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
176 INFOS( "GetServant - Unknown exception was caught!!!" );
181 //=============================================================================
183 * SObjectToObject [ static ]
185 * Get CORBA object corresponding to the SALOMEDS::SObject
187 //=============================================================================
189 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
191 SALOMEDS::GenericAttribute_wrap anAttr;
192 CORBA::Object_var anObj;
193 if ( !theSObject->_is_nil() ) {
195 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
196 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
197 CORBA::String_var aValue = anIOR->Value();
198 if( strcmp( aValue, "" ) != 0 )
199 anObj = GetORB()->string_to_object( aValue );
203 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
209 //=============================================================================
213 * Get SALOME_NamingService object
215 //=============================================================================
217 SALOME_NamingService* SMESH_Gen_i::GetNS()
219 if ( myNS == NULL ) {
220 myNS = SINGLETON_<SALOME_NamingService>::Instance();
221 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
222 myNS->init_orb( GetORB() );
227 //=============================================================================
231 * Get SALOME_LifeCycleCORBA object
233 //=============================================================================
234 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
235 if ( myLCC == NULL ) {
236 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
242 //=============================================================================
244 * GetGeomEngine [ static ]
246 * Get GEOM::GEOM_Gen reference
248 //=============================================================================
249 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
250 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
251 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
252 //CCRT return aGeomEngine._retn();
253 if(CORBA::is_nil(myGeomGen))
255 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
256 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
261 //=============================================================================
263 * SMESH_Gen_i::SMESH_Gen_i
265 * Default constructor: not for use
267 //=============================================================================
269 SMESH_Gen_i::SMESH_Gen_i()
273 //=============================================================================
275 * SMESH_Gen_i::SMESH_Gen_i
277 * Standard constructor, used with Container
279 //=============================================================================
281 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
282 PortableServer::POA_ptr poa,
283 PortableServer::ObjectId* contId,
284 const char* instanceName,
285 const char* interfaceName )
286 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
289 myOrb = CORBA::ORB::_duplicate(orb);
290 myPoa = PortableServer::POA::_duplicate(poa);
293 _id = myPoa->activate_object( _thisObj );
295 myIsEmbeddedMode = false;
296 myShapeReader = NULL; // shape reader
298 myIsHistoricalPythonDump = true;
299 myToForgetMeshDataOnHypModif = false;
301 // set it in standalone mode only
302 //OSD::SetSignal( true );
304 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
305 // find out mode (embedded or standalone) here else
306 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
307 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
308 if ( SALOME_NamingService* ns = GetNS() )
310 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
311 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
312 if ( !session->_is_nil() )
314 CORBA::String_var str_host = session->getHostname();
315 CORBA::Long s_pid = session->getPID();
316 string my_host = Kernel_Utils::GetHostname();
318 long my_pid = (long)_getpid();
320 long my_pid = (long) getpid();
322 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
327 //=============================================================================
329 * SMESH_Gen_i::~SMESH_Gen_i
333 //=============================================================================
335 SMESH_Gen_i::~SMESH_Gen_i()
337 // delete hypothesis creators
338 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
339 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
341 // same creator can be mapped under different names
342 GenericHypothesisCreator_i* creator = (*itHyp).second;
346 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
347 if ( creator == (*itHyp2).second )
348 (*itHyp2).second = 0;
350 myHypCreatorMap.clear();
352 // Clear study contexts data
353 map<int, StudyContext*>::iterator it;
354 for ( it = myStudyContextMap.begin(); it != myStudyContextMap.end(); ++it ) {
357 myStudyContextMap.clear();
358 // delete shape reader
360 delete myShapeReader;
362 //=============================================================================
364 * SMESH_Gen_i::getHypothesisCreator
366 * Get hypothesis creator
368 //=============================================================================
369 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
370 const char* theLibName,
371 std::string& thePlatformLibName)
372 throw (SALOME::SALOME_Exception)
374 std::string aPlatformLibName;
375 /* It's Need to tranlate lib name for WIN32 or X platform */
376 if ( theLibName && theLibName[0] != '\0' )
378 int libNameLen = strlen(theLibName);
379 //check for old format "libXXXXXXX.so"
380 if (libNameLen > 7 &&
381 !strncmp( theLibName, "lib", 3 ) &&
382 !strcmp( theLibName+libNameLen-3, ".so" ))
386 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
388 aPlatformLibName = theLibName;
393 //try to use new format
395 aPlatformLibName = theLibName;
396 aPlatformLibName += ".dll";
398 aPlatformLibName = "lib" + std::string( theLibName ) + ".so";
402 thePlatformLibName = aPlatformLibName;
404 Unexpect aCatch(SALOME_SalomeException);
405 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
407 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
408 GenericHypothesisCreator_i* aCreator;
411 // check, if creator for this hypothesis type already exists
412 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
414 // load plugin library
415 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
416 LibHandle libHandle = LoadLib( aPlatformLibName.c_str() );
419 // report any error, if occured
421 const char* anError = dlerror();
422 throw(SALOME_Exception(anError));
424 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
428 // get method, returning hypothesis creator
429 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
430 GetHypothesisCreator procHandle =
431 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
434 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
435 UnLoadLib(libHandle);
438 // get hypothesis creator
439 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
440 aCreator = procHandle(theHypName);
443 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
445 // map hypothesis creator to a hypothesis name
446 myHypCreatorMap[string(theHypName)] = aCreator;
451 return myHypCreatorMap[string(theHypName)];
454 catch (SALOME_Exception& S_ex)
456 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
461 //=============================================================================
463 * SMESH_Gen_i::createHypothesis
465 * Create hypothesis of given type
467 //=============================================================================
468 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
469 const char* theLibName)
471 SMESH_Hypothesis_i* myHypothesis_i = 0;
472 SMESH::SMESH_Hypothesis_var hypothesis_i;
473 std::string aPlatformLibName;
474 GenericHypothesisCreator_i* aCreator =
475 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
477 // create a new hypothesis object, store its ref. in studyContext
478 myHypothesis_i = aCreator->Create(myPoa, GetCurrentStudyID(), &myGen);
481 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
482 CORBA::String_var hypName = myHypothesis_i->GetName();
483 myHypCreatorMap[ hypName.in() ] = aCreator;
485 // activate the CORBA servant of hypothesis
486 hypothesis_i = myHypothesis_i->_this();
487 int nextId = RegisterObject( hypothesis_i );
488 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
489 else { nextId = 0; } // avoid "unused variable" warning in release mode
491 return hypothesis_i._retn();
494 //=============================================================================
496 * SMESH_Gen_i::createMesh
498 * Create empty mesh on shape
500 //=============================================================================
501 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
502 throw ( SALOME::SALOME_Exception )
504 Unexpect aCatch(SALOME_SalomeException);
505 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
507 // Get or create the GEOM_Client instance
509 // create a new mesh object servant, store it in a map in study context
510 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this, GetCurrentStudyID() );
511 // create a new mesh object
512 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
513 meshServant->SetImpl( myGen.CreateMesh( GetCurrentStudyID(), myIsEmbeddedMode ));
515 // activate the CORBA servant of Mesh
516 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
517 int nextId = RegisterObject( mesh );
518 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
519 else { nextId = 0; } // avoid "unused variable" warning in release mode
522 catch (SALOME_Exception& S_ex) {
523 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
525 return SMESH::SMESH_Mesh::_nil();
528 //=============================================================================
530 * SMESH_Gen_i::GetShapeReader
534 //=============================================================================
535 GEOM_Client* SMESH_Gen_i::GetShapeReader()
537 // create shape reader if necessary
538 if ( !myShapeReader )
539 myShapeReader = new GEOM_Client(GetContainerRef());
540 ASSERT( myShapeReader );
541 return myShapeReader;
544 //=============================================================================
546 * SMESH_Gen_i::SetGeomEngine
548 * Set GEOM::GEOM_Gen reference
550 //=============================================================================
551 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
552 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
554 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
555 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
556 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
560 //=============================================================================
562 * SMESH_Gen_i::SetEmbeddedMode
566 //=============================================================================
568 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
570 myIsEmbeddedMode = theMode;
572 if ( !myIsEmbeddedMode ) {
573 //PAL10867: disable signals catching with "noexcepthandler" option
574 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
575 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
580 char* envDisableFPE = getenv("DISABLE_FPE");
581 if (envDisableFPE && atoi(envDisableFPE))
586 OSD::SetSignal( raiseFPE );
588 // else OSD::SetSignal() is called in GUI
592 //=============================================================================
594 * SMESH_Gen_i::IsEmbeddedMode
598 //=============================================================================
600 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
602 return myIsEmbeddedMode;
605 //=============================================================================
607 * SMESH_Gen_i::SetCurrentStudy
611 //=============================================================================
613 void SMESH_Gen_i::SetCurrentStudy( SALOMEDS::Study_ptr theStudy )
615 setCurrentStudy( theStudy );
618 void SMESH_Gen_i::setCurrentStudy( SALOMEDS::Study_ptr theStudy,
619 bool theStudyIsBeingClosed)
621 int curStudyId = GetCurrentStudyID();
622 myCurrentStudy = SALOMEDS::Study::_duplicate( theStudy );
623 // create study context, if it doesn't exist and set current study
624 int studyId = GetCurrentStudyID();
625 if ( myStudyContextMap.find( studyId ) == myStudyContextMap.end() )
626 myStudyContextMap[ studyId ] = new StudyContext;
628 // myCurrentStudy may be nil
629 if ( !theStudyIsBeingClosed && !CORBA::is_nil( myCurrentStudy ) ) {
630 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
631 SALOMEDS::SComponent_wrap GEOM_var = myCurrentStudy->FindComponent( "GEOM" );
632 if( !GEOM_var->_is_nil() )
633 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
634 // NPAL16168, issue 0020210
635 // Let meshes update their data depending on GEOM groups that could change
636 if ( curStudyId != studyId )
638 CORBA::String_var compDataType = ComponentDataType();
639 SALOMEDS::SComponent_wrap me = myCurrentStudy->FindComponent( compDataType.in() );
640 if ( !me->_is_nil() ) {
641 SALOMEDS::ChildIterator_wrap anIter = myCurrentStudy->NewChildIterator( me );
642 for ( ; anIter->More(); anIter->Next() ) {
643 SALOMEDS::SObject_wrap so = anIter->Value();
644 CORBA::Object_var ior = SObjectToObject( so );
645 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
646 mesh->CheckGeomModif();
653 //=============================================================================
655 * SMESH_Gen_i::GetCurrentStudy
659 //=============================================================================
661 SALOMEDS::Study_ptr SMESH_Gen_i::GetCurrentStudy()
663 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetCurrentStudy: study Id = " << GetCurrentStudyID() );
664 if ( GetCurrentStudyID() < 0 )
665 return SALOMEDS::Study::_nil();
666 return SALOMEDS::Study::_duplicate( myCurrentStudy );
669 //=============================================================================
671 * SMESH_Gen_i::GetCurrentStudyContext
673 * Get current study context
675 //=============================================================================
676 StudyContext* SMESH_Gen_i::GetCurrentStudyContext()
678 if ( !CORBA::is_nil( myCurrentStudy ) &&
679 myStudyContextMap.find( GetCurrentStudyID() ) != myStudyContextMap.end() )
680 return myStudyContextMap[ myCurrentStudy->StudyId() ];
685 //=============================================================================
687 * SMESH_Gen_i::CreateHypothesis
689 * Create hypothesis/algorothm of given type and publish it in the study
691 //=============================================================================
693 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
694 const char* theLibName )
695 throw ( SALOME::SALOME_Exception )
697 Unexpect aCatch(SALOME_SalomeException);
698 // Create hypothesis/algorithm
699 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
701 // Publish hypothesis/algorithm in the study
702 if ( CanPublishInStudy( hyp ) ) {
703 SALOMEDS::SObject_wrap aSO = PublishHypothesis( myCurrentStudy, hyp );
704 if ( !aSO->_is_nil() ) {
705 // Update Python script
706 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
707 << theHypName << "', '" << theLibName << "')";
714 //================================================================================
716 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
717 * existing on the given geometry or to size of the geometry.
718 * \param theHypType - hypothesis type name
719 * \param theLibName - plugin library name
720 * \param theMesh - The mesh of interest
721 * \param theGeom - The shape to get parameter values from
722 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
723 * in a study and used to compute the mesh, or a temporary one created just to pass
726 //================================================================================
728 SMESH::SMESH_Hypothesis_ptr
729 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
730 const char* theLibName,
731 SMESH::SMESH_Mesh_ptr theMesh,
732 GEOM::GEOM_Object_ptr theGeom,
733 CORBA::Boolean byMesh)
734 throw ( SALOME::SALOME_Exception )
736 Unexpect aCatch(SALOME_SalomeException);
737 if ( byMesh && CORBA::is_nil( theMesh ) )
738 return SMESH::SMESH_Hypothesis::_nil();
739 if ( byMesh && CORBA::is_nil( theGeom ) )
740 return SMESH::SMESH_Hypothesis::_nil();
742 // -----------------------------------------------
743 // find hypothesis used to mesh theGeom
744 // -----------------------------------------------
746 // get mesh and shape
747 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
748 TopoDS_Shape shape = GeomObjectToShape( theGeom );
749 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
750 return SMESH::SMESH_Hypothesis::_nil();
751 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
753 // create a temporary hypothesis to know its dimension
754 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
755 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
757 return SMESH::SMESH_Hypothesis::_nil();
758 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
761 // look for a hypothesis of theHypType used to mesh the shape
762 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
765 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
766 int nbLocalHyps = aHypList->length();
767 for ( int i = 0; i < nbLocalHyps; i++ ) {
768 CORBA::String_var hypName = aHypList[i]->GetName();
769 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
770 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
772 // check super shapes
773 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
774 while ( nbLocalHyps == 0 && itShape.More() ) {
775 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
776 if ( ! CORBA::is_nil( geomObj )) {
777 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
778 nbLocalHyps = aHypList->length();
779 for ( int i = 0; i < nbLocalHyps; i++ )
780 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
781 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
787 // let the temporary hypothesis find out somehow parameter values by mesh
788 if ( hyp->SetParametersByMesh( mesh, shape ))
789 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
794 diagonal = mesh->GetShapeDiagonalSize();
796 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
797 ::SMESH_Hypothesis::TDefaults dflts;
798 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
799 dflts._nbSegments = myGen.GetDefaultNbSegments();
800 dflts._shape = &shape;
801 // let the temporary hypothesis initialize it's values
802 if ( hyp->SetParametersByDefaults( dflts, mesh ))
803 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
806 return SMESH::SMESH_Hypothesis::_nil();
809 //=============================================================================
811 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
812 * \param [in] theHyp - the hypothesis of interest
813 * \param [out] theMesh - the sole mesh using \a theHyp
814 * \param [out] theShape - the sole geometry \a theHyp is assigned to
815 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
817 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
818 * considered as SAME sub-mesh => result is \c true.
819 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
820 * a shape to which an hyp being edited is assigned.
822 //=============================================================================
824 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
825 SMESH::SMESH_Mesh_out theMesh,
826 GEOM::GEOM_Object_out theShape)
828 if ( GetCurrentStudyID() < 0 || CORBA::is_nil( theHyp ))
831 // get Mesh component SO
832 CORBA::String_var compDataType = ComponentDataType();
833 SALOMEDS::SComponent_wrap comp = myCurrentStudy->FindComponent( compDataType.in() );
834 if ( CORBA::is_nil( comp ))
837 // look for child SO of meshes
838 SMESH::SMESH_Mesh_var foundMesh;
839 TopoDS_Shape foundShape;
841 SALOMEDS::ChildIterator_wrap meshIter = myCurrentStudy->NewChildIterator( comp );
842 for ( ; meshIter->More() && isSole; meshIter->Next() )
844 SALOMEDS::SObject_wrap curSO = meshIter->Value();
845 CORBA::Object_var obj = SObjectToObject( curSO );
846 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
850 // look for a sole shape where theHyp is assigned
851 bool isHypFound = false;
852 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
853 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
854 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
856 const THypList& hyps = s2hypsIt.Value();
857 THypList::const_iterator h = hyps.begin();
858 for ( ; h != hyps.end(); ++h )
859 if ( (*h)->GetID() == theHyp->GetId() )
861 if ( h != hyps.end()) // theHyp found
864 if ( ! foundShape.IsNull() &&
865 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
867 foundShape.Nullify();
871 foundShape = s2hypsIt.Key();
873 } // loop on assigned hyps
875 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
877 if ( !foundMesh->_is_nil() ) // not a sole mesh
879 if ( !foundMesh->HasShapeToMesh() ||
880 !mesh_i ->HasShapeToMesh() )
882 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
886 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
887 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
888 isSole = s1->IsSame( s2 );
891 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
897 ! foundMesh->_is_nil() &&
898 ! foundShape.IsNull() )
900 theMesh = foundMesh._retn();
901 theShape = ShapeToGeomObject( foundShape );
902 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
907 //=============================================================================
909 * Sets number of segments per diagonal of boundary box of geometry by which
910 * default segment length of appropriate 1D hypotheses is defined
912 //=============================================================================
914 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
915 throw ( SALOME::SALOME_Exception )
917 if ( theNbSegments > 0 )
918 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
920 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
922 //=============================================================================
924 * \brief Sets default number of segments per edge
926 //=============================================================================
927 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
928 throw ( SALOME::SALOME_Exception )
930 if ( theNbSegments > 0 )
931 myGen.SetDefaultNbSegments( int(theNbSegments) );
933 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
936 //=============================================================================
940 //=============================================================================
942 void SMESH_Gen_i::SetOption(const char* name, const char* value)
944 if ( name && value && strlen( value ) > 0 )
947 if ( strcmp(name, "historical_python_dump") == 0 )
949 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
950 msgToGUI = "preferences/SMESH/historical_python_dump/";
951 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
953 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
955 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
956 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
957 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
959 else if ( strcmp(name, "default_grp_color") == 0 )
963 // color must be presented as a string of following form:
964 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
966 for ( size_t i = 0; i < str.length()/2; i++ )
967 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
968 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
970 else if ( value ) { // rgb color ("255,170,0", for example)
971 string tempValue( value );
972 char* colorValue = strtok( &tempValue[0], "," );
973 while ( colorValue != NULL ) {
974 int c_value = atoi( colorValue );
975 if ( c_value >= 0 && c_value <= 255 )
976 color.push_back( c_value );
977 colorValue = strtok( NULL, "," );
980 if ( color.size() == 3 ) { // color must have three valid component
981 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
982 myDefaultGroupColor = value;
983 msgToGUI = "preferences/SMESH/default_grp_color/";
988 // update preferences in case if SetOption() is invoked from python console
989 if ( !msgToGUI.empty() )
991 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
992 SALOME::Session_var session = SALOME::Session::_narrow( obj );
993 if ( !CORBA::is_nil( session ) )
994 session->emitMessageOneWay(msgToGUI.c_str());
999 //=============================================================================
1001 Return an option value
1003 //=============================================================================
1005 char* SMESH_Gen_i::GetOption(const char* name)
1009 if ( strcmp(name, "historical_python_dump") == 0 )
1011 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1013 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1015 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1017 if ( strcmp(name, "default_grp_color") == 0 )
1019 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1022 return CORBA::string_dup( "" );
1025 //=============================================================================
1027 * SMESH_Gen_i::CreateMesh
1029 * Create empty mesh on a shape and publish it in the study
1031 //=============================================================================
1033 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1034 throw ( SALOME::SALOME_Exception )
1036 Unexpect aCatch(SALOME_SalomeException);
1037 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1039 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1041 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1042 ASSERT( meshServant );
1043 meshServant->SetShape( theShapeObject );
1045 // publish mesh in the study
1046 if ( CanPublishInStudy( mesh ) ) {
1047 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1048 aStudyBuilder->NewCommand(); // There is a transaction
1049 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1050 aStudyBuilder->CommitCommand();
1051 if ( !aSO->_is_nil() ) {
1052 // Update Python script
1053 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1057 return mesh._retn();
1060 //=============================================================================
1062 * SMESH_Gen_i::CreateEmptyMesh
1066 //=============================================================================
1068 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1069 throw ( SALOME::SALOME_Exception )
1071 Unexpect aCatch(SALOME_SalomeException);
1072 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1074 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1076 // publish mesh in the study
1077 if ( CanPublishInStudy( mesh ) ) {
1078 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1079 aStudyBuilder->NewCommand(); // There is a transaction
1080 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, mesh.in() );
1081 aStudyBuilder->CommitCommand();
1082 if ( !aSO->_is_nil() ) {
1083 // Update Python script
1084 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1088 return mesh._retn();
1093 //================================================================================
1095 * \brief Throws an exception in case if the file can't be read
1097 //================================================================================
1099 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1101 SMESH_File f ( theFileName );
1104 if ( !f.error().empty() )
1105 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1107 THROW_SALOME_CORBA_EXCEPTION
1108 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1109 SALOME::BAD_PARAM );
1114 //=============================================================================
1116 * SMESH_Gen_i::CreateMeshFromUNV
1118 * Create mesh and import data from UNV file
1120 //=============================================================================
1122 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1123 throw ( SALOME::SALOME_Exception )
1125 Unexpect aCatch(SALOME_SalomeException);
1127 checkFileReadable( theFileName );
1129 SMESH::SMESH_Mesh_var aMesh = createMesh();
1131 // publish mesh in the study
1132 if ( CanPublishInStudy( aMesh ) ) {
1133 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1134 aStudyBuilder->NewCommand(); // There is a transaction
1135 SALOMEDS::SObject_wrap aSO = PublishMesh( myCurrentStudy, aMesh.in(), aFileName.c_str() );
1136 aStudyBuilder->CommitCommand();
1137 if ( !aSO->_is_nil() ) {
1138 // Update Python script
1139 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1143 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1145 aServant->ImportUNVFile( theFileName );
1147 // Dump creation of groups
1148 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1150 aServant->GetImpl().GetMeshDS()->Modified();
1151 return aMesh._retn();
1154 //=============================================================================
1156 * SMESH_Gen_i::CreateMeshFromMED
1158 * Create mesh and import data from MED file
1160 //=============================================================================
1162 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1163 SMESH::DriverMED_ReadStatus& theStatus,
1164 const char* theCommandNameForPython,
1165 const char* theFileNameForPython)
1168 char bname[ _MAX_FNAME ];
1169 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1170 string aFileName = bname;
1172 string aFileName = basename( theFileNameForPython );
1174 // Retrieve mesh names from the file
1175 DriverMED_R_SMESHDS_Mesh myReader;
1176 myReader.SetFile( theFileName );
1177 myReader.SetMeshId( -1 );
1178 Driver_Mesh::Status aStatus;
1179 list<string> aNames = myReader.GetMeshNames(aStatus);
1180 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1181 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1183 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1186 TPythonDump aPythonDump;
1187 aPythonDump << "([";
1189 if (theStatus == SMESH::DRS_OK) {
1190 SALOMEDS::StudyBuilder_var aStudyBuilder;
1191 if ( GetCurrentStudyID() > -1 )
1193 aStudyBuilder = myCurrentStudy->NewBuilder();
1194 aStudyBuilder->NewCommand(); // There is a transaction
1196 aResult->length( aNames.size() );
1199 // Iterate through all meshes and create mesh objects
1200 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1203 if (i > 0) aPythonDump << ", ";
1206 SMESH::SMESH_Mesh_var mesh = createMesh();
1208 // publish mesh in the study
1209 SALOMEDS::SObject_wrap aSO;
1210 if ( CanPublishInStudy( mesh ) )
1211 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1212 // - as names of meshes are stored in MED file, we use them for data publishing
1213 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1214 aSO = PublishMesh( myCurrentStudy, mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1215 if ( !aSO->_is_nil() ) {
1220 aPythonDump << "mesh_" << i;
1223 // Read mesh data (groups are published automatically by ImportMEDFile())
1224 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1225 ASSERT( meshServant );
1226 SMESH::DriverMED_ReadStatus status1 =
1227 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1228 if (status1 > theStatus)
1229 theStatus = status1;
1231 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1232 meshServant->GetImpl().GetMeshDS()->Modified();
1234 if ( !aStudyBuilder->_is_nil() )
1235 aStudyBuilder->CommitCommand();
1238 // Update Python script
1239 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1241 // Dump creation of groups
1242 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1243 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1245 return aResult._retn();
1248 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1249 SMESH::DriverMED_ReadStatus& theStatus)
1250 throw ( SALOME::SALOME_Exception )
1252 Unexpect aCatch(SALOME_SalomeException);
1253 checkFileReadable( theFileName );
1255 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1259 //=============================================================================
1261 * SMESH_Gen_i::CreateMeshFromSAUV
1263 * Create mesh and import data from SAUV file
1265 //=============================================================================
1267 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1268 SMESH::DriverMED_ReadStatus& theStatus)
1269 throw ( SALOME::SALOME_Exception )
1271 Unexpect aCatch(SALOME_SalomeException);
1272 checkFileReadable( theFileName );
1274 std::string sauvfilename(theFileName);
1275 std::string medfilename(theFileName);
1276 medfilename += ".med";
1279 cmd = "%PYTHONBIN% ";
1284 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1286 system(cmd.c_str());
1287 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1289 cmd = "%PYTHONBIN% ";
1294 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1296 system(cmd.c_str());
1300 //=============================================================================
1302 * SMESH_Gen_i::CreateMeshFromSTL
1304 * Create mesh and import data from STL file
1306 //=============================================================================
1308 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1309 throw ( SALOME::SALOME_Exception )
1311 Unexpect aCatch(SALOME_SalomeException);
1312 checkFileReadable( theFileName );
1314 SMESH::SMESH_Mesh_var aMesh = createMesh();
1317 char bname[ _MAX_FNAME ];
1318 _splitpath( theFileName, NULL, NULL, bname, NULL );
1319 string aFileName = bname;
1321 string aFileName = basename( theFileName );
1323 // publish mesh in the study
1324 if ( CanPublishInStudy( aMesh ) ) {
1325 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1326 aStudyBuilder->NewCommand(); // There is a transaction
1327 SALOMEDS::SObject_wrap aSO = PublishInStudy
1328 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1329 aStudyBuilder->CommitCommand();
1330 if ( !aSO->_is_nil() ) {
1331 // Update Python script
1332 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1336 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1338 aServant->ImportSTLFile( theFileName );
1339 aServant->GetImpl().GetMeshDS()->Modified();
1340 return aMesh._retn();
1343 //================================================================================
1345 * \brief Create meshes and import data from the CGSN file
1347 //================================================================================
1349 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1350 SMESH::DriverMED_ReadStatus& theStatus)
1351 throw ( SALOME::SALOME_Exception )
1353 Unexpect aCatch(SALOME_SalomeException);
1354 checkFileReadable( theFileName );
1356 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1359 // Retrieve nb meshes from the file
1360 DriverCGNS_Read myReader;
1361 myReader.SetFile( theFileName );
1362 Driver_Mesh::Status aStatus;
1363 int nbMeshes = myReader.GetNbMeshes(aStatus);
1364 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1366 aResult->length( nbMeshes );
1368 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1371 TPythonDump aPythonDump;
1372 aPythonDump << "([";
1374 if (theStatus == SMESH::DRS_OK)
1376 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1377 aStudyBuilder->NewCommand(); // There is a transaction
1381 // Iterate through all meshes and create mesh objects
1382 for ( ; i < nbMeshes; ++i )
1385 if (i > 0) aPythonDump << ", ";
1388 SMESH::SMESH_Mesh_var mesh = createMesh();
1389 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1391 // Read mesh data (groups are published automatically by ImportMEDFile())
1392 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1393 ASSERT( meshServant );
1395 SMESH::DriverMED_ReadStatus status1 =
1396 meshServant->ImportCGNSFile( theFileName, i, meshName );
1397 if (status1 > theStatus)
1398 theStatus = status1;
1400 meshServant->GetImpl().GetMeshDS()->Modified();
1401 // publish mesh in the study
1402 SALOMEDS::SObject_wrap aSO;
1403 if ( CanPublishInStudy( mesh ) )
1404 aSO = PublishMesh( myCurrentStudy, mesh.in(), meshName.c_str() );
1407 if ( !aSO->_is_nil() ) {
1411 aPythonDump << "mesh_" << i;
1414 aStudyBuilder->CommitCommand();
1417 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1419 // Dump creation of groups
1420 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1421 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1423 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1426 return aResult._retn();
1429 //================================================================================
1431 * \brief Create a mesh and import data from a GMF file
1433 //================================================================================
1435 SMESH::SMESH_Mesh_ptr
1436 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1437 CORBA::Boolean theMakeRequiredGroups,
1438 SMESH::ComputeError_out theError)
1439 throw ( SALOME::SALOME_Exception )
1441 Unexpect aCatch(SALOME_SalomeException);
1442 checkFileReadable( theFileName );
1444 SMESH::SMESH_Mesh_var aMesh = createMesh();
1446 char bname[ _MAX_FNAME ];
1447 _splitpath( theFileName, NULL, NULL, bname, NULL );
1448 string aFileName = bname;
1450 string aFileName = basename( theFileName );
1452 // publish mesh in the study
1453 if ( CanPublishInStudy( aMesh ) ) {
1454 SALOMEDS::StudyBuilder_var aStudyBuilder = myCurrentStudy->NewBuilder();
1455 aStudyBuilder->NewCommand(); // There is a transaction
1456 SALOMEDS::SObject_wrap aSO = PublishInStudy
1457 ( myCurrentStudy, SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1458 aStudyBuilder->CommitCommand();
1459 if ( !aSO->_is_nil() ) {
1460 // Update Python script
1461 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1462 << theFileName << "', "
1463 << theMakeRequiredGroups << " )";
1466 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1468 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1469 aServant->GetImpl().GetMeshDS()->Modified();
1470 return aMesh._retn();
1474 //=============================================================================
1476 * SMESH_Gen_i::IsReadyToCompute
1478 * Returns true if mesh contains enough data to be computed
1480 //=============================================================================
1482 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1483 GEOM::GEOM_Object_ptr theShapeObject )
1484 throw ( SALOME::SALOME_Exception )
1486 Unexpect aCatch(SALOME_SalomeException);
1487 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1489 if ( CORBA::is_nil( theShapeObject ) )
1490 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1491 SALOME::BAD_PARAM );
1493 if ( CORBA::is_nil( theMesh ) )
1494 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1495 SALOME::BAD_PARAM );
1499 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1500 ASSERT( meshServant );
1501 if ( meshServant ) {
1502 // get local TopoDS_Shape
1503 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1504 // call implementation
1505 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1506 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1509 catch ( SALOME_Exception& S_ex ) {
1510 INFOS( "catch exception "<< S_ex.what() );
1515 //================================================================================
1517 * \brief Find SObject for an algo
1519 //================================================================================
1521 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1524 if ( !myCurrentStudy->_is_nil() ) {
1525 // find algo in the study
1526 CORBA::String_var compDataType = ComponentDataType();
1527 SALOMEDS::SComponent_wrap father = myCurrentStudy->FindComponent( compDataType.in() );
1528 if ( !father->_is_nil() ) {
1529 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( father );
1530 for ( ; itBig->More(); itBig->Next() ) {
1531 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1532 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1533 SALOMEDS::ChildIterator_wrap algoIt = myCurrentStudy->NewChildIterator( gotBranch );
1534 for ( ; algoIt->More(); algoIt->Next() ) {
1535 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1536 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1537 if ( !CORBA::is_nil( algoIOR )) {
1538 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1539 if ( impl && impl->GetImpl() == algo )
1540 return algoSO._retn();
1542 } // loop on algo SO's
1545 } // SMESH component iterator
1549 return SALOMEDS::SObject::_nil();
1552 //================================================================================
1554 * \brief Return errors of mesh computation
1556 //================================================================================
1558 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1559 GEOM::GEOM_Object_ptr theSubObject )
1560 throw ( SALOME::SALOME_Exception )
1562 Unexpect aCatch(SALOME_SalomeException);
1563 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1565 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1566 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1568 if ( CORBA::is_nil( theMesh ) )
1569 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1571 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1573 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1576 if(theMesh->HasShapeToMesh())
1577 shape = GeomObjectToShape( theSubObject );
1579 shape = SMESH_Mesh::PseudoShape();
1581 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1583 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1586 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1587 const bool includeSelf = true, complexShapeFirst = true;
1588 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1590 while ( smIt->more() )
1593 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1595 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1596 if ( error && !error->IsOK() )
1598 if ( !( error->myAlgo ) &&
1599 !( error->myAlgo = sm->GetAlgo() ))
1601 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1602 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1603 errStruct.comment = error->myComment.c_str();
1604 errStruct.subShapeID = sm->GetId();
1605 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1606 if ( !algoSO->_is_nil() ) {
1607 CORBA::String_var algoName = algoSO->GetName();
1608 errStruct.algoName = algoName;
1611 errStruct.algoName = error->myAlgo->GetName();
1613 errStruct.hasBadMesh = !error->myBadElements.empty();
1616 error_array->length( nbErr );
1619 catch ( SALOME_Exception& S_ex ) {
1620 INFOS( "catch exception "<< S_ex.what() );
1623 return error_array._retn();
1626 //================================================================================
1628 * \brief Return mesh elements preventing computation of a subshape
1630 //================================================================================
1632 SMESH::MeshPreviewStruct*
1633 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1634 CORBA::Short theSubShapeID )
1635 throw ( SALOME::SALOME_Exception )
1637 Unexpect aCatch(SALOME_SalomeException);
1638 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1640 if ( CORBA::is_nil( theMesh ) )
1641 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1643 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1646 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1648 // mesh implementation
1649 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1650 // submesh by subshape id
1651 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1654 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1655 if ( error && !error->myBadElements.empty())
1657 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1658 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1660 // get nodes of elements and count elements
1661 TNode2LocalIDMap mapNode2LocalID;
1662 list< TNodeLocalID > connectivity;
1663 int i, nbElements = 0, nbConnNodes = 0;
1665 list<const SMDS_MeshElement*>::iterator elemIt = error->myBadElements.begin();
1666 list<const SMDS_MeshElement*>::iterator elemEnd = error->myBadElements.end();
1667 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1669 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1670 while ( nIt->more() )
1671 connectivity.push_back
1672 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1674 // fill node coords and assign local ids to the nodes
1675 int nbNodes = mapNode2LocalID.size();
1676 result->nodesXYZ.length( nbNodes );
1677 TNodeLocalID node2ID = mapNode2LocalID.begin();
1678 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1679 node2ID->second = i;
1680 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1681 result->nodesXYZ[i].x = node->X();
1682 result->nodesXYZ[i].y = node->Y();
1683 result->nodesXYZ[i].z = node->Z();
1685 // fill connectivity
1686 result->elementConnectivities.length( nbConnNodes );
1687 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1688 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1689 result->elementConnectivities[i] = (*connIt)->second;
1691 // fill element types
1692 result->elementTypes.length( nbElements );
1693 for ( i = 0, elemIt = error->myBadElements.begin(); i <nbElements; ++i, ++elemIt )
1695 const SMDS_MeshElement* elem = *elemIt;
1696 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1697 result->elementTypes[i].isPoly = elem->IsPoly();
1698 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1704 catch ( SALOME_Exception& S_ex ) {
1705 INFOS( "catch exception "<< S_ex.what() );
1708 return result._retn();
1711 //================================================================================
1713 * \brief Create a group of elements preventing computation of a sub-shape
1715 //================================================================================
1717 SMESH::ListOfGroups*
1718 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1719 CORBA::Short theSubShapeID,
1720 const char* theGroupName )
1721 throw ( SALOME::SALOME_Exception )
1723 Unexpect aCatch(SALOME_SalomeException);
1725 SMESH::ListOfGroups_var groups;
1727 if ( CORBA::is_nil( theMesh ) )
1728 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1731 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1733 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1734 TPythonDump() << groups << " = " << this
1735 << ".MakeGroupsOfBadInputElements( "
1736 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1739 catch ( SALOME_Exception& S_ex ) {
1740 INFOS( "catch exception "<< S_ex.what() );
1742 return groups._retn();
1745 //================================================================================
1747 * \brief Returns errors of hypotheses definintion
1748 * \param theMesh - the mesh
1749 * \param theSubObject - the main or sub- shape
1750 * \retval SMESH::algo_error_array* - sequence of errors
1752 //================================================================================
1754 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1755 GEOM::GEOM_Object_ptr theSubObject )
1756 throw ( SALOME::SALOME_Exception )
1758 Unexpect aCatch(SALOME_SalomeException);
1759 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1761 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1762 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1764 if ( CORBA::is_nil( theMesh ) )
1765 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1767 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1769 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1770 ASSERT( meshServant );
1771 if ( meshServant ) {
1772 TopoDS_Shape myLocShape;
1773 if(theMesh->HasShapeToMesh())
1774 myLocShape = GeomObjectToShape( theSubObject );
1776 myLocShape = SMESH_Mesh::PseudoShape();
1778 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1779 list< ::SMESH_Gen::TAlgoStateError > error_list;
1780 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1781 // call ::SMESH_Gen::GetAlgoState()
1782 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1783 error_array->length( error_list.size() );
1785 for ( error = error_list.begin(); error != error_list.end(); ++error )
1787 // fill AlgoStateError structure
1788 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1789 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1790 errStruct.algoDim = error->_algoDim;
1791 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1792 errStruct.algoName = "";
1793 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1794 if ( !algoSO->_is_nil() ) {
1795 CORBA::String_var algoName = algoSO->GetName();
1796 errStruct.algoName = algoName.in();
1801 catch ( SALOME_Exception& S_ex ) {
1802 INFOS( "catch exception "<< S_ex.what() );
1804 return error_array._retn();
1807 //=============================================================================
1809 * SMESH_Gen_i::GetSubShapesId
1811 * Get sub-shapes unique ID's list
1813 //=============================================================================
1816 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1817 const SMESH::object_array& theListOfSubShapeObject )
1818 throw ( SALOME::SALOME_Exception )
1820 Unexpect aCatch(SALOME_SalomeException);
1821 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1823 SMESH::long_array_var shapesId = new SMESH::long_array;
1826 if ( CORBA::is_nil( theMainShapeObject ) )
1827 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1831 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1832 TopTools_IndexedMapOfShape myIndexToShape;
1833 TopExp::MapShapes(myMainShape,myIndexToShape);
1835 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1837 GEOM::GEOM_Object_var aShapeObject
1838 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1839 if ( CORBA::is_nil( aShapeObject ) )
1840 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1841 SALOME::BAD_PARAM );
1843 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1844 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1846 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1847 setId.insert(myIndexToShape.FindIndex(F));
1848 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1850 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1852 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1853 setId.insert(myIndexToShape.FindIndex(E));
1854 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1856 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1858 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1859 setId.insert(myIndexToShape.FindIndex(V));
1860 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1863 shapesId->length(setId.size());
1864 set<int>::iterator iind;
1866 for (iind = setId.begin(); iind != setId.end(); iind++)
1868 if(MYDEBUG) SCRUTE((*iind));
1869 shapesId[i] = (*iind);
1870 if(MYDEBUG) SCRUTE(shapesId[i]);
1874 catch (SALOME_Exception& S_ex)
1876 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1879 return shapesId._retn();
1882 //=============================================================================
1884 * SMESH_Gen_i::Compute
1886 * Compute mesh on a shape
1888 //=============================================================================
1890 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1891 GEOM::GEOM_Object_ptr theShapeObject )
1892 throw ( SALOME::SALOME_Exception )
1895 Unexpect aCatch(SALOME_SalomeException);
1896 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1898 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1899 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1900 SALOME::BAD_PARAM );
1902 if ( CORBA::is_nil( theMesh ) )
1903 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1904 SALOME::BAD_PARAM );
1906 // Update Python script
1907 TPythonDump() << "isDone = " << this << ".Compute( "
1908 << theMesh << ", " << theShapeObject << ")";
1912 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1913 ASSERT( meshServant );
1914 if ( meshServant ) {
1915 meshServant->Load();
1916 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
1917 meshServant->CheckGeomModif();
1918 // get local TopoDS_Shape
1919 TopoDS_Shape myLocShape;
1920 if(theMesh->HasShapeToMesh())
1921 myLocShape = GeomObjectToShape( theShapeObject );
1923 myLocShape = SMESH_Mesh::PseudoShape();
1924 // call implementation compute
1925 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1926 myGen.PrepareCompute( myLocMesh, myLocShape );
1927 int how = ::SMESH_Gen::COMPACT_MESH;
1928 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1929 how |= ::SMESH_Gen::SHAPE_ONLY;
1930 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1931 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1932 myLocMesh.GetMeshDS()->Modified();
1936 catch ( std::bad_alloc ) {
1937 INFOS( "Compute(): lack of memory" );
1939 catch ( SALOME_Exception& S_ex ) {
1940 INFOS( "Compute(): catch exception "<< S_ex.what() );
1943 INFOS( "Compute(): unknown exception " );
1948 //=============================================================================
1950 * SMESH_Gen_i::CancelCompute
1952 * Cancel Compute mesh on a shape
1954 //=============================================================================
1956 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1957 GEOM::GEOM_Object_ptr theShapeObject )
1959 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1960 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1961 TopoDS_Shape myLocShape;
1962 if(theMesh->HasShapeToMesh())
1963 myLocShape = GeomObjectToShape( theShapeObject );
1965 myLocShape = SMESH_Mesh::PseudoShape();
1966 myGen.CancelCompute( myLocMesh, myLocShape);
1969 //=============================================================================
1971 * SMESH_Gen_i::Precompute
1973 * Compute mesh as preview till indicated dimension on shape
1975 //=============================================================================
1977 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
1978 GEOM::GEOM_Object_ptr theShapeObject,
1979 SMESH::Dimension theDimension,
1980 SMESH::long_array& theShapesId)
1981 throw ( SALOME::SALOME_Exception )
1983 Unexpect aCatch(SALOME_SalomeException);
1984 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
1986 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1987 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1988 SALOME::BAD_PARAM );
1990 if ( CORBA::is_nil( theMesh ) )
1991 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1992 SALOME::BAD_PARAM );
1994 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1997 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1998 meshServant->Load();
1999 ASSERT( meshServant );
2000 if ( meshServant ) {
2001 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2002 meshServant->CheckGeomModif();
2003 // get local TopoDS_Shape
2004 TopoDS_Shape myLocShape;
2005 if(theMesh->HasShapeToMesh())
2006 myLocShape = GeomObjectToShape( theShapeObject );
2008 return result._retn();;
2010 // call implementation compute
2011 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2013 ::MeshDimension aDim = (MeshDimension)theDimension;
2014 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2016 int nbShapeId = shapeIds.size();
2017 theShapesId.length( nbShapeId );
2018 // iterates on shapes and collect mesh entities into mesh preview
2019 TSetOfInt::const_iterator idIt = shapeIds.begin();
2020 TSetOfInt::const_iterator idEnd = shapeIds.end();
2021 std::map< int, int > mapOfShIdNb;
2022 std::set< SMESH_TLink > setOfEdge;
2023 std::list< SMDSAbs_ElementType > listOfElemType;
2024 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2025 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2026 TNode2LocalIDMap mapNode2LocalID;
2027 list< TNodeLocalID > connectivity;
2028 int i, nbConnNodes = 0;
2029 std::set< const SMESH_subMesh* > setOfVSubMesh;
2030 // iterates on shapes
2031 for ( ; idIt != idEnd; idIt++ )
2033 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2035 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2036 if ( !sm || !sm->IsMeshComputed() )
2039 const TopoDS_Shape& aSh = sm->GetSubShape();
2040 const int shDim = myGen.GetShapeDim( aSh );
2041 if ( shDim < 1 || shDim > theDimension )
2044 mapOfShIdNb[ *idIt ] = 0;
2045 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2047 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2048 if ( !smDS ) continue;
2050 if ( theDimension == SMESH::DIM_2D )
2052 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2053 while ( faceIt->more() )
2055 const SMDS_MeshElement* face = faceIt->next();
2056 int aNbNode = face->NbNodes();
2058 aNbNode /= 2; // do not take into account additional middle nodes
2060 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2061 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2063 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2064 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2066 listOfElemType.push_back( SMDSAbs_Edge );
2067 connectivity.push_back
2068 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2069 connectivity.push_back
2070 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2076 else if ( theDimension == SMESH::DIM_1D )
2078 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2079 while ( nodeIt->more() )
2081 listOfElemType.push_back( SMDSAbs_Node );
2082 connectivity.push_back
2083 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2085 // add corner nodes by first vertex from edge
2086 SMESH_subMeshIteratorPtr edgeSmIt =
2087 sm->getDependsOnIterator(/*includeSelf*/false,
2088 /*complexShapeFirst*/false);
2089 while ( edgeSmIt->more() )
2091 SMESH_subMesh* vertexSM = edgeSmIt->next();
2092 // check that vertex is not already treated
2093 if ( !setOfVSubMesh.insert( vertexSM ).second )
2095 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2098 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2099 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2100 while ( nodeIt->more() )
2102 listOfElemType.push_back( SMDSAbs_Node );
2103 connectivity.push_back
2104 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2110 // fill node coords and assign local ids to the nodes
2111 int nbNodes = mapNode2LocalID.size();
2112 result->nodesXYZ.length( nbNodes );
2113 TNodeLocalID node2ID = mapNode2LocalID.begin();
2114 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2115 node2ID->second = i;
2116 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2117 result->nodesXYZ[i].x = node->X();
2118 result->nodesXYZ[i].y = node->Y();
2119 result->nodesXYZ[i].z = node->Z();
2121 // fill connectivity
2122 result->elementConnectivities.length( nbConnNodes );
2123 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2124 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2125 result->elementConnectivities[i] = (*connIt)->second;
2128 // fill element types
2129 result->elementTypes.length( listOfElemType.size() );
2130 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2131 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2132 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2134 SMDSAbs_ElementType elemType = *typeIt;
2135 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2136 result->elementTypes[i].isPoly = false;
2137 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2140 // correct number of shapes
2141 theShapesId.length( mapOfShIdNb.size() );
2145 catch ( std::bad_alloc ) {
2146 INFOS( "Precompute(): lack of memory" );
2148 catch ( SALOME_Exception& S_ex ) {
2149 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2152 INFOS( "Precompute(): unknown exception " );
2154 return result._retn();
2158 //=============================================================================
2160 * SMESH_Gen_i::Evaluate
2162 * Evaluate mesh on a shape
2164 //=============================================================================
2166 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2167 GEOM::GEOM_Object_ptr theShapeObject)
2168 // SMESH::long_array& theNbElems)
2169 throw ( SALOME::SALOME_Exception )
2171 Unexpect aCatch(SALOME_SalomeException);
2172 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2174 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2175 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2176 SALOME::BAD_PARAM );
2178 if ( CORBA::is_nil( theMesh ) )
2179 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2180 SALOME::BAD_PARAM );
2182 SMESH::long_array_var nbels = new SMESH::long_array;
2183 nbels->length(SMESH::Entity_Last);
2184 int i = SMESH::Entity_Node;
2185 for (; i < SMESH::Entity_Last; i++)
2188 // Update Python script
2189 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2190 << theMesh << ", " << theShapeObject << ")";
2194 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2195 ASSERT( meshServant );
2196 if ( meshServant ) {
2197 meshServant->Load();
2198 // NPAL16168: "geometrical group edition from a submesh don't modifiy mesh computation"
2199 meshServant->CheckGeomModif();
2200 // get local TopoDS_Shape
2201 TopoDS_Shape myLocShape;
2202 if(theMesh->HasShapeToMesh())
2203 myLocShape = GeomObjectToShape( theShapeObject );
2205 myLocShape = SMESH_Mesh::PseudoShape();
2206 // call implementation compute
2207 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2208 MapShapeNbElems aResMap;
2209 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2210 MapShapeNbElemsItr anIt = aResMap.begin();
2211 for(; anIt!=aResMap.end(); anIt++) {
2212 const vector<int>& aVec = (*anIt).second;
2213 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2214 int nbElem = aVec[i];
2215 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2217 SMESH_subMesh* sm = anIt->first;
2218 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2219 const SMESH_Algo* algo = sm->GetAlgo();
2220 if ( (algo && !error.get()) || error->IsOK() )
2221 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2225 nbels[i] += aVec[i];
2229 return nbels._retn();
2232 catch ( std::bad_alloc ) {
2233 INFOS( "Evaluate(): lack of memory" );
2235 catch ( SALOME_Exception& S_ex ) {
2236 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2239 INFOS( "Evaluate(): unknown exception " );
2242 return nbels._retn();
2245 //================================================================================
2247 * \brief Return geometrical object the given element is built on
2248 * \param theMesh - the mesh the element is in
2249 * \param theElementID - the element ID
2250 * \param theGeomName - the name of the result geom object if it is not yet published
2251 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2253 //================================================================================
2255 GEOM::GEOM_Object_ptr
2256 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2257 CORBA::Long theElementID,
2258 const char* theGeomName)
2259 throw ( SALOME::SALOME_Exception )
2261 Unexpect aCatch(SALOME_SalomeException);
2263 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2264 if ( !geom->_is_nil() ) {
2265 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2266 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2268 // try to find the corresponding SObject
2269 SALOMEDS::SObject_wrap SObj = ObjectToSObject( myCurrentStudy, geom.in() );
2270 if ( SObj->_is_nil() ) // submesh can be not found even if published
2272 // try to find published submesh
2273 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2274 if ( !geom->IsMainShape() && list->length() == 1 ) {
2275 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2276 SALOMEDS::ChildIterator_wrap it;
2277 if ( !mainSO->_is_nil() ) {
2278 it = myCurrentStudy->NewChildIterator( mainSO );
2280 if ( !it->_is_nil() ) {
2281 for ( it->InitEx(true); it->More(); it->Next() ) {
2282 SALOMEDS::SObject_wrap so = it->Value();
2283 CORBA::Object_var obj = SObjectToObject( so );
2284 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2285 if ( !subGeom->_is_nil() ) {
2286 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2287 if ( subList->length() == 1 && list[0] == subList[0] ) {
2297 if ( SObj->_is_nil() ) // publish a new subshape
2298 SObj = geomGen->AddInStudy( myCurrentStudy, geom, theGeomName, mainShape );
2300 // return only published geometry
2301 if ( !SObj->_is_nil() ) {
2302 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2303 CORBA::Object_var obj = SObjectToObject( SObj );
2304 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2308 return GEOM::GEOM_Object::_nil();
2311 //================================================================================
2313 * \brief Return geometrical object the given element is built on.
2314 * \param theMesh - the mesh the element is in
2315 * \param theElementID - the element ID
2316 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2318 //================================================================================
2320 GEOM::GEOM_Object_ptr
2321 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2322 CORBA::Long theElementID)
2323 throw ( SALOME::SALOME_Exception )
2325 Unexpect aCatch(SALOME_SalomeException);
2326 if ( CORBA::is_nil( theMesh ) )
2327 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2329 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2330 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2332 // get a core mesh DS
2333 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2334 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2336 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2337 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2338 // find the element in mesh
2339 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2340 // find a shape id by the element
2341 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2342 // get a geom object by the shape id
2343 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2344 if ( geom->_is_nil() ) {
2345 // try to find a published sub-shape
2346 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( myCurrentStudy, mainShape );
2347 SALOMEDS::ChildIterator_wrap it;
2348 if ( !mainSO->_is_nil() ) {
2349 it = myCurrentStudy->NewChildIterator( mainSO );
2351 if ( !it->_is_nil() ) {
2352 for ( it->InitEx(true); it->More(); it->Next() ) {
2353 SALOMEDS::SObject_wrap so = it->Value();
2354 CORBA::Object_var obj = SObjectToObject( so );
2355 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2356 if ( !subGeom->_is_nil() ) {
2357 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2358 if ( subList->length() == 1 && shapeID == subList[0] ) {
2366 if ( geom->_is_nil() ) {
2368 GEOM::GEOM_IShapesOperations_wrap op =
2369 geomGen->GetIShapesOperations( GetCurrentStudyID() );
2370 if ( !op->_is_nil() )
2371 geom = op->GetSubShape( mainShape, shapeID );
2376 if ( !geom->_is_nil() ) {
2377 GeomObjectToShape( geom ); // let geom client remember the found shape
2378 return geom._retn();
2383 return GEOM::GEOM_Object::_nil();
2386 //================================================================================
2388 * SMESH_Gen_i::Concatenate
2390 * Concatenate the given meshes into one mesh
2392 //================================================================================
2394 SMESH::SMESH_Mesh_ptr
2395 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2396 CORBA::Boolean theUniteIdenticalGroups,
2397 CORBA::Boolean theMergeNodesAndElements,
2398 CORBA::Double theMergeTolerance)
2399 throw ( SALOME::SALOME_Exception )
2401 return ConcatenateCommon(theMeshesArray,
2402 theUniteIdenticalGroups,
2403 theMergeNodesAndElements,
2408 //================================================================================
2410 * SMESH_Gen_i::ConcatenateWithGroups
2412 * Concatenate the given meshes into one mesh
2413 * Create the groups of all elements from initial meshes
2415 //================================================================================
2417 SMESH::SMESH_Mesh_ptr
2418 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2419 CORBA::Boolean theUniteIdenticalGroups,
2420 CORBA::Boolean theMergeNodesAndElements,
2421 CORBA::Double theMergeTolerance)
2422 throw ( SALOME::SALOME_Exception )
2424 return ConcatenateCommon(theMeshesArray,
2425 theUniteIdenticalGroups,
2426 theMergeNodesAndElements,
2431 //================================================================================
2433 * SMESH_Gen_i::ConcatenateCommon
2435 * Concatenate the given meshes into one mesh
2437 //================================================================================
2439 SMESH::SMESH_Mesh_ptr
2440 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2441 CORBA::Boolean theUniteIdenticalGroups,
2442 CORBA::Boolean theMergeNodesAndElements,
2443 CORBA::Double theMergeTolerance,
2444 CORBA::Boolean theCommonGroups)
2445 throw ( SALOME::SALOME_Exception )
2447 typedef list<SMESH::SMESH_Group_var> TListOfNewGroups;
2448 typedef map< pair<string, SMESH::ElementType>, TListOfNewGroups > TGroupsMap;
2450 TPythonDump* pPythonDump = new TPythonDump;
2451 TPythonDump& aPythonDump = *pPythonDump; // prevent dump of called methods
2454 SMESH::SMESH_Mesh_var aNewMesh = CreateEmptyMesh();
2456 if ( aNewMesh->_is_nil() )
2457 return aNewMesh._retn();
2459 SMESH_Mesh_i* aNewImpl = SMESH::DownCast<SMESH_Mesh_i*>( aNewMesh );
2461 return aNewMesh._retn();
2463 ::SMESH_Mesh& aLocMesh = aNewImpl->GetImpl();
2464 SMESHDS_Mesh* aNewMeshDS = aLocMesh.GetMeshDS();
2466 TGroupsMap aGroupsMap;
2467 TListOfNewGroups aListOfNewGroups;
2468 ::SMESH_MeshEditor aNewEditor(&aLocMesh);
2469 SMESH::ListOfGroups_var aListOfGroups;
2471 ::SMESH_MeshEditor::ElemFeatures elemType;
2472 std::vector<const SMDS_MeshNode*> aNodesArray;
2474 // loop on sub-meshes
2475 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++)
2477 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2478 SMESH::SMESH_Mesh_var anInitMesh = theMeshesArray[i]->GetMesh();
2479 if ( anInitMesh->_is_nil() ) continue;
2480 SMESH_Mesh_i* anInitImpl = SMESH::DownCast<SMESH_Mesh_i*>( anInitMesh );
2481 if ( !anInitImpl ) continue;
2484 //::SMESH_Mesh& aInitLocMesh = anInitImpl->GetImpl();
2485 //SMESHDS_Mesh* anInitMeshDS = aInitLocMesh.GetMeshDS();
2487 // remember nb of elements before filling in
2488 SMESH::long_array_var prevState = aNewMesh->GetNbElementsByType();
2490 typedef std::map<const SMDS_MeshElement*, const SMDS_MeshElement*, TIDCompare > TEEMap;
2491 TEEMap elemsMap, nodesMap;
2493 // loop on elements of a sub-mesh
2494 SMDS_ElemIteratorPtr itElems = anInitImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2495 const SMDS_MeshElement* anElem;
2496 const SMDS_MeshElement* aNewElem;
2497 const SMDS_MeshNode* aNode;
2498 const SMDS_MeshNode* aNewNode;
2501 while ( itElems->more() )
2503 anElem = itElems->next();
2504 anElemNbNodes = anElem->NbNodes();
2505 aNodesArray.resize( anElemNbNodes );
2507 // loop on nodes of an element
2508 SMDS_ElemIteratorPtr itNodes = anElem->nodesIterator();
2509 for ( int k = 0; itNodes->more(); k++)
2511 aNode = static_cast<const SMDS_MeshNode*>( itNodes->next() );
2512 TEEMap::iterator n2nnIt = nodesMap.find( aNode );
2513 if ( n2nnIt == nodesMap.end() )
2515 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2516 nodesMap.insert( make_pair( aNode, aNewNode ));
2520 aNewNode = static_cast<const SMDS_MeshNode*>( n2nnIt->second );
2522 aNodesArray[k] = aNewNode;
2525 // creates a corresponding element on existent nodes in new mesh
2526 if ( anElem->GetType() == SMDSAbs_Node )
2530 aNewEditor.AddElement( aNodesArray, elemType.Init( anElem, /*basicOnly=*/false ));
2533 elemsMap.insert( make_pair( anElem, aNewElem ));
2537 aNewEditor.ClearLastCreated(); // forget the history
2540 // create groups of just added elements
2541 SMESH::SMESH_Group_var aNewGroup;
2542 SMESH::ElementType aGroupType;
2543 if ( theCommonGroups )
2545 SMESH::long_array_var curState = aNewMesh->GetNbElementsByType();
2547 for( aGroupType = SMESH::NODE;
2548 aGroupType < SMESH::NB_ELEMENT_TYPES;
2549 aGroupType = (SMESH::ElementType)( aGroupType + 1 ))
2551 if ( curState[ aGroupType ] <= prevState[ aGroupType ])
2554 // make a group name
2555 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2556 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2557 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2558 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1];
2560 string groupName = "Gr";
2561 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, theMeshesArray[i] );
2563 CORBA::String_var name = aMeshSObj->GetName();
2567 groupName += typeNames[ aGroupType ];
2569 // make and fill a group
2570 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2571 aNewGroup = aNewImpl->CreateGroup( aGroupType, groupName.c_str() );
2572 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( aNewGroup ))
2574 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2576 TEEMap::iterator e2neIt = e2neMap.begin();
2577 for ( ; e2neIt != e2neMap.end(); ++e2neIt )
2579 aNewElem = e2neIt->second;
2580 if ( aNewElem->GetType() == grpDS->GetType() )
2582 grpDS->Add( aNewElem );
2584 if ( prevState[ aGroupType ]++ >= curState[ aGroupType ] )
2590 aListOfNewGroups.clear();
2591 aListOfNewGroups.push_back(aNewGroup);
2592 aGroupsMap.insert(make_pair( make_pair(groupName, aGroupType), aListOfNewGroups ));
2596 if ( SMESH_Mesh_i* anSrcImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2598 // copy orphan nodes
2599 if ( anSrcImpl->NbNodes() > (int)nodesMap.size() )
2601 SMDS_ElemIteratorPtr itNodes = anInitImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2602 while ( itNodes->more() )
2604 const SMDS_MeshNode* aNode = static_cast< const SMDS_MeshNode* >( itNodes->next() );
2605 if ( aNode->NbInverseElements() == 0 )
2607 aNewNode = aNewMeshDS->AddNode(aNode->X(), aNode->Y(), aNode->Z());
2608 nodesMap.insert( make_pair( aNode, aNewNode ));
2615 SMESH::SMESH_GroupBase_ptr aGroup;
2616 CORBA::String_var aGroupName;
2617 SMESH::long_array_var anNewIDs = new SMESH::long_array();
2619 // loop on groups of a source mesh
2620 aListOfGroups = anSrcImpl->GetGroups();
2621 for ( CORBA::ULong iG = 0; iG < aListOfGroups->length(); iG++ )
2623 aGroup = aListOfGroups[iG];
2624 aGroupType = aGroup->GetType();
2625 aGroupName = aGroup->GetName();
2626 string aName = aGroupName.in();
2628 // convert a list of IDs
2629 anNewIDs->length( aGroup->Size() );
2630 TEEMap & e2neMap = ( aGroupType == SMESH::NODE ) ? nodesMap : elemsMap;
2631 SMDS_ElemIteratorPtr itGrElems = anSrcImpl->GetElements( aGroup, SMESH::ALL );
2633 while ( itGrElems->more() )
2635 anElem = itGrElems->next();
2636 TEEMap::iterator e2neIt = e2neMap.find( anElem );
2637 if ( e2neIt != e2neMap.end() )
2638 anNewIDs[ iElem++ ] = e2neIt->second->GetID();
2640 anNewIDs->length( iElem );
2642 // check a current group name and type don't have identical ones in final mesh
2643 aListOfNewGroups.clear();
2644 TGroupsMap::iterator anIter = aGroupsMap.find( make_pair( aName, aGroupType ));
2645 if ( anIter == aGroupsMap.end() ) {
2646 // add a new group in the mesh
2647 aNewGroup = aNewImpl->CreateGroup( aGroupType, aGroupName.in() );
2648 // add elements into new group
2649 aNewGroup->Add( anNewIDs );
2651 aListOfNewGroups.push_back(aNewGroup);
2652 aGroupsMap.insert(make_pair( make_pair(aName, aGroupType), aListOfNewGroups ));
2655 else if ( theUniteIdenticalGroups ) {
2656 // unite identical groups
2657 TListOfNewGroups& aNewGroups = anIter->second;
2658 aNewGroups.front()->Add( anNewIDs );
2662 // rename identical groups
2663 aNewGroup = aNewImpl->CreateGroup(aGroupType, aGroupName.in());
2664 aNewGroup->Add( anNewIDs );
2666 TListOfNewGroups& aNewGroups = anIter->second;
2667 string aNewGroupName;
2668 if (aNewGroups.size() == 1) {
2669 aNewGroupName = aName + "_1";
2670 aNewGroups.front()->SetName(aNewGroupName.c_str());
2672 char aGroupNum[128];
2673 sprintf(aGroupNum, "%u", (unsigned int)aNewGroups.size()+1);
2674 aNewGroupName = aName + "_" + string(aGroupNum);
2675 aNewGroup->SetName(aNewGroupName.c_str());
2676 aNewGroups.push_back(aNewGroup);
2679 } // if an IDSource is a mesh
2682 if (theMergeNodesAndElements) // merge nodes
2684 TIDSortedNodeSet aMeshNodes; // no input nodes
2685 SMESH_MeshEditor::TListOfListOfNodes aGroupsOfNodes;
2686 aNewEditor.FindCoincidentNodes( aMeshNodes, theMergeTolerance, aGroupsOfNodes,
2687 /*SeparateCornersAndMedium=*/ false );
2688 aNewEditor.MergeNodes( aGroupsOfNodes );
2690 aNewEditor.MergeEqualElements();
2693 // Update Python script
2694 aPythonDump << aNewMesh << " = " << this << "."
2695 << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" )
2697 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++) {
2698 if (i > 0) aPythonDump << ", ";
2699 aPythonDump << theMeshesArray[i];
2701 aPythonDump << "], ";
2702 aPythonDump << theUniteIdenticalGroups << ", "
2703 << theMergeNodesAndElements << ", "
2704 << TVar( theMergeTolerance ) << ")";
2706 delete pPythonDump; // enable python dump from GetGroups()
2708 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2709 if ( !aNewMesh->_is_nil() )
2711 SMESH::ListOfGroups_var groups = aNewMesh->GetGroups();
2714 // IPAL21468 Change icon of compound because it need not be computed.
2715 SALOMEDS::SObject_wrap aMeshSObj = ObjectToSObject( myCurrentStudy, aNewMesh );
2716 SetPixMap( aMeshSObj, "ICON_SMESH_TREE_MESH" );
2719 aNewMeshDS->Modified();
2721 return aNewMesh._retn();
2724 //================================================================================
2726 * \brief Create a mesh by copying a part of another mesh
2727 * \param meshPart - a part of mesh to copy
2728 * \param toCopyGroups - to create in the new mesh groups
2729 * the copied elements belongs to
2730 * \param toKeepIDs - to preserve IDs of the copied elements or not
2731 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2733 //================================================================================
2735 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2736 const char* meshName,
2737 CORBA::Boolean toCopyGroups,
2738 CORBA::Boolean toKeepIDs)
2740 Unexpect aCatch(SALOME_SalomeException);
2742 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2744 // 1. Get source mesh
2746 if ( CORBA::is_nil( meshPart ))
2747 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2749 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2750 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2752 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2754 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2756 // 2. Make a new mesh
2758 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2759 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2761 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2762 SALOMEDS::SObject_wrap meshSO = ObjectToSObject(myCurrentStudy, newMesh );
2763 if ( !meshSO->_is_nil() )
2765 SetName( meshSO, meshName, "Mesh" );
2766 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2768 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2769 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2770 ::SMESH_MeshEditor::ElemFeatures elemType;
2772 // 3. Get elements to copy
2774 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2775 TIDSortedElemSet srcElems;
2776 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2777 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2780 srcElemIt = srcMeshDS->elementsIterator();
2781 srcNodeIt = srcMeshDS->nodesIterator();
2785 SMESH::long_array_var ids = meshPart->GetIDs();
2786 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2788 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2789 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2790 srcElems.insert( elem );
2794 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2795 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2796 srcElems.insert( elem );
2798 if ( srcElems.empty() )
2799 return newMesh._retn();
2801 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2802 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2807 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2808 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2809 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2811 const SMDS_MeshNode *nSrc, *nTgt;
2812 vector< const SMDS_MeshNode* > nodes;
2813 while ( srcElemIt->more() )
2815 const SMDS_MeshElement * elem = srcElemIt->next();
2817 nodes.resize( elem->NbNodes());
2818 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2820 for ( iN = 0; nIt->more(); ++iN )
2822 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2823 nTgt = newMeshDS->FindNode( nSrc->GetID());
2825 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2830 for ( iN = 0; nIt->more(); ++iN )
2832 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2833 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2835 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2836 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2840 if ( elem->GetType() != SMDSAbs_Node )
2842 elemType.Init( elem, /*basicOnly=*/false );
2843 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2845 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2846 if ( toCopyGroups && !toKeepIDs )
2847 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2849 } // while ( srcElemIt->more() )
2851 // 4(b). Copy free nodes
2853 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2855 while ( srcNodeIt->more() )
2857 nSrc = srcNodeIt->next();
2858 if ( nSrc->NbInverseElements() == 0 )
2861 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2863 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2870 int nbNewGroups = 0;
2873 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2874 while ( gIt->more() )
2876 SMESH_Group* group = gIt->next();
2877 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2879 // Check group type. We copy nodal groups containing nodes of copied element
2880 SMDSAbs_ElementType groupType = groupDS->GetType();
2881 if ( groupType != SMDSAbs_Node &&
2882 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2883 continue; // group type differs from types of meshPart
2885 // Find copied elements in the group
2886 vector< const SMDS_MeshElement* > groupElems;
2887 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2890 const SMDS_MeshElement* foundElem;
2891 if ( groupType == SMDSAbs_Node )
2893 while ( eIt->more() )
2894 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2895 groupElems.push_back( foundElem );
2899 while ( eIt->more() )
2900 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2901 groupElems.push_back( foundElem );
2906 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2907 if ( e2eMap.empty() ) continue;
2908 int minID = e2eMap.begin()->first->GetID();
2909 int maxID = e2eMap.rbegin()->first->GetID();
2910 TE2EMap::iterator e2e;
2911 while ( eIt->more() && groupElems.size() < e2eMap.size())
2913 const SMDS_MeshElement* e = eIt->next();
2914 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2915 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2916 groupElems.push_back( e2e->second );
2920 if ( !groupElems.empty() )
2922 SMESH::SMESH_Group_var newGroupObj =
2923 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2924 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2926 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2927 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2928 for ( unsigned i = 0; i < groupElems.size(); ++i )
2929 smdsGroup.Add( groupElems[i] );
2937 newMeshDS->Modified();
2939 *pyDump << newMesh << " = " << this
2940 << ".CopyMesh( " << meshPart << ", "
2941 << "'" << meshName << "', "
2942 << toCopyGroups << ", "
2943 << toKeepIDs << ")";
2945 delete pyDump; pyDump = 0; // allow dump in GetGroups()
2947 if ( nbNewGroups > 0 ) // dump created groups
2948 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2950 return newMesh._retn();
2953 //================================================================================
2955 * SMESH_Gen_i::GetMEDVersion
2957 * Get MED version of the file by its name
2959 //================================================================================
2960 CORBA::Boolean SMESH_Gen_i::GetMEDVersion(const char* theFileName,
2961 SMESH::MED_VERSION& theVersion)
2963 theVersion = SMESH::MED_V2_1;
2964 MED::EVersion aVersion = MED::GetVersionId( theFileName );
2965 switch( aVersion ) {
2966 case MED::eV2_1 : theVersion = SMESH::MED_V2_1; return true;
2967 case MED::eV2_2 : theVersion = SMESH::MED_V2_2; return true;
2968 case MED::eVUnknown : return false;
2973 //================================================================================
2975 * SMESH_Gen_i::GetMeshNames
2977 * Get names of meshes defined in file with the specified name
2979 //================================================================================
2980 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
2982 SMESH::string_array_var aResult = new SMESH::string_array();
2983 MED::PWrapper aMed = MED::CrWrapper( theFileName );
2985 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
2987 aResult->length( aNbMeshes );
2988 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
2989 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
2990 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
2993 return aResult._retn();
2996 //=============================================================================
3000 * Save SMESH module's data
3002 //=============================================================================
3003 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
3007 // ASSERT( theComponent->GetStudy()->StudyId() == myCurrentStudy->StudyId() )
3008 // san -- in case <myCurrentStudy> differs from theComponent's study,
3009 // use that of the component
3010 if ( theComponent->GetStudy()->StudyId() != GetCurrentStudyID() )
3011 SetCurrentStudy( theComponent->GetStudy() );
3013 // Store study contents as a set of python commands
3014 SavePython(myCurrentStudy);
3016 StudyContext* myStudyContext = GetCurrentStudyContext();
3018 // Declare a byte stream
3019 SALOMEDS::TMPFile_var aStreamFile;
3021 // Obtain a temporary dir
3022 TCollection_AsciiString tmpDir =
3023 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3025 // Create a sequence of files processed
3026 SALOMEDS::ListOfFileNames_var aFileSeq = new SALOMEDS::ListOfFileNames;
3027 aFileSeq->length( NUM_TMP_FILES );
3029 TCollection_AsciiString aStudyName( "" );
3031 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( myCurrentStudy->URL() ).c_str() );
3033 // Set names of temporary files
3034 TCollection_AsciiString filename =
3035 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
3036 TCollection_AsciiString meshfile =
3037 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
3038 aFileSeq[ 0 ] = CORBA::string_dup( filename.ToCString() );
3039 aFileSeq[ 1 ] = CORBA::string_dup( meshfile.ToCString() );
3040 filename = tmpDir + filename;
3041 meshfile = tmpDir + meshfile;
3044 HDFdataset* aDataset;
3045 HDFgroup* aTopGroup;
3047 HDFgroup* aSubGroup;
3048 HDFgroup* aSubSubGroup;
3049 hdf_size aSize[ 1 ];
3052 //Remove the files if they exist: BugID: 11225
3053 #ifndef WIN32 /* unix functionality */
3054 TCollection_AsciiString cmd("rm -f \"");
3056 TCollection_AsciiString cmd("del /F \"");
3063 system(cmd.ToCString());
3065 // MED writer to be used by storage process
3066 DriverMED_W_SMESHDS_Mesh myWriter;
3067 myWriter.SetFile( meshfile.ToCString() );
3070 // SetStoreName() to groups before storing hypotheses to let them refer to
3071 // groups using "store name", which is "Group <group_persistent_id>"
3073 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3074 for ( ; itBig->More(); itBig->Next() ) {
3075 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3076 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3077 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3078 if ( !CORBA::is_nil( anObject ) ) {
3079 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3080 if ( !myMesh->_is_nil() ) {
3081 myMesh->Load(); // load from study file if not yet done
3082 TPythonDump pd; // not to dump GetGroups()
3083 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
3084 pd << ""; // to avoid optimizing pd out
3085 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
3087 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
3090 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
3091 int anId = myStudyContext->findId( string( objStr.in() ) );
3093 sprintf( grpName, "Group %d", anId );
3094 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
3095 aGrpBaseDS->SetStoreName( grpName );
3105 // ---> create HDF file
3106 aFile = new HDFfile( (char*) filename.ToCString() );
3107 aFile->CreateOnDisk();
3109 // --> iterator for top-level objects
3110 SALOMEDS::ChildIterator_wrap itBig = myCurrentStudy->NewChildIterator( theComponent );
3111 for ( ; itBig->More(); itBig->Next() ) {
3112 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
3114 // --> hypotheses root branch (only one for the study)
3115 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
3116 // create hypotheses root HDF group
3117 aTopGroup = new HDFgroup( "Hypotheses", aFile );
3118 aTopGroup->CreateOnDisk();
3120 // iterator for all hypotheses
3121 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3122 for ( ; it->More(); it->Next() ) {
3123 SALOMEDS::SObject_wrap mySObject = it->Value();
3124 CORBA::Object_var anObject = SObjectToObject( mySObject );
3125 if ( !CORBA::is_nil( anObject ) ) {
3126 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3127 if ( !myHyp->_is_nil() ) {
3128 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3130 string hypname = string( myHyp->GetName() );
3131 string libname = string( myHyp->GetLibName() );
3133 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3134 // WIN32 and ".so" for X-system) must be deleted
3135 int libname_len = libname.length();
3137 if( libname_len > 4 )
3138 libname.resize( libname_len - 4 );
3140 // PAL17753 (Regresion: missing hypothesis in restored study)
3141 // "lib" also should be removed from the beginning
3142 //if( libname_len > 3 )
3143 //libname.resize( libname_len - 3 );
3144 if( libname_len > 6 )
3145 libname = libname.substr( 3, libname_len - 3 - 3 );
3147 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3148 int id = myStudyContext->findId( string( objStr.in() ) );
3149 string hypdata = string( myImpl->SaveTo() );
3151 // for each hypothesis create HDF group basing on its id
3152 char hypGrpName[30];
3153 sprintf( hypGrpName, "Hypothesis %d", id );
3154 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3155 aGroup->CreateOnDisk();
3156 // --> type name of hypothesis
3157 aSize[ 0 ] = hypname.length() + 1;
3158 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3159 aDataset->CreateOnDisk();
3160 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3161 aDataset->CloseOnDisk();
3162 // --> server plugin library name of hypothesis
3163 aSize[ 0 ] = libname.length() + 1;
3164 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3165 aDataset->CreateOnDisk();
3166 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3167 aDataset->CloseOnDisk();
3168 // --> persistent data of hypothesis
3169 aSize[ 0 ] = hypdata.length() + 1;
3170 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3171 aDataset->CreateOnDisk();
3172 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3173 aDataset->CloseOnDisk();
3174 // close hypothesis HDF group
3175 aGroup->CloseOnDisk();
3180 // close hypotheses root HDF group
3181 aTopGroup->CloseOnDisk();
3183 // --> algorithms root branch (only one for the study)
3184 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
3185 // create algorithms root HDF group
3186 aTopGroup = new HDFgroup( "Algorithms", aFile );
3187 aTopGroup->CreateOnDisk();
3189 // iterator for all algorithms
3190 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( gotBranch );
3191 for ( ; it->More(); it->Next() ) {
3192 SALOMEDS::SObject_wrap mySObject = it->Value();
3193 CORBA::Object_var anObject = SObjectToObject( mySObject );
3194 if ( !CORBA::is_nil( anObject ) ) {
3195 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
3196 if ( !myHyp->_is_nil() ) {
3197 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
3199 string hypname = string( myHyp->GetName() );
3200 string libname = string( myHyp->GetLibName() );
3202 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
3203 // WIN32 and ".so" for X-system) must be deleted
3204 int libname_len = libname.length();
3206 if( libname_len > 4 )
3207 libname.resize( libname_len - 4 );
3209 // PAL17753 (Regresion: missing hypothesis in restored study)
3210 // "lib" also should be removed from the beginning
3211 //if( libname_len > 3 )
3212 //libname.resize( libname_len - 3 );
3213 if( libname_len > 6 )
3214 libname = libname.substr( 3, libname_len - 3 - 3 );
3216 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3217 int id = myStudyContext->findId( string( objStr.in() ) );
3218 string hypdata = string( myImpl->SaveTo() );
3220 // for each algorithm create HDF group basing on its id
3221 char hypGrpName[30];
3222 sprintf( hypGrpName, "Algorithm %d", id );
3223 aGroup = new HDFgroup( hypGrpName, aTopGroup );
3224 aGroup->CreateOnDisk();
3225 // --> type name of algorithm
3226 aSize[0] = hypname.length() + 1;
3227 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
3228 aDataset->CreateOnDisk();
3229 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
3230 aDataset->CloseOnDisk();
3231 // --> server plugin library name of hypothesis
3232 aSize[0] = libname.length() + 1;
3233 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
3234 aDataset->CreateOnDisk();
3235 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
3236 aDataset->CloseOnDisk();
3237 // --> persistent data of algorithm
3238 aSize[0] = hypdata.length() + 1;
3239 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
3240 aDataset->CreateOnDisk();
3241 aDataset->WriteOnDisk( ( char* )( hypdata.c_str() ) );
3242 aDataset->CloseOnDisk();
3243 // close algorithm HDF group
3244 aGroup->CloseOnDisk();
3249 // close algorithms root HDF group
3250 aTopGroup->CloseOnDisk();
3252 // --> mesh objects roots branches
3253 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
3254 CORBA::Object_var anObject = SObjectToObject( gotBranch );
3255 if ( !CORBA::is_nil( anObject ) ) {
3256 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
3257 if ( !myMesh->_is_nil() ) {
3258 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
3260 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3261 int id = myStudyContext->findId( string( objStr.in() ) );
3262 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
3263 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
3264 bool hasShape = myLocMesh.HasShapeToMesh();
3266 // for each mesh open the HDF group basing on its id
3267 char meshGrpName[ 30 ];
3268 sprintf( meshGrpName, "Mesh %d", id );
3269 aTopGroup = new HDFgroup( meshGrpName, aFile );
3270 aTopGroup->CreateOnDisk();
3272 // --> put dataset to hdf file which is a flag that mesh has data
3273 string strHasData = "0";
3274 // check if the mesh is not empty
3275 if ( mySMESHDSMesh->NbNodes() > 0 ) {
3276 // write mesh data to med file
3277 myWriter.SetMesh( mySMESHDSMesh );
3278 myWriter.SetMeshId( id );
3281 aSize[ 0 ] = strHasData.length() + 1;
3282 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
3283 aDataset->CreateOnDisk();
3284 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
3285 aDataset->CloseOnDisk();
3288 // for each mesh open the HDF group basing on its auto color parameter
3289 char meshAutoColorName[ 30 ];
3290 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
3292 anAutoColor[0] = myImpl->GetAutoColor();
3294 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
3295 aDataset->CreateOnDisk();
3296 aDataset->WriteOnDisk( anAutoColor );
3297 aDataset->CloseOnDisk();
3299 // issue 0020693. Store _isModified flag
3300 int isModified = myLocMesh.GetIsModified();
3302 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
3303 aDataset->CreateOnDisk();
3304 aDataset->WriteOnDisk( &isModified );
3305 aDataset->CloseOnDisk();
3307 // issue 20918. Store Persistent Id of SMESHDS_Mesh
3308 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
3310 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
3311 aDataset->CreateOnDisk();
3312 aDataset->WriteOnDisk( &meshPersistentId );
3313 aDataset->CloseOnDisk();
3315 // write reference on a shape if exists
3316 SALOMEDS::SObject_wrap myRef;
3317 bool shapeRefFound = false;
3318 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
3320 SALOMEDS::SObject_wrap myShape;
3321 bool ok = myRef->ReferencedObject( myShape.inout() );
3323 shapeRefFound = (! CORBA::is_nil( myShape->GetObject() ));
3324 string myRefOnObject = myShape->GetID();
3325 if ( shapeRefFound && myRefOnObject.length() > 0 ) {
3326 aSize[ 0 ] = myRefOnObject.length() + 1;
3327 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
3328 aDataset->CreateOnDisk();
3329 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3330 aDataset->CloseOnDisk();
3335 // write applied hypotheses if exist
3336 SALOMEDS::SObject_wrap myHypBranch;
3337 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
3338 if ( found && !shapeRefFound && hasShape) { // remove applied hyps
3339 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
3341 if ( found && (shapeRefFound || !hasShape) ) {
3342 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
3343 aGroup->CreateOnDisk();
3345 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myHypBranch );
3347 for ( ; it->More(); it->Next() ) {
3348 SALOMEDS::SObject_wrap mySObject = it->Value();
3349 SALOMEDS::SObject_wrap myRefOnHyp;
3350 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
3352 // san - it is impossible to recover applied hypotheses
3353 // using their entries within Load() method,
3354 // for there are no AttributeIORs in the study when Load() is working.
3355 // Hence, it is better to store persistent IDs of hypotheses as references to them
3357 //string myRefOnObject = myRefOnHyp->GetID();
3358 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
3359 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3360 int id = myStudyContext->findId( string( objStr.in() ) );
3361 //if ( myRefOnObject.length() > 0 ) {
3362 //aSize[ 0 ] = myRefOnObject.length() + 1;
3363 char hypName[ 30 ], hypId[ 30 ];
3364 sprintf( hypName, "Hyp %d", ++hypNb );
3365 sprintf( hypId, "%d", id );
3366 aSize[ 0 ] = strlen( hypId ) + 1;
3367 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
3368 aDataset->CreateOnDisk();
3369 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3370 aDataset->WriteOnDisk( hypId );
3371 aDataset->CloseOnDisk();
3375 aGroup->CloseOnDisk();
3378 // write applied algorithms if exist
3379 SALOMEDS::SObject_wrap myAlgoBranch;
3380 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
3381 myAlgoBranch.inout() );
3382 if ( found && !shapeRefFound && hasShape) { // remove applied algos
3383 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
3385 if ( found && (shapeRefFound || !hasShape)) {
3386 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
3387 aGroup->CreateOnDisk();
3389 SALOMEDS::ChildIterator_wrap it = myCurrentStudy->NewChildIterator( myAlgoBranch );
3391 for ( ; it->More(); it->Next() ) {
3392 SALOMEDS::SObject_wrap mySObject = it->Value();
3393 SALOMEDS::SObject_wrap myRefOnAlgo;
3394 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
3396 // san - it is impossible to recover applied algorithms
3397 // using their entries within Load() method,
3398 // for there are no AttributeIORs in the study when Load() is working.
3399 // Hence, it is better to store persistent IDs of algorithms as references to them
3401 //string myRefOnObject = myRefOnAlgo->GetID();
3402 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
3403 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
3404 int id = myStudyContext->findId( string( objStr.in() ) );
3405 //if ( myRefOnObject.length() > 0 ) {
3406 //aSize[ 0 ] = myRefOnObject.length() + 1;
3407 char algoName[ 30 ], algoId[ 30 ];
3408 sprintf( algoName, "Algo %d", ++algoNb );
3409 sprintf( algoId, "%d", id );
3410 aSize[ 0 ] = strlen( algoId ) + 1;
3411 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
3412 aDataset->CreateOnDisk();
3413 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3414 aDataset->WriteOnDisk( algoId );
3415 aDataset->CloseOnDisk();
3419 aGroup->CloseOnDisk();
3422 // --> submesh objects sub-branches
3424 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
3425 SALOMEDS::SObject_wrap mySubmeshBranch;
3426 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
3428 if ( found ) // check if there is shape reference in submeshes
3430 bool hasShapeRef = false;
3431 SALOMEDS::ChildIterator_wrap itSM =
3432 myCurrentStudy->NewChildIterator( mySubmeshBranch );
3433 for ( ; itSM->More(); itSM->Next() ) {
3434 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
3435 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3436 mySubRef->ReferencedObject( myShape.inout() );
3437 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
3440 { // remove one submesh
3441 if ( shapeRefFound )
3442 { // unassign hypothesis
3443 SMESH::SMESH_subMesh_var mySubMesh =
3444 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
3445 if ( !mySubMesh->_is_nil() ) {
3446 int shapeID = mySubMesh->GetId();
3447 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
3448 const list<const SMESHDS_Hypothesis*>& hypList =
3449 mySMESHDSMesh->GetHypothesis( S );
3450 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
3451 while ( hyp != hypList.end() ) {
3452 int hypID = (*hyp++)->GetID(); // goto next hyp here because
3453 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
3457 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
3459 } // loop on submeshes of a type
3460 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
3461 myCurrentStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
3464 } // end check if there is shape reference in submeshes
3466 char name_meshgroup[ 30 ];
3467 if ( i == GetSubMeshOnVertexTag() )
3468 strcpy( name_meshgroup, "SubMeshes On Vertex" );
3469 else if ( i == GetSubMeshOnEdgeTag() )
3470 strcpy( name_meshgroup, "SubMeshes On Edge" );
3471 else if ( i == GetSubMeshOnWireTag() )
3472 strcpy( name_meshgroup, "SubMeshes On Wire" );
3473 else if ( i == GetSubMeshOnFaceTag() )
3474 strcpy( name_meshgroup, "SubMeshes On Face" );
3475 else if ( i == GetSubMeshOnShellTag() )
3476 strcpy( name_meshgroup, "SubMeshes On Shell" );
3477 else if ( i == GetSubMeshOnSolidTag() )
3478 strcpy( name_meshgroup, "SubMeshes On Solid" );
3479 else if ( i == GetSubMeshOnCompoundTag() )
3480 strcpy( name_meshgroup, "SubMeshes On Compound" );
3482 // for each type of submeshes create container HDF group
3483 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
3484 aGroup->CreateOnDisk();
3486 // iterator for all submeshes of given type
3487 SALOMEDS::ChildIterator_wrap itSM = myCurrentStudy->NewChildIterator( mySubmeshBranch );
3488 for ( ; itSM->More(); itSM->Next() ) {
3489 SALOMEDS::SObject_wrap mySObject = itSM->Value();
3490 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
3491 if ( !CORBA::is_nil( anSubObject ))
3493 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
3494 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
3495 int subid = myStudyContext->findId( string( objStr.in() ) );
3497 // for each mesh open the HDF group basing on its id
3498 char submeshGrpName[ 30 ];
3499 sprintf( submeshGrpName, "SubMesh %d", subid );
3500 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
3501 aSubGroup->CreateOnDisk();
3503 // write reference on a shape, already checked if it exists
3504 SALOMEDS::SObject_wrap mySubRef, myShape;
3505 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
3506 mySubRef->ReferencedObject( myShape.inout() );
3507 string myRefOnObject = myShape->GetID();
3508 if ( myRefOnObject.length() > 0 ) {
3509 aSize[ 0 ] = myRefOnObject.length() + 1;
3510 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
3511 aDataset->CreateOnDisk();
3512 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
3513 aDataset->CloseOnDisk();
3516 // write applied hypotheses if exist
3517 SALOMEDS::SObject_wrap mySubHypBranch;
3518 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
3519 mySubHypBranch.inout() );
3521 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );