1 // Copyright (C) 2007-2022 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
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
52 // Have to be included before std headers
54 #include <structmember.h>
61 #include <libgen.h> // for basename function
65 #define LibHandle HMODULE
66 #define LoadLib( name ) LoadLibrary( name )
67 #define GetProc GetProcAddress
68 #define UnLoadLib( handle ) FreeLibrary( handle );
70 #define LibHandle void*
72 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
73 #else // DYNLOAD_LOCAL
74 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
75 #endif // DYNLOAD_LOCAL
77 #define UnLoadLib( handle ) dlclose( handle );
80 #include "SMESH_Gen_i.hxx"
81 #include "SMESH_version.h"
83 #include "DriverMED_W_SMESHDS_Mesh.h"
84 #include "DriverMED_R_SMESHDS_Mesh.h"
86 #include "DriverCGNS_Read.hxx"
88 #include "MED_Factory.hxx"
89 #include "SMDS_EdgePosition.hxx"
90 #include "SMDS_FacePosition.hxx"
91 #include "SMDS_SetIterator.hxx"
92 #include "SMDS_SpacePosition.hxx"
93 #include "SMDS_VertexPosition.hxx"
94 #include "SMESHDS_Document.hxx"
95 #include "SMESHDS_Group.hxx"
96 #include "SMESHDS_GroupOnGeom.hxx"
97 #include "SMESH_Algo_i.hxx"
98 #include "SMESH_File.hxx"
99 #include "SMESH_Group.hxx"
100 #include "SMESH_Group_i.hxx"
101 #include "SMESH_Hypothesis.hxx"
102 #include "SMESH_Hypothesis_i.hxx"
103 #include "SMESH_Mesh.hxx"
104 #include "SMESH_MeshEditor.hxx"
105 #include "SMESH_Mesh_i.hxx"
106 #include "SMESH_PreMeshInfo.hxx"
107 #include "SMESH_PythonDump.hxx"
108 #include "SMESH_ControlsDef.hxx"
109 #include <SMESH_BoostTxtArchive.hxx>
111 // to pass CORBA exception through SMESH_TRY
112 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
113 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
115 #include CORBA_SERVER_HEADER(SMESH_Group)
116 #include CORBA_SERVER_HEADER(SMESH_Filter)
117 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
120 #include <GEOMImpl_Types.hxx>
121 #include <GEOM_Client.hxx>
123 #include <Basics_Utils.hxx>
124 #include <Basics_DirUtils.hxx>
126 #include <OpUtil.hxx>
127 #include <SALOMEDS_Tool.hxx>
128 #include <SALOME_Container_i.hxx>
129 #include <SALOME_LifeCycleCORBA.hxx>
130 #include <SALOME_NamingService.hxx>
131 #include <Utils_CorbaException.hxx>
132 #include <Utils_ExceptHandlers.hxx>
133 #include <Utils_SINGLETON.hxx>
134 #include <utilities.h>
136 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
137 #include CORBA_CLIENT_HEADER(SALOME_Session)
139 // helpers about SALOME::GenericObj
140 #include <SALOMEDS_wrap.hxx>
141 #include <SALOMEDS_Attributes_wrap.hxx>
142 #include <GEOM_wrap.hxx>
151 #include <boost/archive/text_oarchive.hpp>
152 #include <boost/serialization/list.hpp>
153 #include <boost/serialization/string.hpp>
154 #include <boost/filesystem.hpp>
156 namespace fs = boost::filesystem;
159 using SMESH::TPythonDump;
162 #define NUM_TMP_FILES 2
164 // Static variables definition
165 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
166 CORBA::ORB_var SMESH_Gen_i::myOrb;
167 PortableServer::POA_var SMESH_Gen_i::myPoa;
168 SALOME_NamingService_Abstract* SMESH_Gen_i::myNS = nullptr;
169 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = nullptr;
170 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = nullptr;
173 const int nbElemPerDiagonal = 10;
175 //=============================================================================
177 * GetServant [ static ]
179 * Get servant of the CORBA object
181 //=============================================================================
183 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
185 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
188 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
191 catch (PortableServer::POA::ObjectNotActive &ex)
193 MESSAGE("GetServant: ObjectNotActive");
196 catch (PortableServer::POA::WrongAdapter &ex)
198 MESSAGE("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
201 catch (PortableServer::POA::WrongPolicy &ex)
203 MESSAGE("GetServant: WrongPolicy");
208 MESSAGE( "GetServant - Unknown exception was caught!!!" );
213 //=============================================================================
215 * SObjectToObject [ static ]
217 * Get CORBA object corresponding to the SALOMEDS::SObject
219 //=============================================================================
221 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
223 SALOMEDS::GenericAttribute_wrap anAttr;
224 CORBA::Object_var anObj;
225 if ( !theSObject->_is_nil() ) {
227 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
228 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
229 CORBA::String_var aValue = anIOR->Value();
230 if( strcmp( aValue, "" ) != 0 )
231 anObj = GetORB()->string_to_object( aValue );
235 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
241 // Set Naming Service object
242 void SMESH_Gen_i::SetNS(SALOME_NamingService_Abstract *ns)
249 //=============================================================================
253 * Get SALOME_NamingService object
255 //=============================================================================
257 SALOME_NamingService_Abstract* SMESH_Gen_i::GetNS()
260 myNS = SINGLETON_<SALOME_NamingService>::Instance();
261 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
262 myNS->init_orb( GetORB() );
267 //=============================================================================
271 * Get SALOME_LifeCycleCORBA object
273 //=============================================================================
275 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
277 if ( myLCC == NULL ) {
278 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
283 //=============================================================================
285 * GetGeomEngine [ static ]
287 * Get GEOM::GEOM_Gen reference
289 //=============================================================================
291 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
293 GEOM::GEOM_Gen_ptr gen = GEOM::GEOM_Gen::_nil();
294 if ( !CORBA::is_nil( go ))
299 //=============================================================================
301 * SMESH_Gen_i::SMESH_Gen_i
303 * Default constructor: not for use
305 //=============================================================================
307 SMESH_Gen_i::SMESH_Gen_i()
311 //=============================================================================
313 * SMESH_Gen_i::SMESH_Gen_i
315 * Standard constructor, used with Container
317 //=============================================================================
319 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
320 PortableServer::POA_ptr poa,
321 PortableServer::ObjectId* contId,
322 const char* instanceName,
323 const char* interfaceName,
325 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName, false, checkNS )
328 myOrb = CORBA::ORB::_duplicate(orb);
329 myPoa = PortableServer::POA::_duplicate(poa);
332 _id = myPoa->activate_object( _thisObj );
334 myStudyContext = new StudyContext;
336 myIsEmbeddedMode = false;
337 myIsEnablePublish = true;
338 myShapeReader = NULL; // shape reader
340 myIsHistoricalPythonDump = true;
341 myToForgetMeshDataOnHypModif = false;
343 // set it in standalone mode only
344 //OSD::SetSignal( true );
346 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
347 // find out mode (embedded or standalone) here else
348 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
349 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
352 if ( SALOME_NamingService_Abstract* ns = GetNS() )
354 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
355 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
356 if ( !session->_is_nil() )
358 CORBA::String_var str_host = session->getHostname();
359 CORBA::Long s_pid = session->getPID();
360 string my_host = Kernel_Utils::GetHostname();
362 long my_pid = (long)_getpid();
364 long my_pid = (long) getpid();
366 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
372 //=============================================================================
374 * SMESH_Gen_i::~SMESH_Gen_i
378 //=============================================================================
380 SMESH_Gen_i::~SMESH_Gen_i()
382 // delete hypothesis creators
383 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
384 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
386 // same creator can be mapped under different names
387 GenericHypothesisCreator_i* creator = (*itHyp).second;
391 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
392 if ( creator == (*itHyp2).second )
393 (*itHyp2).second = 0;
395 myHypCreatorMap.clear();
397 // Clear study contexts data
398 delete myStudyContext;
400 // delete shape reader
402 delete myShapeReader;
405 //=============================================================================
407 * SMESH_Gen_i::getHypothesisCreator
409 * Get hypothesis creator
411 //=============================================================================
413 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
414 const char* theLibName,
415 std::string& thePlatformLibName)
417 std::string aPlatformLibName;
418 /* It's Need to translate lib name for WIN32 or X platform */
419 if ( theLibName && theLibName[0] != '\0' )
421 int libNameLen = strlen(theLibName);
422 //check for old format "libXXXXXXX.so"
423 if (libNameLen > 7 &&
424 !strncmp( theLibName, "lib", 3 ) &&
425 !strcmp( theLibName+libNameLen-3, ".so" ))
429 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
430 #elif defined(__APPLE__)
431 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
433 aPlatformLibName = theLibName;
438 //try to use new format
440 aPlatformLibName = theLibName;
441 aPlatformLibName += ".dll";
442 #elif defined(__APPLE__)
443 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
445 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
449 thePlatformLibName = aPlatformLibName;
451 Unexpect aCatch(SALOME_SalomeException);
452 MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
454 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
455 GenericHypothesisCreator_i* aCreator;
458 // check, if creator for this hypothesis type already exists
459 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
461 // load plugin library
462 MESSAGE("Loading server meshers plugin library ...");
465 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
466 SMESHUtils::ArrayDeleter<const wchar_t> deleter( path );
468 const char* path = aPlatformLibName.c_str();
471 const char* path = aPlatformLibName.c_str();
473 LibHandle libHandle = LoadLib( path );
477 // report any error, if occurred
479 const char* anError = dlerror();
480 throw(SALOME_Exception( anError ));
482 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
483 << aPlatformLibName));
487 // get method, returning hypothesis creator
488 MESSAGE("Find GetHypothesisCreator() method ...");
489 GetHypothesisCreator procHandle =
490 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
493 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
494 << aPlatformLibName ));
495 UnLoadLib(libHandle);
498 // get hypothesis creator
499 MESSAGE("Get Hypothesis Creator for " << theHypName);
500 aCreator = procHandle(theHypName);
503 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
504 << aPlatformLibName));
506 // map hypothesis creator to a hypothesis name
507 myHypCreatorMap[string(theHypName)] = aCreator;
512 return myHypCreatorMap[string(theHypName)];
515 catch (SALOME_Exception& S_ex)
517 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
522 //=============================================================================
524 * SMESH_Gen_i::createHypothesis
526 * Create hypothesis of given type
528 //=============================================================================
530 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
531 const char* theLibName)
533 SMESH_Hypothesis_i* myHypothesis_i = 0;
534 SMESH::SMESH_Hypothesis_var hypothesis_i;
535 std::string aPlatformLibName;
536 GenericHypothesisCreator_i* aCreator =
537 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
539 // create a new hypothesis object, store its ref. in studyContext
540 myHypothesis_i = aCreator->Create(myPoa, &myGen);
543 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
544 CORBA::String_var hypName = myHypothesis_i->GetName();
545 myHypCreatorMap[ hypName.in() ] = aCreator;
547 // activate the CORBA servant of hypothesis
548 hypothesis_i = myHypothesis_i->_this();
549 int nextId = RegisterObject( hypothesis_i );
550 MESSAGE( "Add hypo to map with id = "<< nextId );
552 return hypothesis_i._retn();
555 //=============================================================================
557 * SMESH_Gen_i::createMesh
559 * Create empty mesh on shape
561 //=============================================================================
563 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
565 Unexpect aCatch(SALOME_SalomeException);
566 MESSAGE( "SMESH_Gen_i::createMesh" );
568 // Get or create the GEOM_Client instance
570 // create a new mesh object servant, store it in a map in study context
571 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
572 // create a new mesh object
573 MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
574 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
576 // activate the CORBA servant of Mesh
577 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
578 int nextId = RegisterObject( mesh );
579 MESSAGE( "Add mesh to map with id = "<< nextId);
583 catch (SALOME_Exception& S_ex) {
584 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
586 return SMESH::SMESH_Mesh::_nil();
589 //=============================================================================
591 * SMESH_Gen_i::GetShapeReader
595 //=============================================================================
597 GEOM_Client* SMESH_Gen_i::GetShapeReader()
599 // create shape reader if necessary
600 if ( !myShapeReader )
601 myShapeReader = new GEOM_Client(GetContainerRef());
602 ASSERT( myShapeReader );
603 return myShapeReader;
606 //=============================================================================
608 * SMESH_Gen_i::SetGeomEngine
610 * Set GEOM::GEOM_Gen reference
612 //=============================================================================
614 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
616 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
619 //=============================================================================
621 * SMESH_Gen_i::SetEmbeddedMode
625 //=============================================================================
627 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
629 myIsEmbeddedMode = theMode;
631 if ( !myIsEmbeddedMode ) {
632 //PAL10867: disable signals catching with "noexcepthandler" option
633 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
634 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
638 if (SALOME::VerbosityActivated())
641 char* envDisableFPE = getenv("DISABLE_FPE");
642 if (envDisableFPE && atoi(envDisableFPE))
650 OSD::SetSignal( raiseFPE );
652 // else OSD::SetSignal() is called in GUI
656 //=============================================================================
658 * SMESH_Gen_i::IsEmbeddedMode
662 //=============================================================================
664 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
666 return myIsEmbeddedMode;
669 //=============================================================================
671 * SMESH_Gen_i::SetEnablePublish
673 * Set enable publishing in the study
675 //=============================================================================
677 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
679 myIsEnablePublish = theIsEnablePublish;
682 //=============================================================================
684 * SMESH_Gen_i::IsEnablePublish
686 * Check enable publishing
688 //=============================================================================
690 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
692 return myIsEnablePublish;
695 //=============================================================================
697 * SMESH_Gen_i::UpdateStudy
699 * Update study (needed at switching GEOM->SMESH)
701 //=============================================================================
703 void SMESH_Gen_i::UpdateStudy()
705 if ( !myStudyContext )
706 myStudyContext = new StudyContext;
708 SALOMEDS::Study_var aStudy = getStudyServant();
709 if ( !CORBA::is_nil( aStudy ) )
711 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
713 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
714 if( !GEOM_var->_is_nil() )
715 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
717 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
718 if( !GEOM_var->_is_nil() )
719 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
721 // NPAL16168, issue 0020210
722 // Let meshes update their data depending on GEOM groups that could change
723 CORBA::String_var compDataType = ComponentDataType();
724 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
725 if ( !me->_is_nil() ) {
726 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
727 for ( ; anIter->More(); anIter->Next() ) {
728 SALOMEDS::SObject_wrap so = anIter->Value();
729 CORBA::Object_var ior = SObjectToObject( so );
730 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
731 mesh->CheckGeomModif();
737 //================================================================================
739 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
741 //================================================================================
743 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
745 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
746 SALOMEDS::GenericAttribute_wrap attr;
747 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
749 SALOMEDS::AttributePixMap_wrap pm = attr;
750 CORBA::String_var ico = pm->GetPixMap();
751 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
756 //=================================================================================
757 // function : hasObjectInfo()
758 // purpose : shows if module provides information for its objects
759 //=================================================================================
761 bool SMESH_Gen_i::hasObjectInfo()
766 //=================================================================================
767 // function : getObjectInfo()
768 // purpose : returns an information for a given object by its entry
769 //=================================================================================
771 char* SMESH_Gen_i::getObjectInfo( const char* entry )
773 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
774 // for the rest, "module 'SMESH', ID=0:1:2:*"
778 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
779 CORBA::Object_var obj = SObjectToObject( so );
780 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
781 if ( isGeomModifIcon( mesh ))
783 txt << "The geometry was changed and the mesh needs to be recomputed";
788 CORBA::String_var compType = ComponentDataType();
789 txt << "module '" << compType << "', ID=" << entry;
791 return CORBA::string_dup( txt );
794 //=============================================================================
796 * SMESH_Gen_i::GetStudyContext
800 //=============================================================================
802 StudyContext* SMESH_Gen_i::GetStudyContext()
804 return myStudyContext;
807 //=============================================================================
809 * SMESH_Gen_i::CreateHypothesis
811 * Create hypothesis/algorithm of given type and publish it in the study
813 //=============================================================================
815 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
816 const char* theLibName )
818 Unexpect aCatch(SALOME_SalomeException);
819 // Create hypothesis/algorithm
820 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
822 // Publish hypothesis/algorithm in the study
823 if ( CanPublishInStudy( hyp ) ) {
824 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
825 if ( !aSO->_is_nil() ) {
826 // Update Python script
827 TPythonDump(this) << aSO << " = " << this << ".CreateHypothesis('"
828 << theHypName << "', '" << theLibName << "')";
835 //================================================================================
837 * \brief Return a hypothesis initialized by given average length.
838 * \param theHypType - hypothesis type name
839 * \param theLibName - plugin library name
840 * \param theAverageLength - average length
841 * \param theQuadDominated - is quad-dominated flag
842 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
844 //================================================================================
846 SMESH::SMESH_Hypothesis_ptr
847 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
848 const char* theLibName,
849 CORBA::Double theAverageLength,
850 CORBA::Boolean theQuadDominated)
852 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
853 theAverageLength, theQuadDominated };
855 SMESH::SMESH_Hypothesis_var hyp =
856 GetHypothesisParameterValues( theHypType, theLibName,
857 SMESH::SMESH_Mesh::_nil(),
858 GEOM::GEOM_Object::_nil(),
860 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
862 TPythonDump(this) << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
863 << theHypType << "', '"
864 << theLibName << "', "
865 << theAverageLength << ", "
866 << theQuadDominated << " )";
871 //================================================================================
873 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
874 * existing on the given geometry or to size of the geometry.
875 * \param theHypType - hypothesis type name
876 * \param theLibName - plugin library name
877 * \param theMesh - The mesh of interest
878 * \param theGeom - The shape to get parameter values from
879 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
880 * in a study and used to compute the mesh, or a temporary one created just to pass
883 //================================================================================
885 SMESH::SMESH_Hypothesis_ptr
886 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
887 const char* theLibName,
888 SMESH::SMESH_Mesh_ptr theMesh,
889 GEOM::GEOM_Object_ptr theGeom,
890 const SMESH::HypInitParams& theParams)
892 Unexpect aCatch(SALOME_SalomeException);
894 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
895 if ( byMesh && CORBA::is_nil( theMesh ) )
896 return SMESH::SMESH_Hypothesis::_nil();
897 if ( byMesh && CORBA::is_nil( theGeom ) )
898 return SMESH::SMESH_Hypothesis::_nil();
900 // -----------------------------------------------
901 // find hypothesis used to mesh theGeom
902 // -----------------------------------------------
904 // get mesh and shape
905 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
906 TopoDS_Shape shape = GeomObjectToShape( theGeom );
907 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
908 return SMESH::SMESH_Hypothesis::_nil();
909 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
911 // create a temporary hypothesis to know its dimension
912 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
913 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
915 return SMESH::SMESH_Hypothesis::_nil();
916 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
919 // look for a hypothesis of theHypType used to mesh the shape
920 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
923 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
924 int nbLocalHyps = aHypList->length();
925 for ( int i = 0; i < nbLocalHyps; i++ ) {
926 CORBA::String_var hypName = aHypList[i]->GetName();
927 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
928 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
930 // check super shapes
931 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
932 while ( nbLocalHyps == 0 && itShape.More() ) {
933 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
934 if ( ! CORBA::is_nil( geomObj )) {
935 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
936 nbLocalHyps = aHypList->length();
937 for ( int i = 0; i < nbLocalHyps; i++ )
938 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
939 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
945 // let the temporary hypothesis find out somehow parameter values by mesh
946 if ( hyp->SetParametersByMesh( mesh, shape ))
947 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
951 ::SMESH_Hypothesis::TDefaults dflts;
952 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
953 dflts._nbSegments = myGen.GetDefaultNbSegments();
954 dflts._elemLength = theParams.averageLength;
955 dflts._quadDominated = theParams.quadDominated;
956 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
959 dflts._diagonal = mesh->GetShapeDiagonalSize();
961 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
962 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
963 dflts._shape = &shape;
966 // let the hypothesis initialize it's values
967 if ( hyp->SetParametersByDefaults( dflts, mesh ))
968 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
971 return SMESH::SMESH_Hypothesis::_nil();
974 //=============================================================================
976 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
977 * \param [in] theHyp - the hypothesis of interest
978 * \param [out] theMesh - the sole mesh using \a theHyp
979 * \param [out] theShape - the sole geometry \a theHyp is assigned to
980 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
982 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
983 * considered as SAME sub-mesh => result is \c true.
984 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
985 * a shape to which an hyp being edited is assigned.
987 //=============================================================================
989 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
990 SMESH::SMESH_Mesh_out theMesh,
991 GEOM::GEOM_Object_out theShape)
993 if ( CORBA::is_nil( theHyp ))
996 // get Mesh component SO
997 CORBA::String_var compDataType = ComponentDataType();
998 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
999 if ( CORBA::is_nil( comp ))
1002 // look for child SO of meshes
1003 SMESH::SMESH_Mesh_var foundMesh;
1004 TopoDS_Shape foundShape;
1006 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1007 for ( ; meshIter->More() && isSole; meshIter->Next() )
1009 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1010 CORBA::Object_var obj = SObjectToObject( curSO );
1011 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1015 // look for a sole shape where theHyp is assigned
1016 bool isHypFound = false;
1017 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1018 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1019 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1021 const THypList& hyps = s2hypsIt.Value();
1022 THypList::const_iterator h = hyps.begin();
1023 for ( ; h != hyps.end(); ++h )
1024 if ( (*h)->GetID() == theHyp->GetId() )
1026 if ( h != hyps.end()) // theHyp found
1029 if ( ! foundShape.IsNull() &&
1030 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1032 foundShape.Nullify();
1036 foundShape = s2hypsIt.Key();
1038 } // loop on assigned hyps
1040 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1042 if ( !foundMesh->_is_nil() ) // not a sole mesh
1044 if ( !foundMesh->HasShapeToMesh() ||
1045 !mesh_i ->HasShapeToMesh() )
1047 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1051 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1052 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1053 isSole = s1->IsSame( s2 );
1056 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1062 ! foundMesh->_is_nil() &&
1063 ! foundShape.IsNull() )
1065 theMesh = foundMesh._retn();
1066 theShape = ShapeToGeomObject( foundShape );
1067 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1072 //=============================================================================
1074 * Set number of segments per diagonal of boundary box of geometry by which
1075 * default segment length of appropriate 1D hypotheses is defined
1077 //=============================================================================
1079 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1081 if ( theNbSegments > 0 )
1082 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1084 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1087 //=============================================================================
1089 * \brief Set default number of segments per edge
1091 //=============================================================================
1093 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1095 if ( theNbSegments > 0 )
1096 myGen.SetDefaultNbSegments( int(theNbSegments) );
1098 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1101 //=============================================================================
1103 * Set an option value
1105 //=============================================================================
1107 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1109 if ( name && value && strlen( value ) > 0 )
1112 if ( strcmp(name, "historical_python_dump") == 0 )
1114 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1115 msgToGUI = "preferences/SMESH/historical_python_dump/";
1116 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1118 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1120 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1121 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1122 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1124 else if ( strcmp(name, "default_grp_color") == 0 )
1128 // color must be presented as a string of following form:
1129 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1130 str = str.substr(1);
1131 for ( size_t i = 0; i < str.length()/2; i++ )
1132 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1133 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1135 else if ( value ) { // rgb color ("255,170,0", for example)
1136 string tempValue( value );
1137 char* colorValue = strtok( &tempValue[0], "," );
1138 while ( colorValue != NULL ) {
1139 int c_value = atoi( colorValue );
1140 if ( c_value >= 0 && c_value <= 255 )
1141 color.push_back( c_value );
1142 colorValue = strtok( NULL, "," );
1145 if ( color.size() == 3 ) { // color must have three valid component
1146 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1147 myDefaultGroupColor = value;
1148 msgToGUI = "preferences/SMESH/default_grp_color/";
1153 // update preferences in case if SetOption() is invoked from python console
1154 if ( !msgToGUI.empty() )
1156 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1157 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1158 if ( !CORBA::is_nil( session ) )
1159 session->emitMessageOneWay(msgToGUI.c_str());
1164 //=============================================================================
1166 * Return an option value
1168 //=============================================================================
1170 char* SMESH_Gen_i::GetOption(const char* name)
1174 if ( strcmp(name, "historical_python_dump") == 0 )
1176 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1178 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1180 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1182 if ( strcmp(name, "default_grp_color") == 0 )
1184 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1187 return CORBA::string_dup( "" );
1190 //=============================================================================
1192 * SMESH_Gen_i::CreateMesh
1194 * Create empty mesh on a shape and publish it in the study
1196 //=============================================================================
1198 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1200 Unexpect aCatch(SALOME_SalomeException);
1201 MESSAGE( "SMESH_Gen_i::CreateMesh" );
1203 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1205 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1206 ASSERT( meshServant );
1207 meshServant->SetShape( theShapeObject );
1209 // publish mesh in the study
1210 if ( CanPublishInStudy( mesh ) ) {
1211 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1212 aStudyBuilder->NewCommand(); // There is a transaction
1213 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1214 aStudyBuilder->CommitCommand();
1215 if ( !aSO->_is_nil() ) {
1216 // Update Python script
1217 TPythonDump(this) << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1221 return mesh._retn();
1224 //=============================================================================
1226 * SMESH_Gen_i::CreateEmptyMesh
1230 //=============================================================================
1232 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1234 Unexpect aCatch(SALOME_SalomeException);
1235 MESSAGE( "SMESH_Gen_i::CreateMesh" );
1237 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1239 // publish mesh in the study
1240 if ( CanPublishInStudy( mesh ) ) {
1241 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1242 aStudyBuilder->NewCommand(); // There is a transaction
1243 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1244 aStudyBuilder->CommitCommand();
1245 if ( !aSO->_is_nil() ) {
1246 // Update Python script
1247 TPythonDump(this) << aSO << " = " << this << ".CreateEmptyMesh()";
1251 return mesh._retn();
1256 //================================================================================
1258 * \brief Throw an exception in case if the file can't be read
1260 //================================================================================
1262 void checkFileReadable( const char* theFileName )
1264 SMESH_File f ( theFileName );
1267 if ( !f.error().empty() )
1268 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1270 THROW_SALOME_CORBA_EXCEPTION
1271 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1272 SALOME::BAD_PARAM );
1277 //=============================================================================
1279 * SMESH_Gen_i::CreateMeshFromUNV
1281 * Create mesh and import data from UNV file
1283 //=============================================================================
1285 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1287 Unexpect aCatch(SALOME_SalomeException);
1289 checkFileReadable( theFileName );
1291 SMESH::SMESH_Mesh_var aMesh = createMesh();
1293 // publish mesh in the study
1294 if ( CanPublishInStudy( aMesh ) ) {
1295 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1296 aStudyBuilder->NewCommand(); // There is a transaction
1297 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1298 aStudyBuilder->CommitCommand();
1299 if ( !aSO->_is_nil() ) {
1300 // Update Python script
1301 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1305 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1307 aServant->ImportUNVFile( theFileName );
1309 // Dump creation of groups
1310 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1312 aServant->GetImpl().GetMeshDS()->Modified();
1313 return aMesh._retn();
1316 //=============================================================================
1318 * SMESH_Gen_i::CreateMeshFromMED
1320 * Create mesh and import data from MED file
1322 //=============================================================================
1324 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1325 SMESH::DriverMED_ReadStatus& theStatus )
1327 checkFileReadable( theFileName );
1330 char bname[ _MAX_FNAME ];
1331 _splitpath( theFileName, NULL, NULL, bname, NULL );
1332 string aFileName = bname;
1334 string aFileName = basename( const_cast<char *>( theFileName ));
1336 // Retrieve mesh names from the file
1337 DriverMED_R_SMESHDS_Mesh myReader;
1338 myReader.SetFile( theFileName );
1339 myReader.SetMeshId( -1 );
1340 Driver_Mesh::Status aStatus;
1341 list<string> aNames = myReader.GetMeshNames(aStatus);
1342 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1343 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1345 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1348 TPythonDump aPythonDump(this);
1349 aPythonDump << "([";
1351 if (theStatus == SMESH::DRS_OK)
1353 SALOMEDS::StudyBuilder_var aStudyBuilder;
1354 aStudyBuilder = getStudyServant()->NewBuilder();
1355 aStudyBuilder->NewCommand(); // There is a transaction
1357 aResult->length( aNames.size() );
1360 // Iterate through all meshes and create mesh objects
1361 for ( const std::string & meshName : aNames )
1364 if (i > 0) aPythonDump << ", ";
1367 SMESH::SMESH_Mesh_var mesh = createMesh();
1369 // publish mesh in the study
1370 SALOMEDS::SObject_wrap aSO;
1371 if ( CanPublishInStudy( mesh ) )
1372 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1375 if ( !aSO->_is_nil() ) {
1378 aPythonDump << "mesh_" << i;
1381 // Read mesh data (groups are published automatically by ImportMEDFile())
1382 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1383 ASSERT( meshServant );
1384 SMESH::DriverMED_ReadStatus status1 =
1385 meshServant->ImportMEDFile( theFileName, meshName.c_str() );
1386 if (status1 > theStatus)
1387 theStatus = status1;
1389 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1390 meshServant->GetImpl().GetMeshDS()->Modified();
1392 if ( !aStudyBuilder->_is_nil() )
1393 aStudyBuilder->CommitCommand();
1396 // Update Python script
1397 aPythonDump << "], status) = " << this << ".CreateMeshesFromMED( r'" << theFileName << "' )";
1399 // Dump creation of groups
1400 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1401 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1403 return aResult._retn();
1406 //=============================================================================
1408 * SMESH_Gen_i::CreateMeshFromSTL
1410 * Create mesh and import data from STL file
1412 //=============================================================================
1414 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1416 Unexpect aCatch(SALOME_SalomeException);
1417 checkFileReadable( theFileName );
1419 SMESH::SMESH_Mesh_var aMesh = createMesh();
1422 char bname[ _MAX_FNAME ];
1423 _splitpath( theFileName, NULL, NULL, bname, NULL );
1424 string aFileName = bname;
1426 string aFileName = basename( const_cast<char *>(theFileName) );
1428 // publish mesh in the study
1429 if ( CanPublishInStudy( aMesh ) ) {
1430 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1431 aStudyBuilder->NewCommand(); // There is a transaction
1432 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1433 aStudyBuilder->CommitCommand();
1434 if ( !aSO->_is_nil() ) {
1435 // Update Python script
1436 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1440 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1442 aServant->ImportSTLFile( theFileName );
1443 aServant->GetImpl().GetMeshDS()->Modified();
1444 return aMesh._retn();
1447 //================================================================================
1449 * \brief Create meshes and import data from the CGSN file
1451 //================================================================================
1453 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1454 SMESH::DriverMED_ReadStatus& theStatus)
1456 Unexpect aCatch(SALOME_SalomeException);
1457 checkFileReadable( theFileName );
1459 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1462 // Retrieve nb meshes from the file
1463 DriverCGNS_Read myReader;
1464 myReader.SetFile( theFileName );
1465 Driver_Mesh::Status aStatus;
1466 int nbMeshes = myReader.GetNbMeshes(aStatus);
1467 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1469 aResult->length( nbMeshes );
1471 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1474 TPythonDump aPythonDump(this);
1475 aPythonDump << "([";
1477 if (theStatus == SMESH::DRS_OK)
1479 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1480 aStudyBuilder->NewCommand(); // There is a transaction
1484 // Iterate through all meshes and create mesh objects
1485 for ( ; i < nbMeshes; ++i )
1488 if (i > 0) aPythonDump << ", ";
1491 SMESH::SMESH_Mesh_var mesh = createMesh();
1492 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1494 // Read mesh data (groups are published automatically by ImportMEDFile())
1495 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1496 ASSERT( meshServant );
1498 SMESH::DriverMED_ReadStatus status1 =
1499 meshServant->ImportCGNSFile( theFileName, i, meshName );
1500 if (status1 > theStatus)
1501 theStatus = status1;
1503 meshServant->GetImpl().GetMeshDS()->Modified();
1504 // publish mesh in the study
1505 SALOMEDS::SObject_wrap aSO;
1506 if ( CanPublishInStudy( mesh ) )
1507 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1510 if ( !aSO->_is_nil() ) {
1514 aPythonDump << "mesh_" << i;
1517 aStudyBuilder->CommitCommand();
1520 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1522 // Dump creation of groups
1523 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1524 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1526 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1529 return aResult._retn();
1532 //================================================================================
1534 * \brief Create a mesh and import data from a GMF file
1536 //================================================================================
1538 SMESH::SMESH_Mesh_ptr
1539 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1540 CORBA::Boolean theMakeRequiredGroups,
1541 SMESH::ComputeError_out theError)
1543 Unexpect aCatch(SALOME_SalomeException);
1544 checkFileReadable( theFileName );
1546 SMESH::SMESH_Mesh_var aMesh = createMesh();
1548 char bname[ _MAX_FNAME ];
1549 _splitpath( theFileName, NULL, NULL, bname, NULL );
1550 string aFileName = bname;
1552 string aFileName = basename( const_cast<char *>(theFileName) );
1554 // publish mesh in the study
1555 if ( CanPublishInStudy( aMesh ) ) {
1556 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1557 aStudyBuilder->NewCommand(); // There is a transaction
1558 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1559 aStudyBuilder->CommitCommand();
1560 if ( !aSO->_is_nil() ) {
1561 // Update Python script
1562 TPythonDump(this) << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1563 << theFileName << "', "
1564 << theMakeRequiredGroups << " )";
1567 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1569 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1570 aServant->GetImpl().GetMeshDS()->Modified();
1571 return aMesh._retn();
1575 //=============================================================================
1577 * SMESH_Gen_i::IsReadyToCompute
1579 * Return true if mesh contains enough data to be computed
1581 //=============================================================================
1583 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1584 GEOM::GEOM_Object_ptr theShapeObject )
1586 Unexpect aCatch(SALOME_SalomeException);
1587 MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1589 if ( CORBA::is_nil( theShapeObject ) )
1590 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1591 SALOME::BAD_PARAM );
1592 if ( CORBA::is_nil( theMesh ) )
1593 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1594 SALOME::BAD_PARAM );
1597 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1598 ASSERT( meshServant );
1599 if ( meshServant ) {
1600 // get local TopoDS_Shape
1601 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1602 // call implementation
1603 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1604 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1607 catch ( SALOME_Exception& S_ex ) {
1608 INFOS( "catch exception "<< S_ex.what() );
1613 //================================================================================
1615 * \brief Find SObject for an algo
1617 //================================================================================
1619 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1622 SALOMEDS::Study_var aStudy = getStudyServant();
1623 if ( !aStudy->_is_nil() ) {
1624 // find algo in the study
1625 CORBA::String_var compDataType = ComponentDataType();
1626 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1627 if ( !father->_is_nil() ) {
1628 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1629 for ( ; itBig->More(); itBig->Next() ) {
1630 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1631 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1632 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1633 for ( ; algoIt->More(); algoIt->Next() ) {
1634 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1635 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1636 if ( !CORBA::is_nil( algoIOR )) {
1637 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1638 if ( impl && impl->GetImpl() == algo )
1639 return algoSO._retn();
1641 } // loop on algo SO's
1644 } // SMESH component iterator
1648 return SALOMEDS::SObject::_nil();
1651 //================================================================================
1653 * \brief Return errors of mesh computation
1655 //================================================================================
1657 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1658 GEOM::GEOM_Object_ptr theSubObject )
1660 Unexpect aCatch(SALOME_SalomeException);
1661 MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1663 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1664 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1666 if ( CORBA::is_nil( theMesh ) )
1667 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1669 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1671 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1674 if(theMesh->HasShapeToMesh())
1675 shape = GeomObjectToShape( theSubObject );
1677 shape = SMESH_Mesh::PseudoShape();
1679 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1681 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1684 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1685 const bool includeSelf = true, complexShapeFirst = true;
1686 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1688 while ( smIt->more() )
1691 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1693 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1694 if ( error && !error->IsOK() )
1696 if ( !( error->myAlgo ) &&
1697 !( error->myAlgo = sm->GetAlgo() ))
1699 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1700 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1701 errStruct.comment = error->myComment.c_str();
1702 errStruct.subShapeID = sm->GetId();
1703 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1704 if ( !algoSO->_is_nil() ) {
1705 CORBA::String_var algoName = algoSO->GetName();
1706 errStruct.algoName = algoName;
1709 errStruct.algoName = error->myAlgo->GetName();
1711 errStruct.hasBadMesh = error->HasBadElems();
1714 error_array->length( nbErr );
1717 catch ( SALOME_Exception& S_ex ) {
1718 INFOS( "catch exception "<< S_ex.what() );
1721 return error_array._retn();
1724 //================================================================================
1726 * \brief Return mesh elements preventing computation of a subshape
1728 //================================================================================
1730 SMESH::MeshPreviewStruct*
1731 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1732 CORBA::Short theSubShapeID )
1734 Unexpect aCatch(SALOME_SalomeException);
1735 MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1737 if ( CORBA::is_nil( theMesh ) )
1738 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1740 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1743 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1745 // mesh implementation
1746 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1747 // submesh by subshape id
1748 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1751 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1752 if ( error && error->HasBadElems() )
1754 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1755 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1757 // get nodes of elements and count elements
1758 TNode2LocalIDMap mapNode2LocalID;
1759 list< TNodeLocalID > connectivity;
1760 int i, nbElements = 0, nbConnNodes = 0;
1762 const list<const SMDS_MeshElement*>& badElems =
1763 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1764 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1765 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1766 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1768 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1769 while ( nIt->more() )
1770 connectivity.push_back
1771 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1773 // fill node coords and assign local ids to the nodes
1774 int nbNodes = mapNode2LocalID.size();
1775 result->nodesXYZ.length( nbNodes );
1776 TNodeLocalID node2ID = mapNode2LocalID.begin();
1777 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1778 node2ID->second = i;
1779 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1780 result->nodesXYZ[i].x = node->X();
1781 result->nodesXYZ[i].y = node->Y();
1782 result->nodesXYZ[i].z = node->Z();
1784 // fill connectivity
1785 result->elementConnectivities.length( nbConnNodes );
1786 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1787 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1788 result->elementConnectivities[i] = (*connIt)->second;
1790 // fill element types
1791 result->elementTypes.length( nbElements );
1792 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1794 const SMDS_MeshElement* elem = *elemIt;
1795 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1796 result->elementTypes[i].isPoly = elem->IsPoly();
1797 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1803 catch ( SALOME_Exception& S_ex ) {
1804 INFOS( "catch exception "<< S_ex.what() );
1807 return result._retn();
1810 //================================================================================
1812 * \brief Create a group of elements preventing computation of a sub-shape
1814 //================================================================================
1816 SMESH::ListOfGroups*
1817 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1818 CORBA::Short theSubShapeID,
1819 const char* theGroupName )
1821 Unexpect aCatch(SALOME_SalomeException);
1823 SMESH::ListOfGroups_var groups;
1825 if ( CORBA::is_nil( theMesh ) )
1826 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1829 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1831 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1832 TPythonDump(this) << groups << " = " << this
1833 << ".MakeGroupsOfBadInputElements( "
1834 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1837 catch ( SALOME_Exception& S_ex ) {
1838 INFOS( "catch exception "<< S_ex.what() );
1840 return groups._retn();
1843 //================================================================================
1845 * \brief Returns errors of hypotheses definition
1846 * \param theMesh - the mesh
1847 * \param theSubObject - the main or sub- shape
1848 * \retval SMESH::algo_error_array* - sequence of errors
1850 //================================================================================
1852 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1853 GEOM::GEOM_Object_ptr theSubObject )
1855 Unexpect aCatch(SALOME_SalomeException);
1856 MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1858 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1859 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1861 if ( CORBA::is_nil( theMesh ) )
1862 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1864 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1866 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1867 ASSERT( meshServant );
1868 if ( meshServant ) {
1869 TopoDS_Shape myLocShape;
1870 if(theMesh->HasShapeToMesh())
1871 myLocShape = GeomObjectToShape( theSubObject );
1873 myLocShape = SMESH_Mesh::PseudoShape();
1875 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1876 list< ::SMESH_Gen::TAlgoStateError > error_list;
1877 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1878 // call ::SMESH_Gen::GetAlgoState()
1879 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1880 error_array->length( error_list.size() );
1882 for ( error = error_list.begin(); error != error_list.end(); ++error )
1884 // fill AlgoStateError structure
1885 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1886 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1887 errStruct.algoDim = error->_algoDim;
1888 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1889 errStruct.algoName = "";
1890 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1891 if ( !algoSO->_is_nil() ) {
1892 CORBA::String_var algoName = algoSO->GetName();
1893 errStruct.algoName = algoName.in();
1898 catch ( SALOME_Exception& S_ex ) {
1899 INFOS( "catch exception "<< S_ex.what() );
1901 return error_array._retn();
1904 //=============================================================================
1906 * SMESH_Gen_i::GetSubShapesId
1908 * Get sub-shapes unique ID's list
1910 //=============================================================================
1913 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1914 const SMESH::object_array& theListOfSubShapeObject )
1916 Unexpect aCatch(SALOME_SalomeException);
1917 MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1919 SMESH::long_array_var shapesId = new SMESH::long_array;
1922 if ( CORBA::is_nil( theMainShapeObject ) )
1923 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1927 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1928 TopTools_IndexedMapOfShape myIndexToShape;
1929 TopExp::MapShapes(myMainShape,myIndexToShape);
1931 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1933 GEOM::GEOM_Object_var aShapeObject
1934 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1935 if ( CORBA::is_nil( aShapeObject ) )
1936 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1937 SALOME::BAD_PARAM );
1939 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1940 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1942 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1943 setId.insert(myIndexToShape.FindIndex(F));
1944 SCRUTE(myIndexToShape.FindIndex(F));
1946 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1948 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1949 setId.insert(myIndexToShape.FindIndex(E));
1950 SCRUTE(myIndexToShape.FindIndex(E));
1952 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1954 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1955 setId.insert(myIndexToShape.FindIndex(V));
1956 SCRUTE(myIndexToShape.FindIndex(V));
1959 shapesId->length(setId.size());
1960 set<int>::iterator iind;
1962 for (iind = setId.begin(); iind != setId.end(); iind++)
1965 shapesId[i] = (*iind);
1966 SCRUTE(shapesId[i]);
1970 catch (SALOME_Exception& S_ex)
1972 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1975 return shapesId._retn();
1978 //=============================================================================
1980 * SMESH_Gen_i::Compute
1982 * Compute mesh on a shape
1984 //=============================================================================
1986 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1987 GEOM::GEOM_Object_ptr theShapeObject )
1990 Unexpect aCatch(SALOME_SalomeException);
1991 MESSAGE( "SMESH_Gen_i::Compute" );
1993 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1994 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1995 SALOME::BAD_PARAM );
1997 if ( CORBA::is_nil( theMesh ) )
1998 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1999 SALOME::BAD_PARAM );
2001 // Update Python script
2002 TPythonDump(this) << "isDone = " << this << ".Compute( "
2003 << theMesh << ", " << theShapeObject << ")";
2007 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2008 ASSERT( meshServant );
2009 if ( meshServant ) {
2010 if ( isGeomModifIcon( theMesh ))
2011 meshServant->Clear();
2013 meshServant->Load();
2014 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2015 meshServant->CheckGeomModif();
2016 // get local TopoDS_Shape
2017 TopoDS_Shape myLocShape;
2018 if(theMesh->HasShapeToMesh())
2019 myLocShape = GeomObjectToShape( theShapeObject );
2021 myLocShape = SMESH_Mesh::PseudoShape();
2022 // call implementation compute
2023 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2024 myGen.PrepareCompute( myLocMesh, myLocShape );
2025 int how = ::SMESH_Gen::COMPACT_MESH;
2026 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2027 how |= ::SMESH_Gen::SHAPE_ONLY;
2028 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2029 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2030 myLocMesh.GetMeshDS()->Modified();
2031 UpdateIcons( theMesh );
2033 HighLightInvalid( theMesh, /*isInvalid=*/false );
2037 catch ( std::bad_alloc& ) {
2038 INFOS( "Compute(): lack of memory" );
2040 catch ( SALOME_Exception& S_ex ) {
2041 INFOS( "Compute(): catch exception "<< S_ex.what() );
2044 INFOS( "Compute(): unknown exception " );
2049 //=============================================================================
2051 * SMESH_Gen_i::CancelCompute
2053 * Cancel Compute mesh on a shape
2055 //=============================================================================
2057 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2058 GEOM::GEOM_Object_ptr theShapeObject )
2060 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2062 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2063 TopoDS_Shape myLocShape;
2064 if(theMesh->HasShapeToMesh())
2065 myLocShape = GeomObjectToShape( theShapeObject );
2067 myLocShape = SMESH_Mesh::PseudoShape();
2068 myGen.CancelCompute( myLocMesh, myLocShape);
2072 //=============================================================================
2074 * SMESH_Gen_i::Precompute
2076 * Compute mesh as preview till indicated dimension on shape
2078 //=============================================================================
2080 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2081 GEOM::GEOM_Object_ptr theShapeObject,
2082 SMESH::Dimension theDimension,
2083 SMESH::long_array& theShapesId)
2085 Unexpect aCatch(SALOME_SalomeException);
2086 MESSAGE( "SMESH_Gen_i::Precompute" );
2088 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2089 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2090 SALOME::BAD_PARAM );
2092 if ( CORBA::is_nil( theMesh ) )
2093 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2094 SALOME::BAD_PARAM );
2096 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2099 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2100 meshServant->Load();
2101 ASSERT( meshServant );
2102 if ( meshServant ) {
2103 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2104 meshServant->CheckGeomModif();
2105 // get local TopoDS_Shape
2106 TopoDS_Shape myLocShape;
2107 if(theMesh->HasShapeToMesh())
2108 myLocShape = GeomObjectToShape( theShapeObject );
2110 return result._retn();
2112 // call implementation compute
2113 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2115 ::MeshDimension aDim = (MeshDimension)theDimension;
2116 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2118 int nbShapeId = shapeIds.size();
2119 theShapesId.length( nbShapeId );
2120 // iterates on shapes and collect mesh entities into mesh preview
2121 TSetOfInt::const_iterator idIt = shapeIds.begin();
2122 TSetOfInt::const_iterator idEnd = shapeIds.end();
2123 std::map< int, int > mapOfShIdNb;
2124 std::set< SMESH_TLink > setOfEdge;
2125 std::list< SMDSAbs_ElementType > listOfElemType;
2126 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2127 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2128 TNode2LocalIDMap mapNode2LocalID;
2129 list< TNodeLocalID > connectivity;
2130 int i, nbConnNodes = 0;
2131 std::set< const SMESH_subMesh* > setOfVSubMesh;
2132 // iterates on shapes
2133 for ( ; idIt != idEnd; idIt++ )
2135 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2137 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2138 if ( !sm || !sm->IsMeshComputed() )
2141 const TopoDS_Shape& aSh = sm->GetSubShape();
2142 const int shDim = myGen.GetShapeDim( aSh );
2143 if ( shDim < 1 || shDim > theDimension )
2146 mapOfShIdNb[ *idIt ] = 0;
2147 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2149 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2150 if ( !smDS ) continue;
2152 if ( theDimension == SMESH::DIM_2D )
2154 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2155 while ( faceIt->more() )
2157 const SMDS_MeshElement* face = faceIt->next();
2158 int aNbNode = face->NbNodes();
2160 aNbNode /= 2; // do not take into account additional middle nodes
2162 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2163 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2165 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2166 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2168 listOfElemType.push_back( SMDSAbs_Edge );
2169 connectivity.push_back
2170 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2171 connectivity.push_back
2172 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2178 else if ( theDimension == SMESH::DIM_1D )
2180 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2181 while ( nodeIt->more() )
2183 listOfElemType.push_back( SMDSAbs_Node );
2184 connectivity.push_back
2185 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2187 // add corner nodes by first vertex from edge
2188 SMESH_subMeshIteratorPtr edgeSmIt =
2189 sm->getDependsOnIterator(/*includeSelf*/false,
2190 /*complexShapeFirst*/false);
2191 while ( edgeSmIt->more() )
2193 SMESH_subMesh* vertexSM = edgeSmIt->next();
2194 // check that vertex is not already treated
2195 if ( !setOfVSubMesh.insert( vertexSM ).second )
2197 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2200 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2201 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2202 while ( nodeIt->more() )
2204 listOfElemType.push_back( SMDSAbs_Node );
2205 connectivity.push_back
2206 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2212 // fill node coords and assign local ids to the nodes
2213 int nbNodes = mapNode2LocalID.size();
2214 result->nodesXYZ.length( nbNodes );
2215 TNodeLocalID node2ID = mapNode2LocalID.begin();
2216 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2217 node2ID->second = i;
2218 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2219 result->nodesXYZ[i].x = node->X();
2220 result->nodesXYZ[i].y = node->Y();
2221 result->nodesXYZ[i].z = node->Z();
2223 // fill connectivity
2224 result->elementConnectivities.length( nbConnNodes );
2225 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2226 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2227 result->elementConnectivities[i] = (*connIt)->second;
2230 // fill element types
2231 result->elementTypes.length( listOfElemType.size() );
2232 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2233 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2234 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2236 SMDSAbs_ElementType elemType = *typeIt;
2237 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2238 result->elementTypes[i].isPoly = false;
2239 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2242 // correct number of shapes
2243 theShapesId.length( mapOfShIdNb.size() );
2247 catch ( std::bad_alloc& ) {
2248 INFOS( "Precompute(): lack of memory" );
2250 catch ( SALOME_Exception& S_ex ) {
2251 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2254 INFOS( "Precompute(): unknown exception " );
2256 return result._retn();
2260 //=============================================================================
2262 * SMESH_Gen_i::Evaluate
2264 * Evaluate mesh on a shape
2266 //=============================================================================
2268 SMESH::smIdType_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2269 GEOM::GEOM_Object_ptr theShapeObject)
2271 Unexpect aCatch(SALOME_SalomeException);
2272 MESSAGE( "SMESH_Gen_i::Evaluate" );
2274 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2275 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2277 if ( CORBA::is_nil( theMesh ) )
2278 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2280 SMESH::smIdType_array_var nbels = new SMESH::smIdType_array;
2281 nbels->length(SMESH::Entity_Last);
2282 int i = SMESH::Entity_Node;
2283 for (; i < SMESH::Entity_Last; i++)
2286 // Update Python script
2287 TPythonDump(this) << "theNbElems = " << this << ".Evaluate( "
2288 << theMesh << ", " << theShapeObject << ")";
2292 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2293 ASSERT( meshServant );
2294 if ( meshServant ) {
2295 meshServant->Load();
2296 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2297 meshServant->CheckGeomModif();
2298 // get local TopoDS_Shape
2299 TopoDS_Shape myLocShape;
2300 if(theMesh->HasShapeToMesh())
2301 myLocShape = GeomObjectToShape( theShapeObject );
2303 myLocShape = SMESH_Mesh::PseudoShape();
2304 // call implementation compute
2305 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2306 MapShapeNbElems aResMap;
2307 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2308 MapShapeNbElemsItr anIt = aResMap.begin();
2309 for(; anIt!=aResMap.end(); anIt++) {
2310 const vector<smIdType>& aVec = (*anIt).second;
2311 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2312 smIdType nbElem = aVec[i];
2313 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2315 SMESH_subMesh* sm = anIt->first;
2316 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2317 const SMESH_Algo* algo = sm->GetAlgo();
2318 if ( (algo && !error.get()) || error->IsOK() )
2319 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2323 nbels[i] += aVec[i];
2327 return nbels._retn();
2330 catch ( std::bad_alloc& ) {
2331 INFOS( "Evaluate(): lack of memory" );
2333 catch ( SALOME_Exception& S_ex ) {
2334 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2337 INFOS( "Evaluate(): unknown exception " );
2340 return nbels._retn();
2343 //================================================================================
2345 * \brief Return geometrical object the given element is built on
2346 * \param theMesh - the mesh the element is in
2347 * \param theElementID - the element ID
2348 * \param theGeomName - the name of the result geom object if it is not yet published
2349 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2351 //================================================================================
2353 GEOM::GEOM_Object_ptr
2354 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2355 SMESH::smIdType theElementID,
2356 const char* theGeomName)
2358 Unexpect aCatch(SALOME_SalomeException);
2360 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2361 if ( !geom->_is_nil() ) {
2362 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2363 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2365 // try to find the corresponding SObject
2366 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2367 if ( SObj->_is_nil() ) // submesh can be not found even if published
2369 // try to find published submesh
2370 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2371 if ( !geom->IsMainShape() && list->length() == 1 ) {
2372 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2373 SALOMEDS::ChildIterator_wrap it;
2374 if ( !mainSO->_is_nil() ) {
2375 it = getStudyServant()->NewChildIterator( mainSO );
2377 if ( !it->_is_nil() ) {
2378 for ( it->InitEx(true); it->More(); it->Next() ) {
2379 SALOMEDS::SObject_wrap so = it->Value();
2380 CORBA::Object_var obj = SObjectToObject( so );
2381 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2382 if ( !subGeom->_is_nil() ) {
2383 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2384 if ( subList->length() == 1 && list[0] == subList[0] ) {
2394 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2395 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2397 // return only published geometry
2398 if ( !SObj->_is_nil() ) {
2399 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2400 CORBA::Object_var obj = SObjectToObject( SObj );
2401 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2405 return GEOM::GEOM_Object::_nil();
2408 //================================================================================
2410 * \brief Return geometrical object the given element is built on.
2411 * \param theMesh - the mesh the element is in
2412 * \param theElementID - the element ID
2413 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2415 //================================================================================
2417 GEOM::GEOM_Object_ptr
2418 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2419 SMESH::smIdType theElementID)
2421 Unexpect aCatch(SALOME_SalomeException);
2422 if ( CORBA::is_nil( theMesh ) )
2423 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2425 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2426 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2428 // get a core mesh DS
2429 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2430 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2432 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2433 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2434 // find the element in mesh
2435 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2436 // find a shape id by the element
2437 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2438 // get a geom object by the shape id
2439 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2440 if ( geom->_is_nil() ) {
2441 // try to find a published sub-shape
2442 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2443 SALOMEDS::ChildIterator_wrap it;
2444 if ( !mainSO->_is_nil() ) {
2445 it = getStudyServant()->NewChildIterator( mainSO );
2447 if ( !it->_is_nil() ) {
2448 for ( it->InitEx(true); it->More(); it->Next() ) {
2449 SALOMEDS::SObject_wrap so = it->Value();
2450 CORBA::Object_var obj = SObjectToObject( so );
2451 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2452 if ( !subGeom->_is_nil() ) {
2453 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2454 if ( subList->length() == 1 && shapeID == subList[0] ) {
2462 if ( geom->_is_nil() ) {
2464 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2465 if ( !op->_is_nil() )
2466 geom = op->GetSubShape( mainShape, shapeID );
2471 if ( !geom->_is_nil() ) {
2472 GeomObjectToShape( geom ); // let geom client remember the found shape
2473 return geom._retn();
2478 return GEOM::GEOM_Object::_nil();
2481 //================================================================================
2483 * SMESH_Gen_i::Concatenate
2485 * Concatenate the given meshes into one mesh
2487 //================================================================================
2489 SMESH::SMESH_Mesh_ptr
2490 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2491 CORBA::Boolean theUniteIdenticalGroups,
2492 CORBA::Boolean theMergeNodesAndElements,
2493 CORBA::Double theMergeTolerance,
2494 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2496 return ConcatenateCommon(theMeshesArray,
2497 theUniteIdenticalGroups,
2498 theMergeNodesAndElements,
2504 //================================================================================
2506 * SMESH_Gen_i::ConcatenateWithGroups
2508 * Concatenate the given meshes into one mesh
2509 * Create the groups of all elements from initial meshes
2511 //================================================================================
2513 SMESH::SMESH_Mesh_ptr
2514 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2515 CORBA::Boolean theUniteIdenticalGroups,
2516 CORBA::Boolean theMergeNodesAndElements,
2517 CORBA::Double theMergeTolerance,
2518 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2520 return ConcatenateCommon(theMeshesArray,
2521 theUniteIdenticalGroups,
2522 theMergeNodesAndElements,
2528 //================================================================================
2530 * SMESH_Gen_i::ConcatenateCommon
2532 * Concatenate the given meshes into one mesh
2534 //================================================================================
2536 SMESH::SMESH_Mesh_ptr
2537 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2538 CORBA::Boolean theUniteIdenticalGroups,
2539 CORBA::Boolean theMergeNodesAndElements,
2540 CORBA::Double theMergeTolerance,
2541 CORBA::Boolean theCommonGroups,
2542 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2544 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump(this) );
2545 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2547 // create mesh if theMeshToAppendTo not provided
2548 SMESH::SMESH_Mesh_var newMesh;
2549 if ( CORBA::is_nil( theMeshToAppendTo ))
2550 newMesh = CreateEmptyMesh();
2552 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2553 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2554 if ( !newImpl ) return newMesh._retn();
2557 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2558 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2560 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2561 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2562 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2563 TGroupsMap groupsMap;
2564 TListOfNewGroups listOfNewGroups;
2566 if ( !CORBA::is_nil( theMeshToAppendTo ))
2568 // fill groupsMap with existing groups
2569 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2570 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2572 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2573 if ( !group->_is_nil() )
2575 CORBA::String_var name = group->GetName();
2576 SMESH::ElementType type = group->GetType();
2577 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2582 ::SMESH_MeshEditor newEditor( &locMesh );
2583 ::SMESH_MeshEditor::ElemFeatures elemType;
2585 // loop on sub-meshes
2586 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2588 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2589 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2590 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2591 if ( !initImpl ) continue;
2592 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2596 // assure that IDs increment by one during iteration
2597 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2598 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2599 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2600 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2602 initMeshDS->Modified();
2603 initMeshDS->CompactMesh();
2606 // remember nb of elements before filling in
2607 SMESH::smIdType_array_var prevState = newMesh->GetNbElementsByType();
2611 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2612 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2613 while ( elemIt->more() )
2615 SMESH_NodeXYZ node = elemIt->next();
2616 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2621 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2622 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2623 bool hasElems = (( srcElemTypes->length() > 1 ) ||
2624 ( srcElemTypes->length() == 1 && srcElemTypes[0] != SMESH::NODE ));
2627 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2628 while ( elemIt->more() )
2630 const SMDS_MeshElement* elem = elemIt->next();
2631 elemType.myNodes.resize( elem->NbNodes() );
2633 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2634 for ( int k = 0; itNodes->more(); k++)
2636 const SMDS_MeshNode* node = itNodes->next();
2637 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2640 // creates a corresponding element on existent nodes in new mesh
2641 newElems[ elem->GetID() ] =
2642 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2644 newEditor.ClearLastCreated(); // forget the history
2648 // create groups of just added elements
2649 SMESH::SMESH_Group_var newGroup;
2650 SMESH::ElementType groupType;
2651 if ( theCommonGroups )
2654 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2656 // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2657 static_assert( sizeof(typeNames) / sizeof(const char*) ==SMESH::NB_ELEMENT_TYPES,
2658 "Update names of ElementType's!!!" );
2660 SMESH::smIdType_array_var curState = newMesh->GetNbElementsByType();
2662 for( groupType = SMESH::NODE;
2663 groupType < SMESH::NB_ELEMENT_TYPES;
2664 groupType = (SMESH::ElementType)( groupType + 1 ))
2666 if ( curState[ groupType ] <= prevState[ groupType ])
2667 continue; // no elements of groupType added from the i-th mesh
2669 // make a group name
2670 std::string groupName = "Gr";
2671 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2673 CORBA::String_var name = meshSO->GetName();
2677 groupName += typeNames[ groupType ];
2679 // make and fill a group
2680 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2681 std::vector< const SMDS_MeshElement* > & elemVec =
2682 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2683 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2685 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2687 for ( size_t j = 0; j < elemVec.size(); ++j )
2689 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2690 grpDS->Add( elemVec[j] );
2694 listOfNewGroups.clear();
2695 listOfNewGroups.push_back( newGroup );
2696 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2701 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2705 SMESH::SMESH_GroupBase_ptr group;
2706 CORBA::String_var groupName;
2707 SMESH::smIdType_array_var newIDs = new SMESH::smIdType_array();
2709 // loop on groups of a source mesh
2710 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2711 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2713 group = listOfGroups[iG];
2714 groupType = group->GetType();
2715 groupName = group->GetName();
2716 std::string name = groupName.in();
2718 // convert a list of IDs
2719 newIDs->length( group->Size() );
2720 std::vector< const SMDS_MeshElement* > & elemVec =
2721 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2722 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2724 while ( itGrElems->more() )
2726 const SMDS_MeshElement* elem = itGrElems->next();
2727 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2729 newIDs[ nbElems++ ] = newElem->GetID();
2731 newIDs->length( nbElems );
2733 // check that a current group name and type don't have identical ones in final mesh
2734 listOfNewGroups.clear();
2735 TNameAndType nameAndType( name, groupType );
2736 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2737 if ( anIter == groupsMap.end() )
2739 // add a new group in the mesh
2740 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2741 newGroup->Add( newIDs );
2743 listOfNewGroups.push_back( newGroup );
2744 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2746 else if ( theUniteIdenticalGroups )
2748 // unite identical groups
2749 TListOfNewGroups& aNewGroups = anIter->second;
2750 aNewGroups.front()->Add( newIDs );
2754 // rename identical groups
2755 newGroup = newImpl->CreateGroup( groupType, groupName );
2756 newGroup->Add( newIDs );
2758 TListOfNewGroups& newGroups = anIter->second;
2759 std::string newGroupName;
2760 if ( newGroups.size() == 1 )
2762 newGroupName = name + "_1";
2763 newGroups.front()->SetName( newGroupName.c_str() );
2765 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2766 newGroup->SetName( newGroupName.c_str() );
2767 newGroups.push_back( newGroup );
2770 } // if an IDSource is a mesh
2773 if ( theMergeNodesAndElements ) // merge nodes
2775 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2776 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2777 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2778 /*SeparateCornersAndMedium=*/ false );
2779 newEditor.MergeNodes( groupsOfNodes );
2781 newEditor.MergeEqualElements();
2784 // Update Python script
2785 pythonDump << newMesh << " = " << this
2786 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2787 << theMeshesArray << ", "
2788 << theUniteIdenticalGroups << ", "
2789 << theMergeNodesAndElements << ", "
2790 << TVar( theMergeTolerance ) << ", "
2791 << theMeshToAppendTo << " )";
2793 pPythonDump.reset(); // enable python dump from GetGroups()
2795 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2796 if ( !newMesh->_is_nil() )
2798 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2801 // IPAL21468 Change icon of compound because it need not be computed.
2802 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2803 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2805 newMeshDS->Modified();
2807 return newMesh._retn();
2811 //================================================================================
2813 * \brief Create a mesh by copying a part of another mesh
2814 * \param mesh - TetraHedron mesh
2815 * \param meshName Name of the created mesh
2816 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2818 //================================================================================
2820 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateDualMesh(SMESH::SMESH_IDSource_ptr mesh,
2821 const char* meshName,
2822 CORBA::Boolean adapt_to_shape)
2824 Unexpect aCatch(SALOME_SalomeException);
2826 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2827 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2829 // 1. Get source mesh
2831 if ( CORBA::is_nil( mesh ))
2832 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2834 SMESH::SMESH_Mesh_var srcMesh = mesh->GetMesh();
2835 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2837 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2839 CORBA::String_var mesh_var=GetORB()->object_to_string(mesh);
2840 std::string mesh_ior = mesh_var.in();
2842 //temporary folder for the generation of the med file
2843 fs::path tmp_folder = fs::temp_directory_path() / fs::unique_path(fs::path("dual_mesh-%%%%"));
2844 fs::create_directories(tmp_folder);
2845 fs::path dual_mesh_file = tmp_folder / fs::path("tmp_dual_mesh.med");
2846 std::string mesh_name(meshName);
2847 MESSAGE("Working in folder" + tmp_folder.string());
2849 // Running Python script
2850 assert(Py_IsInitialized());
2851 PyGILState_STATE gstate;
2852 gstate = PyGILState_Ensure();
2861 std::string cmd="import salome.smesh.smesh_tools as smt\n";
2862 cmd +="smt.smesh_create_dual_mesh(\"" + mesh_ior + "\", r\"" +
2863 dual_mesh_file.string() + "\", mesh_name=\"" + mesh_name + "\", adapt_to_shape=" + ats + ")";
2866 PyObject *py_main = PyImport_AddModule("__main__");
2867 PyObject *py_dict = PyModule_GetDict(py_main);
2868 PyObject *local_dict = PyDict_New();
2870 PyRun_String(cmd.c_str(), Py_file_input, py_dict, local_dict);
2872 if (PyErr_Occurred()) {
2873 // Restrieving python error
2874 MESSAGE("Catching error");
2875 PyObject *errtype, *errvalue, *traceback;
2876 PyErr_Fetch(&errtype, &errvalue, &traceback);
2877 if(errvalue != NULL) {
2878 MESSAGE("Error has a value");
2879 PyObject *s = PyObject_Str(errvalue);
2881 std::string msg = PyUnicode_AsUTF8AndSize(s, &size);
2882 msg = "Issue with the execution of create_dual_mesh:\n"+msg;
2883 MESSAGE("throwing exception");
2884 // We need to deactivate the GIL before throwing the exception
2885 PyGILState_Release(gstate);
2886 THROW_SALOME_CORBA_EXCEPTION(msg.c_str(), SALOME::INTERNAL_ERROR );
2889 Py_XDECREF(errvalue);
2890 Py_XDECREF(errtype);
2891 Py_XDECREF(traceback);
2894 PyGILState_Release(gstate);
2896 MESSAGE("Mesh created in " + dual_mesh_file.string());
2898 // Import created MED
2899 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2900 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2902 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2903 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2904 if ( !meshSO->_is_nil() )
2906 SetName( meshSO, meshName, meshName );
2907 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2909 int ret = newMesh_i->ImportMEDFile(dual_mesh_file.string().c_str(), meshName);
2911 THROW_SALOME_CORBA_EXCEPTION( "Issue when importing mesh", SALOME::INTERNAL_ERROR );
2914 SMESH_Mesh& newMesh2 = newMesh_i->GetImpl();
2917 MESSAGE("Loading file: " << dual_mesh_file.string() << " with mesh " << meshName);
2918 int ret = newMesh2.MEDToMesh(dual_mesh_file.c_str(), meshName);
2921 newMesh_i->GetImpl().GetMeshDS()->Modified();
2923 *pyDump << newMesh << " = " << this
2924 << ".CreateDualMesh("
2926 << "'" << mesh_name << "', "
2929 pyDumpDeleter.reset(); // allow dump in GetGroups()
2931 if ( srcMesh_i->GetImpl().GetGroupIds().size() > 0 ) // dump created groups
2932 MESSAGE("Dump of groups");
2933 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2936 fs::remove_all(tmp_folder);
2939 return newMesh._retn();
2942 //================================================================================
2944 * \brief Create a mesh by copying a part of another mesh
2945 * \param meshPart - a part of mesh to copy
2946 * \param toCopyGroups - to create in the new mesh groups
2947 * the copied elements belongs to
2948 * \param toKeepIDs - to preserve IDs of the copied elements or not
2949 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2951 //================================================================================
2953 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2954 const char* meshName,
2955 CORBA::Boolean toCopyGroups,
2956 CORBA::Boolean toKeepIDs)
2958 Unexpect aCatch(SALOME_SalomeException);
2960 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2961 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2963 // 1. Get source mesh
2965 if ( CORBA::is_nil( meshPart ))
2966 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2968 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2969 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2971 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2973 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2975 // 2. Make a new mesh
2977 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2978 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2980 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2981 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2982 if ( !meshSO->_is_nil() )
2984 SetName( meshSO, meshName, "Mesh" );
2985 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2987 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2988 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2989 ::SMESH_MeshEditor::ElemFeatures elemType;
2991 // 3. Get elements to copy
2993 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2994 TIDSortedElemSet srcElems;
2995 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2996 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2999 srcElemIt = srcMeshDS->elementsIterator();
3000 srcNodeIt = srcMeshDS->nodesIterator();
3004 SMESH::smIdType_array_var ids = meshPart->GetIDs();
3005 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
3007 for ( CORBA::ULong i=0; i < ids->length(); i++ )
3008 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
3009 srcElems.insert( elem );
3013 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
3014 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
3015 srcElems.insert( elem );
3017 if ( srcElems.empty() )
3018 return newMesh._retn();
3020 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
3021 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
3026 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
3027 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
3028 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
3030 const SMDS_MeshNode *nSrc, *nTgt;
3031 vector< const SMDS_MeshNode* > nodes;
3032 while ( srcElemIt->more() )
3034 const SMDS_MeshElement * elem = srcElemIt->next();
3036 nodes.resize( elem->NbNodes());
3037 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3039 for ( iN = 0; nIt->more(); ++iN )
3041 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3042 nTgt = newMeshDS->FindNode( nSrc->GetID());
3044 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3049 for ( iN = 0; nIt->more(); ++iN )
3051 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3052 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
3054 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3055 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
3059 if ( elem->GetType() != SMDSAbs_Node )
3061 elemType.Init( elem, /*basicOnly=*/false );
3062 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
3064 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
3065 if ( toCopyGroups && !toKeepIDs )
3066 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
3068 } // while ( srcElemIt->more() )
3070 // 4(b). Copy free nodes
3072 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3074 while ( srcNodeIt->more() )
3076 nSrc = srcNodeIt->next();
3077 if ( nSrc->NbInverseElements() == 0 )
3080 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3082 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3089 int nbNewGroups = 0;
3092 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3093 while ( gIt->more() )
3095 SMESH_Group* group = gIt->next();
3096 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3098 // Check group type. We copy nodal groups containing nodes of copied element
3099 SMDSAbs_ElementType groupType = groupDS->GetType();
3100 if ( groupType != SMDSAbs_Node &&
3101 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3102 continue; // group type differs from types of meshPart
3104 // Find copied elements in the group
3105 vector< const SMDS_MeshElement* > groupElems;
3106 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3109 const SMDS_MeshElement* foundElem;
3110 if ( groupType == SMDSAbs_Node )
3112 while ( eIt->more() )
3113 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3114 groupElems.push_back( foundElem );
3118 while ( eIt->more() )
3119 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3120 groupElems.push_back( foundElem );
3125 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3126 if ( e2eMap.empty() ) continue;
3127 smIdType minID = e2eMap.begin()->first->GetID();
3128 smIdType maxID = e2eMap.rbegin()->first->GetID();
3129 TE2EMap::iterator e2e;
3130 while ( eIt->more() && groupElems.size() < e2eMap.size())
3132 const SMDS_MeshElement* e = eIt->next();
3133 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3134 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3135 groupElems.push_back( e2e->second );
3139 if ( !groupElems.empty() )
3141 SMESH::SMESH_Group_var newGroupObj =
3142 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3143 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3145 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3146 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3147 for ( unsigned i = 0; i < groupElems.size(); ++i )
3148 smdsGroup.Add( groupElems[i] );
3156 newMeshDS->Modified();
3158 *pyDump << newMesh << " = " << this
3159 << ".CopyMesh( " << meshPart << ", "
3160 << "'" << meshName << "', "
3161 << toCopyGroups << ", "
3162 << toKeepIDs << ")";
3164 pyDumpDeleter.reset(); // allow dump in GetGroups()
3166 if ( nbNewGroups > 0 ) // dump created groups
3167 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3169 return newMesh._retn();
3173 namespace // utils for CopyMeshWithGeom()
3175 typedef std::map< std::string, std::string > TStr2StrMap;
3176 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3177 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3178 typedef std::map< std::string, int > TName2IndexMap;
3180 //================================================================================
3182 * \brief Return a new sub-shape corresponding to an old one
3184 //================================================================================
3188 SMESH_Mesh_i* mySrcMesh_i;
3189 SMESH_Mesh_i* myNewMesh_i;
3190 SMESH_Gen_i* myGen_i;
3194 TStr2StrMap myOld2NewEntryMap; // map of study entries
3196 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3197 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3198 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3201 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3203 // not directly relating to shape search
3204 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3206 //================================================================================
3208 * \brief Constructor
3210 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3211 SMESH_Mesh_i* newMesh_i,
3212 SMESH_Gen_i* smeshGen_i )
3213 : mySrcMesh_i( srcMesh_i ),
3214 myNewMesh_i( newMesh_i ),
3215 myGen_i ( smeshGen_i ),
3216 myToPublish( smeshGen_i->IsEnablePublish() ),
3217 myGIPMapDone( false )
3219 // retrieve from the study shape mapping made thanks to
3220 // "Set presentation parameters and sub-shapes from arguments" option
3222 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3223 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3224 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3225 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3226 if ( newSO->_is_nil() )
3228 myToPublish = false;
3231 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3233 CORBA::String_var oldEntry = oldSO->GetID();
3234 CORBA::String_var newEntry = newSO->GetID();
3235 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3236 std::string( newEntry.in() )));
3237 std::string newMainEntry = newEntry.in();
3239 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3240 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3241 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3242 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3243 /*groupsOnly=*/false );
3244 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3246 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3247 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3248 bool refFound = false;
3249 for ( ; anIter->More(); anIter->Next() )
3251 SALOMEDS::SObject_wrap so = anIter->Value();
3252 if ( so->ReferencedObject( oldSO.inout() ))
3254 oldEntry = oldSO->GetID();
3255 newEntry = newSO->GetID();
3256 if (( refFound = ( newMainEntry != oldEntry.in() )))
3257 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3258 std::string( newEntry.in() )));
3263 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3264 if ( father->_is_equivalent( mainShapeNew ))
3266 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3267 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3268 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3269 CORBA::String_var name = newSO->GetName();
3271 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3277 //================================================================================
3279 * \brief Find a new sub-shape corresponding to an old one
3281 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3284 return GEOM::GEOM_Object::_duplicate( oldShape );
3286 GEOM::GEOM_Object_var newShape;
3288 if ( CORBA::is_nil( oldShape ))
3289 return newShape._retn();
3291 if ( !isChildOfOld( oldShape ))
3292 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3294 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3295 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3297 // try to find by entry or name
3300 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3301 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3302 if ( o2nID != myOld2NewEntryMap.end() )
3304 newShape = getShapeByEntry( o2nID->second );
3306 if ( newShape->_is_nil() )
3308 CORBA::String_var name = oldShape->GetName();
3309 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3310 if ( n2ind != myName2SubshapeIndex.end() )
3312 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3313 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3314 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3315 if ( oldIndices->length() == 0 ||
3316 newIndices->length() == 0 ||
3317 getShapeType( myNewMesh_i, newIndices[0] ) !=
3318 getShapeType( mySrcMesh_i, oldIndices[0] ))
3319 newShape = GEOM::GEOM_Object::_nil();
3324 if ( newShape->_is_nil() )
3326 // try to construct a new sub-shape using myGIPMap
3328 std::vector< int > newIndices;
3329 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3330 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3332 findNewIDs( oldIndices[i], newIndices );
3334 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3337 newShape = getInPlace( oldShape );
3339 if ( !newIndices.empty() && newShape->_is_nil() )
3341 // search for a sub-shape with same ids
3342 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3343 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3344 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3345 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3347 if ( newShape->_is_nil() )
3350 // create a new shape
3351 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3353 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3355 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3356 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3358 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3359 newIndicesList->length( newIndices.size() );
3360 for ( size_t i = 0; i < newIndices.size(); ++i )
3361 newIndicesList[ i ] = newIndices[ i ];
3362 grOp->UnionIDs( newShape, newIndicesList );
3366 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3367 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3376 if ( !newShape->_is_nil() && myToPublish )
3378 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3379 if ( !newEntry.in() || !newEntry.in()[0] )
3381 CORBA::String_var name = oldShape->GetName();
3382 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3383 newEntry = newShape->GetStudyEntry();
3384 oldEntry = oldShape->GetStudyEntry();
3385 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3386 std::string( newEntry.in() )));
3390 return newShape._retn();
3393 //================================================================================
3395 * \brief Return a study entry of a new shape by study entry of the old one
3397 std::string FindNew( const std::string & oldEntry )
3402 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3403 if ( o2nID != myOld2NewEntryMap.end() )
3404 return o2nID->second;
3406 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3407 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3410 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3411 if ( newShape->_is_nil() )
3412 return std::string();
3414 CORBA::String_var newEntry = newShape->GetStudyEntry();
3415 return newEntry.in();
3418 //================================================================================
3420 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3421 * Return zero if not found or there are more than one new ID
3423 int FindNew( int oldID )
3432 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3434 if ( myGIPMap[ oldID ].length() == 1 )
3436 newID = myGIPMap[ oldID ][ 0 ];
3438 else if ( myGIPMap[ oldID ].length() > 1 &&
3439 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3441 // select a meshed VERTEX
3442 SMESH_subMesh* newSM;
3443 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3444 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3445 ( !newSM->IsEmpty() ))
3446 newID = myGIPMap[ oldID ][ i ];
3452 //================================================================================
3454 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3455 * Return zero if the old shape is not kept as is in the new shape.
3457 int FindNewNotChanged( SMESH_subMesh* oldSM )
3460 return oldSM->GetId();
3462 int newID = FindNew( oldSM->GetId() );
3466 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3470 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3471 // one new sub-shape of the same type.
3473 if ( oldSM->DependsOn().size() !=
3474 newSM->DependsOn().size() )
3477 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3478 while ( srcSMIt->more() )
3480 oldSM = srcSMIt->next();
3481 int newSubID = FindNew( oldSM->GetId() );
3482 if ( getShapeType( myNewMesh_i, newSubID ) !=
3483 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3489 //================================================================================
3491 * \brief Return shape by study entry
3493 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3495 GEOM::GEOM_Object_var shape;
3496 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3497 if ( !so->_is_nil() )
3499 CORBA::Object_var obj = so->GetObject();
3500 shape = GEOM::GEOM_Object::_narrow( obj );
3502 return shape._retn();
3505 //================================================================================
3507 * \brief Fill myGIPMap by calling GetInPlaceMap()
3511 if ( !myGIPMapDone )
3513 myGIPMapDone = true;
3515 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3516 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3517 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3518 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3521 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3525 myGIPMap = new GEOM::ListOfListOfLong();
3530 //================================================================================
3532 * \brief Get new sub-shape by calling GetInPlace()
3534 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3536 GEOM::GEOM_Object_var newShape;
3538 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3539 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3540 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3543 newShape = op->GetInPlace( mainShapeNew, oldShape );
3548 return newShape._retn();
3551 //================================================================================
3553 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3554 * number of found IDs
3556 int findNewIDs( int oldID, std::vector< int >& newIDs )
3558 size_t prevNbIDs = newIDs.size();
3560 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3562 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3563 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3565 return newIDs.size() - prevNbIDs;
3568 //================================================================================
3570 * \brief Check if an object relates to the old shape
3572 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3574 if ( CORBA::is_nil( oldShape ))
3576 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3577 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3578 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3579 mainShapeOld1->_is_equivalent( oldShape ));
3582 //================================================================================
3584 * \brief Return shape type by shape ID
3586 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3588 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3589 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3590 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3593 //================================================================================
3595 * \brief Store a source sub-shape for which a counterpart not found and
3596 * a smesh object invalid due to that
3598 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3599 SALOMEDS::SObject_wrap smeshSO )
3601 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3602 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3604 CORBA::String_var smeshEntry = smeshSO->GetID();
3605 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3609 //================================================================================
3611 * \brief Store a source sub-shape for which a counterpart not found and
3612 * a smesh object invalid due to that
3614 void AddInvalid( std::string geomEntry,
3615 SALOMEDS::SObject_wrap smeshSO )
3617 if ( !geomEntry.empty() )
3619 CORBA::String_var smeshEntry = smeshSO->GetID();
3620 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3624 //================================================================================
3626 * \brief Store a source sub-shape for which a counterpart not found and
3627 * a smesh object invalid due to that
3629 void AddInvalid( int oldGeomID,
3630 SALOMEDS::SObject_wrap smeshSO )
3632 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3633 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3636 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3637 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3639 SMESH_Comment geomName( typeName[ shapeType ]);
3640 geomName << " #" << oldGeomID;
3642 CORBA::String_var smeshEntry = smeshSO->GetID();
3643 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3646 //================================================================================
3648 * \brief Return entries of a source sub-shape for which a counterpart not found and
3649 * of smesh objects invalid due to that
3651 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3652 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3655 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3656 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3658 nbSO += 1 + entry2entrySet->second.size();
3660 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3661 theInvalidEntries->length ( nbSO );
3662 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3664 entry2entrySet = myInvalidMap.begin();
3665 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3667 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3669 std::set< std::string > & entrySet = entry2entrySet->second;
3670 std::set< std::string >::iterator entry = entrySet.begin();
3671 for ( ; entry != entrySet.end(); ++entry )
3673 theInvalidEntries[ iEntry++ ] = entry->c_str();
3675 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3676 if ( !so->_is_nil() )
3677 theInvalidMeshSObjects[ iSO++ ] = so;
3682 }; // struct ShapeMapper
3684 //================================================================================
3686 * \brief Append an item to a CORBA sequence
3688 template < class CORBA_seq, class ITEM >
3689 void append( CORBA_seq& seq, ITEM item )
3691 if ( !CORBA::is_nil( item ))
3693 seq->length( 1 + seq->length() );
3694 seq[ seq->length() - 1 ] = item;
3697 } // namespace // utils for CopyMeshWithGeom()
3699 //================================================================================
3701 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3702 * \param [in] sourceMesh - a mesh to copy
3703 * \param [in] newGeometry - a new geometry
3704 * \param [in] toCopyGroups - to create groups in the new mesh
3705 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3706 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3707 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3708 * \param [out] newMesh - return a new mesh
3709 * \param [out] newGroups - return new groups
3710 * \param [out] newSubmeshes - return new sub-meshes
3711 * \param [out] newHypotheses - return new algorithms and hypotheses
3712 * \param [out] invalidEntries - return study entries of objects whose
3713 * counterparts are not found in the newGeometry, followed by entries
3714 * of mesh sub-objects that are invalid because they depend on a not found
3715 * preceding sub-shape
3716 * \return CORBA::Boolean - is a success
3718 //================================================================================
3720 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3721 GEOM::GEOM_Object_ptr theNewGeometry,
3722 const char* theMeshName,
3723 CORBA::Boolean theToCopyGroups,
3724 CORBA::Boolean theToReuseHypotheses,
3725 CORBA::Boolean theToCopyElements,
3726 SMESH::SMESH_Mesh_out theNewMesh,
3727 SMESH::ListOfGroups_out theNewGroups,
3728 SMESH::submesh_array_out theNewSubmeshes,
3729 SMESH::ListOfHypothesis_out theNewHypotheses,
3730 SMESH::string_array_out theInvalidEntries)
3732 if ( CORBA::is_nil( theSourceMesh ) ||
3733 CORBA::is_nil( theNewGeometry ))
3734 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3736 if ( !theSourceMesh->HasShapeToMesh() )
3737 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3742 TPythonDump pyDump(this); // prevent dump from CreateMesh()
3744 theNewMesh = CreateMesh( theNewGeometry );
3745 theNewGroups = new SMESH::ListOfGroups();
3746 theNewSubmeshes = new SMESH::submesh_array();
3747 theNewHypotheses = new SMESH::ListOfHypothesis();
3748 theInvalidEntries = new SMESH::string_array();
3750 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3752 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3753 GEOM::GEOM_Object_var geom, newGeom;
3754 SALOMEDS::SObject_wrap so;
3756 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3757 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3760 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3762 // treat hypotheses of mesh and sub-meshes
3763 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3764 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3766 bool isSubMesh = ( iSM < smList->length() );
3769 // create a new sub-mesh
3770 SMESH::SMESH_subMesh_var newSM;
3771 geom = smList[iSM]->GetSubShape();
3772 so = ObjectToSObject( smList[iSM] );
3773 CORBA::String_var name;
3774 if ( !so->_is_nil() )
3775 name = so->GetName();
3776 newGeom = shapeMapper.FindNew( geom );
3777 if ( newGeom->_is_nil() )
3779 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3780 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3785 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3787 append( theNewSubmeshes, newSM );
3789 if ( newGeom->_is_nil() )
3790 continue; // don't assign hypotheses
3794 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3796 so = ObjectToSObject( theNewMesh );
3797 SetName( so, theMeshName, "Mesh" );
3800 // assign hypotheses
3801 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3802 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3804 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3805 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3807 // get geometry hyp depends on
3808 std::vector< std::string > entryArray;
3809 std::vector< int > subIDArray;
3810 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3812 if ( !theToReuseHypotheses || dependsOnGeom )
3814 // create a new hypothesis
3815 CORBA::String_var type = hyp->GetName();
3816 CORBA::String_var lib = hyp->GetLibName();
3817 CORBA::String_var data = hyp_i->SaveTo();
3820 hyp = CreateHypothesis( type, lib );
3821 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3822 hyp_i->LoadFrom( data.in() );
3823 append( theNewHypotheses, hyp );
3827 // update geometry hyp depends on
3828 if ( dependsOnGeom )
3830 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3832 if ( !entryArray[ iGeo ].empty() )
3834 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3835 if ( newEntry.empty() )
3838 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3839 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3841 entryArray[ iGeo ] = newEntry;
3844 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3846 if ( subIDArray[ iGeo ] > 0 )
3848 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3852 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3853 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3855 subIDArray[ iGeo ] = newID;
3858 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3862 CORBA::String_var errorText;
3863 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3864 if ( errorText.in()[0] )
3867 } // loop on hypotheses
3868 } // loop on sub-meshes and mesh
3871 // copy mesh elements, keeping IDs
3872 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3873 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3875 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3876 ::SMESH_MeshEditor::ElemFeatures elemData;
3878 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3879 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3880 /*vertexLast=*/false);
3881 while ( srcSMIt->more() )
3883 SMESH_subMesh* srcSM = srcSMIt->next();
3884 if ( srcSM->IsEmpty() )
3885 continue; // not yet computed
3886 int newID = shapeMapper.FindNewNotChanged( srcSM );
3890 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3891 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3892 while ( nIt->more() )
3894 SMESH_NodeXYZ node( nIt->next() );
3895 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3897 const SMDS_PositionPtr pos = node->GetPosition();
3898 const double* uv = pos->GetParameters();
3899 switch ( pos->GetTypeOfPosition() )
3901 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3902 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3903 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3904 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3908 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3909 while( eIt->more() )
3911 const SMDS_MeshElement* e = eIt->next();
3912 elemData.Init( e, /*basicOnly=*/false );
3913 elemData.SetID( e->GetID() );
3914 elemData.myNodes.resize( e->NbNodes() );
3915 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3917 for ( iN = 0; nnIt->more(); ++iN )
3919 const SMDS_MeshNode* srcNode = nnIt->next();
3920 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3921 if ( !elemData.myNodes[ iN ])
3924 if ( iN == elemData.myNodes.size() )
3925 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3926 newMeshDS->SetMeshElementOnShape( newElem, newID );
3928 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3929 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3932 newMeshDS->Modified();
3938 TStr2StrMap old2newGroupMap;
3940 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3942 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3943 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3944 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3946 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3947 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3948 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3950 CORBA::String_var name = groups[ i ]->GetName();
3951 SMESH::ElementType elemType = groups[ i ]->GetType();
3953 SMESH::SMESH_GroupBase_var newGroup;
3955 if ( !stdlGroup->_is_nil() )
3957 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3959 SMESH::smIdType_array_var elemIDs = stdlGroup->GetIDs();
3960 const bool isElem = ( elemType != SMESH::NODE );
3961 CORBA::ULong iE = 0;
3962 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3963 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3965 if ( iE < elemIDs->length() )
3967 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3968 stdlGroup->Add( elemIDs );
3969 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3973 else if ( !geomGroup->_is_nil() )
3975 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3976 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3977 if ( newGeom->_is_nil() )
3979 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3980 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3985 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3988 else if ( !fltrGroup->_is_nil() )
3990 // replace geometry in a filter
3991 SMESH::Filter_var filter = fltrGroup->GetFilter();
3992 SMESH::Filter::Criteria_var criteria;
3993 filter->GetCriteria( criteria.out() );
3995 bool isMissingGroup = false;
3996 std::vector< std::string > badEntries;
3998 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
4000 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
4001 switch ( criteria[ iCr ].Type )
4003 case SMESH::FT_BelongToMeshGroup:
4005 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
4006 btgg->SetGroupID( thresholdID );
4007 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
4008 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
4009 if ( refGroupSO->_is_nil() )
4011 CORBA::String_var refID = refGroupSO->GetID();
4012 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
4013 if ( o2nID == old2newGroupMap.end() )
4015 isMissingGroup = true; // corresponding new group not yet created
4018 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
4020 if ( o2nID->second.empty() ) // new referred group is invalid
4021 badEntries.push_back( refID.in() );
4024 case SMESH::FT_BelongToGeom:
4025 case SMESH::FT_BelongToPlane:
4026 case SMESH::FT_BelongToCylinder:
4027 case SMESH::FT_BelongToGenSurface:
4028 case SMESH::FT_LyingOnGeom:
4030 std::string newID = shapeMapper.FindNew( thresholdID );
4031 criteria[ iCr ].ThresholdID = newID.c_str();
4032 if ( newID.empty() )
4033 badEntries.push_back( thresholdID );
4036 case SMESH::FT_ConnectedElements:
4038 if ( thresholdID && thresholdID[0] )
4040 std::string newID = shapeMapper.FindNew( thresholdID );
4041 criteria[ iCr ].ThresholdID = newID.c_str();
4042 if ( newID.empty() )
4043 badEntries.push_back( thresholdID );
4049 } // loop on criteria
4051 if ( isMissingGroup && i < nbGroups )
4053 // to treat the group again
4054 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
4058 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
4059 newFilter->SetCriteria( criteria );
4061 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
4062 newFilter->UnRegister();
4064 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4065 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
4066 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
4068 if ( isMissingGroup ) // all groups treated but a referred groups still not found
4070 invalidSObjects.push_back( ObjectToSObject( newGroup ));
4073 if ( !badEntries.empty() )
4076 } // treat a group on filter
4078 append( theNewGroups, newGroup );
4080 // fill old2newGroupMap
4081 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4082 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4083 if ( !srcSO->_is_nil() )
4085 CORBA::String_var srcID, newID("");
4086 srcID = srcSO->GetID();
4087 if ( !newSO->_is_nil() )
4088 newID = newSO->GetID();
4089 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4090 std::string( newID.in() )));
4093 if ( newGroup->_is_nil() )
4098 newMeshDS->CompactMesh();
4101 if ( !theMeshName || !theMeshName[0] )
4103 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4104 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4105 CORBA::String_var oldName = soOld->GetName();
4106 SetName( soNew, oldName.in(), "Mesh" );
4108 // mark invalid objects
4109 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4111 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4112 highLightInvalid( invalidSObjects[i].in(), true );
4115 << theNewMesh << ", "
4116 << theNewGroups << ", "
4117 << *theNewSubmeshes.ptr() << ", "
4118 << *theNewHypotheses.ptr() << ", "
4119 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4120 << theSourceMesh << ", "
4121 << theNewGeometry << ", "
4122 << "'" << theMeshName << "', "
4123 << theToCopyGroups << ", "
4124 << theToReuseHypotheses << ", "
4125 << theToCopyElements << " )";
4127 SMESH_CATCH( SMESH::throwCorbaException );
4132 //================================================================================
4134 * \brief Get version of MED format being used.
4136 //================================================================================
4138 char* SMESH_Gen_i::GetMEDFileVersion()
4140 MED::TInt majeur, mineur, release;
4141 majeur = mineur = release = 0;
4142 MED::GetVersionRelease(majeur, mineur, release);
4143 std::ostringstream version;
4144 version << majeur << "." << mineur << "." << release;
4145 return CORBA::string_dup( version.str().c_str() );
4148 //================================================================================
4150 * SMESH_Gen_i::GetMEDVersion
4152 * Get MED version of the file by its name
4154 //================================================================================
4156 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4158 std::string version = MED::GetMEDVersion( theFileName );
4159 return CORBA::string_dup( version.c_str() );
4162 //================================================================================
4164 * SMESH_Gen_i::CheckCompatibility
4166 * Check compatibility of file with MED format being used, read only.
4168 //================================================================================
4170 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4172 return MED::CheckCompatibility( theFileName );
4175 //================================================================================
4177 * SMESH_Gen_i::CheckWriteCompatibility
4179 * Check compatibility of file with MED format being used, for append on write.
4181 //================================================================================
4183 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4185 return MED::CheckCompatibility( theFileName, true );
4188 //================================================================================
4190 * SMESH_Gen_i::GetMeshNames
4192 * Get names of meshes defined in file with the specified name
4194 //================================================================================
4195 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4198 SMESH::string_array_var aResult = new SMESH::string_array();
4199 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4201 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4203 aResult->length( aNbMeshes );
4204 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4205 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4206 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4209 return aResult._retn();
4212 //=============================================================================
4216 * Save SMESH module's data
4218 //=============================================================================
4220 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4225 Kernel_Utils::Localizer loc;
4227 if (!myStudyContext)
4230 // Store study contents as a set of python commands
4233 SALOMEDS::Study_var aStudy = getStudyServant();
4235 // Declare a byte stream
4236 SALOMEDS::TMPFile_var aStreamFile;
4238 // Obtain a temporary dir
4239 TCollection_AsciiString tmpDir =
4240 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4242 // Create a sequence of files processed
4243 SALOMEDS_Tool::ListOfFiles aFileSeq;
4244 aFileSeq.reserve( NUM_TMP_FILES );
4246 TCollection_AsciiString aStudyName( "" );
4248 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4250 // Set names of temporary files
4251 TCollection_AsciiString filename =
4252 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4253 TCollection_AsciiString meshfile =
4254 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4255 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4256 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4257 filename = tmpDir + filename;
4258 meshfile = tmpDir + meshfile;
4261 HDFdataset* aDataset;
4262 HDFgroup* aTopGroup;
4264 HDFgroup* aSubGroup;
4265 HDFgroup* aSubSubGroup;
4266 hdf_size aSize[ 1 ];
4269 //Remove the files if they exist: BugID: 11225
4270 #ifndef WIN32 /* unix functionality */
4271 TCollection_AsciiString cmd("rm -f \"");
4273 TCollection_AsciiString cmd("del /F \"");
4283 system(cmd.ToCString());
4285 // MED writer to be used by storage process
4286 DriverMED_W_SMESHDS_Mesh writer;
4287 writer.SetFile( meshfile.ToCString() );
4288 //writer.SetSaveNumbers( false ); // bos #24400 -- it leads to change of element IDs
4291 // SetStoreName() to groups before storing hypotheses to let them refer to
4292 // groups using "store name", which is "Group <group_persistent_id>"
4294 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4295 for ( ; itBig->More(); itBig->Next() ) {
4296 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4297 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4298 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4299 if ( !CORBA::is_nil( anObject ) ) {
4300 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4301 if ( !myMesh->_is_nil() ) {
4302 myMesh->Load(); // load from study file if not yet done
4303 TPythonDump pd(this); // not to dump GetGroups()
4304 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4305 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4307 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4310 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4311 int anId = myStudyContext->findId( string( objStr.in() ) );
4313 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4314 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4315 aGrpBaseDS->SetStoreName( grpName );
4325 // ---> create HDF file
4326 aFile = new HDFfile( (char*) filename.ToCString() );
4327 aFile->CreateOnDisk();
4329 // --> iterator for top-level objects
4330 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4331 for ( ; itBig->More(); itBig->Next() ) {
4332 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4334 // --> hypotheses root branch (only one for the study)
4335 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4336 // create hypotheses root HDF group
4337 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4338 aTopGroup->CreateOnDisk();
4340 // iterator for all hypotheses
4341 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4342 for ( ; it->More(); it->Next() ) {
4343 SALOMEDS::SObject_wrap mySObject = it->Value();
4344 CORBA::Object_var anObject = SObjectToObject( mySObject );
4345 if ( !CORBA::is_nil( anObject ) ) {
4346 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4347 if ( !myHyp->_is_nil() ) {
4348 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4350 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4351 std::string hypname = hn.in();
4352 std::string libname = ln.in();
4354 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4355 // WIN32 and ".so" for X-system) must be deleted
4356 int libname_len = libname.length();
4358 if( libname_len > 4 )
4359 libname.resize( libname_len - 4 );
4361 // PAL17753 (Regression: missing hypothesis in restored study)
4362 // "lib" also should be removed from the beginning
4363 if( libname_len > 6 )
4364 libname = libname.substr( 3, libname_len - 3 - 3 );
4366 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4367 CORBA::String_var hypdata = myImpl->SaveTo();
4368 int id = myStudyContext->findId( string( objStr.in() ));
4370 // for each hypothesis create HDF group basing on its id
4371 char hypGrpName[30];
4372 sprintf( hypGrpName, "Hypothesis %d", id );
4373 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4374 aGroup->CreateOnDisk();
4375 // --> type name of hypothesis
4376 aSize[ 0 ] = hypname.length() + 1;
4377 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4378 aDataset->CreateOnDisk();
4379 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4380 aDataset->CloseOnDisk();
4381 // --> server plugin library name of hypothesis
4382 aSize[ 0 ] = libname.length() + 1;
4383 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4384 aDataset->CreateOnDisk();
4385 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4386 aDataset->CloseOnDisk();
4387 // --> persistent data of hypothesis
4388 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4389 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4390 aDataset->CreateOnDisk();
4391 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4392 aDataset->CloseOnDisk();
4393 // close hypothesis HDF group
4394 aGroup->CloseOnDisk();
4399 // close hypotheses root HDF group
4400 aTopGroup->CloseOnDisk();
4402 // --> algorithms root branch (only one for the study)
4403 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4404 // create algorithms root HDF group
4405 aTopGroup = new HDFgroup( "Algorithms", aFile );
4406 aTopGroup->CreateOnDisk();
4408 // iterator for all algorithms
4409 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4410 for ( ; it->More(); it->Next() ) {
4411 SALOMEDS::SObject_wrap mySObject = it->Value();
4412 CORBA::Object_var anObject = SObjectToObject( mySObject );
4413 if ( !CORBA::is_nil( anObject ) ) {
4414 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4415 if ( !myHyp->_is_nil() ) {
4416 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4418 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4419 std::string hypname = hn.in();
4420 std::string libname = ln.in();
4422 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4423 // WIN32 and ".so" for X-system) must be deleted
4424 int libname_len = libname.length();
4426 if( libname_len > 4 )
4427 libname.resize( libname_len - 4 );
4429 // PAL17753 (Regression: missing hypothesis in restored study)
4430 // "lib" also should be removed from the beginning
4431 if( libname_len > 6 )
4432 libname = libname.substr( 3, libname_len - 3 - 3 );
4434 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4435 CORBA::String_var hypdata = myImpl->SaveTo();
4436 int id = myStudyContext->findId( string( objStr.in() ) );
4438 // for each algorithm create HDF group basing on its id
4439 char hypGrpName[30];
4440 sprintf( hypGrpName, "Algorithm %d", id );
4441 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4442 aGroup->CreateOnDisk();
4443 // --> type name of algorithm
4444 aSize[0] = hypname.length() + 1;
4445 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4446 aDataset->CreateOnDisk();
4447 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4448 aDataset->CloseOnDisk();
4449 // --> server plugin library name of hypothesis
4450 aSize[0] = libname.length() + 1;
4451 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4452 aDataset->CreateOnDisk();
4453 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4454 aDataset->CloseOnDisk();
4455 // --> persistent data of algorithm
4456 aSize[0] = strlen( hypdata.in() ) + 1;
4457 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4458 aDataset->CreateOnDisk();
4459 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4460 aDataset->CloseOnDisk();
4461 // close algorithm HDF group
4462 aGroup->CloseOnDisk();
4467 // close algorithms root HDF group
4468 aTopGroup->CloseOnDisk();
4470 // --> mesh objects roots branches
4471 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4472 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4473 if ( !CORBA::is_nil( anObject ) ) {
4474 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4475 if ( !myMesh->_is_nil() ) {
4476 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4478 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4479 int id = myStudyContext->findId( string( objStr.in() ) );
4480 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4481 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4482 bool hasShape = myLocMesh.HasShapeToMesh();
4484 // for each mesh open the HDF group basing on its id
4485 char meshGrpName[ 30 ];
4486 sprintf( meshGrpName, "Mesh %d", id );
4487 aTopGroup = new HDFgroup( meshGrpName, aFile );
4488 aTopGroup->CreateOnDisk();
4490 // --> put dataset to hdf file which is a flag that mesh has data
4491 string strHasData = "0";
4492 // check if the mesh is not empty
4493 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4494 // write mesh data to med file
4495 writer.SetMesh( mySMESHDSMesh );
4496 writer.SetMeshId( id );
4499 aSize[ 0 ] = strHasData.length() + 1;
4500 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4501 aDataset->CreateOnDisk();
4502 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4503 aDataset->CloseOnDisk();
4506 // for each mesh open the HDF group basing on its auto color parameter
4507 char meshAutoColorName[ 30 ];
4508 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4510 anAutoColor[0] = myImpl->GetAutoColor();
4512 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4513 aDataset->CreateOnDisk();
4514 aDataset->WriteOnDisk( anAutoColor );
4515 aDataset->CloseOnDisk();
4517 // issue 0020693. Store _isModified flag
4518 int isModified = myLocMesh.GetIsModified();
4520 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4521 aDataset->CreateOnDisk();
4522 aDataset->WriteOnDisk( &isModified );
4523 aDataset->CloseOnDisk();
4525 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4526 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4528 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4529 aDataset->CreateOnDisk();
4530 aDataset->WriteOnDisk( &meshPersistentId );
4531 aDataset->CloseOnDisk();
4533 // Store SMESH_Mesh_i::_mainShapeTick
4534 int shapeTick = myImpl->MainShapeTick();
4536 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4537 aDataset->CreateOnDisk();
4538 aDataset->WriteOnDisk( &shapeTick );
4539 aDataset->CloseOnDisk();
4541 // write reference on a shape if exists
4542 SALOMEDS::SObject_wrap myRef;
4543 bool shapeRefFound = false;
4544 bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4546 SALOMEDS::SObject_wrap myShape;
4547 bool ok = myRef->ReferencedObject( myShape.inout() );
4549 CORBA::Object_var shapeObj = myShape->GetObject();
4550 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4551 CORBA::String_var myRefOnObject = myShape->GetID();
4552 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4553 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4554 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4555 aDataset->CreateOnDisk();
4556 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4557 aDataset->CloseOnDisk();
4563 std::string info = myImpl->FileInfoToString();
4564 if ( !info.empty() )
4566 aSize[ 0 ] = info.size();
4567 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4568 aDataset->CreateOnDisk();
4569 aDataset->WriteOnDisk( (char*) info.data() );
4570 aDataset->CloseOnDisk();
4573 // write applied hypotheses if exist
4574 SALOMEDS::SObject_wrap myHypBranch;
4575 found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4576 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4577 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4579 if ( found && (shapeRefFound || !hasShape) ) {
4580 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4581 aGroup->CreateOnDisk();
4583 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4585 for ( ; it->More(); it->Next() ) {
4586 SALOMEDS::SObject_wrap mySObject = it->Value();
4587 SALOMEDS::SObject_wrap myRefOnHyp;
4588 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4590 // san - it is impossible to recover applied hypotheses
4591 // using their entries within Load() method,
4592 // for there are no AttributeIORs in the study when Load() is working.
4593 // Hence, it is better to store persistent IDs of hypotheses as references to them
4595 //string myRefOnObject = myRefOnHyp->GetID();
4596 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4597 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4598 int id = myStudyContext->findId( string( objStr.in() ) );
4599 //if ( myRefOnObject.length() > 0 ) {
4600 //aSize[ 0 ] = myRefOnObject.length() + 1;
4601 char hypName[ 30 ], hypId[ 30 ];
4602 sprintf( hypName, "Hyp %d", ++hypNb );
4603 sprintf( hypId, "%d", id );
4604 aSize[ 0 ] = strlen( hypId ) + 1;
4605 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4606 aDataset->CreateOnDisk();
4607 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4608 aDataset->WriteOnDisk( hypId );
4609 aDataset->CloseOnDisk();
4613 aGroup->CloseOnDisk();
4616 // write applied algorithms if exist
4617 SALOMEDS::SObject_wrap myAlgoBranch;
4618 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4619 myAlgoBranch.inout() );
4620 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4621 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4623 if ( found && (shapeRefFound || !hasShape)) {
4624 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4625 aGroup->CreateOnDisk();
4627 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4629 for ( ; it->More(); it->Next() ) {
4630 SALOMEDS::SObject_wrap mySObject = it->Value();
4631 SALOMEDS::SObject_wrap myRefOnAlgo;
4632 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4634 // san - it is impossible to recover applied algorithms
4635 // using their entries within Load() method,
4636 // for there are no AttributeIORs in the study when Load() is working.
4637 // Hence, it is better to store persistent IDs of algorithms as references to them
4639 //string myRefOnObject = myRefOnAlgo->GetID();
4640 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4641 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4642 int id = myStudyContext->findId( string( objStr.in() ) );
4643 //if ( myRefOnObject.length() > 0 ) {
4644 //aSize[ 0 ] = myRefOnObject.length() + 1;
4645 char algoName[ 30 ], algoId[ 30 ];
4646 sprintf( algoName, "Algo %d", ++algoNb );
4647 sprintf( algoId, "%d", id );
4648 aSize[ 0 ] = strlen( algoId ) + 1;
4649 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4650 aDataset->CreateOnDisk();
4651 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4652 aDataset->WriteOnDisk( algoId );
4653 aDataset->CloseOnDisk();
4657 aGroup->CloseOnDisk();
4660 // --> submesh objects sub-branches
4662 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4663 SALOMEDS::SObject_wrap mySubmeshBranch;
4664 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4666 if ( found ) // check if there is shape reference in submeshes
4668 bool hasShapeRef = false;
4669 SALOMEDS::ChildIterator_wrap itSM =
4670 aStudy->NewChildIterator( mySubmeshBranch );
4671 for ( ; itSM->More(); itSM->Next() ) {
4672 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4673 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4674 mySubRef->ReferencedObject( myShape.inout() );
4675 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4678 { // remove one submesh
4679 if ( shapeRefFound )
4680 { // unassign hypothesis
4681 SMESH::SMESH_subMesh_var mySubMesh =
4682 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4683 if ( !mySubMesh->_is_nil() ) {
4684 int shapeID = mySubMesh->GetId();
4685 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4686 const list<const SMESHDS_Hypothesis*>& hypList =
4687 mySMESHDSMesh->GetHypothesis( S );
4688 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4689 while ( hyp != hypList.end() ) {
4690 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4691 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4695 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4697 } // loop on submeshes of a type
4698 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4699 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4702 } // end check if there is shape reference in submeshes
4704 char name_meshgroup[ 30 ];
4705 if ( i == GetSubMeshOnVertexTag() )
4706 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4707 else if ( i == GetSubMeshOnEdgeTag() )
4708 strcpy( name_meshgroup, "SubMeshes On Edge" );
4709 else if ( i == GetSubMeshOnWireTag() )
4710 strcpy( name_meshgroup, "SubMeshes On Wire" );
4711 else if ( i == GetSubMeshOnFaceTag() )
4712 strcpy( name_meshgroup, "SubMeshes On Face" );
4713 else if ( i == GetSubMeshOnShellTag() )
4714 strcpy( name_meshgroup, "SubMeshes On Shell" );
4715 else if ( i == GetSubMeshOnSolidTag() )
4716 strcpy( name_meshgroup, "SubMeshes On Solid" );
4717 else if ( i == GetSubMeshOnCompoundTag() )
4718 strcpy( name_meshgroup, "SubMeshes On Compound" );
4720 // for each type of submeshes create container HDF group
4721 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4722 aGroup->CreateOnDisk();
4724 // iterator for all submeshes of given type
4725 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4726 for ( ; itSM->More(); itSM->Next() ) {
4727 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4728 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4729 if ( !CORBA::is_nil( anSubObject ))
4731 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4732 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4733 int subid = myStudyContext->findId( string( objStr.in() ) );
4735 // for each mesh open the HDF group basing on its id
4736 char submeshGrpName[ 30 ];
4737 sprintf( submeshGrpName, "SubMesh %d", subid );
4738 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4739 aSubGroup->CreateOnDisk();
4741 // write reference on a shape, already checked if it exists
4742 SALOMEDS::SObject_wrap mySubRef, myShape;
4743 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4744 mySubRef->ReferencedObject( myShape.inout() );
4745 string myRefOnObject = myShape->GetID();
4746 if ( myRefOnObject.length() > 0 ) {
4747 aSize[ 0 ] = myRefOnObject.length() + 1;
4748 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4749 aDataset->CreateOnDisk();
4750 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4751 aDataset->CloseOnDisk();
4754 // write applied hypotheses if exist
4755 SALOMEDS::SObject_wrap mySubHypBranch;
4756 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4757 mySubHypBranch.inout() );
4759 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4760 aSubSubGroup->CreateOnDisk();
4762 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4764 for ( ; it->More(); it->Next() ) {
4765 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4766 SALOMEDS::SObject_wrap myRefOnHyp;
4767 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4769 //string myRefOnObject = myRefOnHyp->GetID();
4770 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4771 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4772 int id = myStudyContext->findId( string( objStr.in() ) );
4773 //if ( myRefOnObject.length() > 0 ) {
4774 //aSize[ 0 ] = myRefOnObject.length() + 1;
4775 char hypName[ 30 ], hypId[ 30 ];
4776 sprintf( hypName, "Hyp %d", ++hypNb );
4777 sprintf( hypId, "%d", id );
4778 aSize[ 0 ] = strlen( hypId ) + 1;
4779 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4780 aDataset->CreateOnDisk();
4781 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4782 aDataset->WriteOnDisk( hypId );
4783 aDataset->CloseOnDisk();
4787 aSubSubGroup->CloseOnDisk();
4790 // write applied algorithms if exist
4791 SALOMEDS::SObject_wrap mySubAlgoBranch;
4792 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4793 mySubAlgoBranch.inout() );
4795 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4796 aSubSubGroup->CreateOnDisk();
4798 SALOMEDS::ChildIterator_wrap it =
4799 aStudy->NewChildIterator( mySubAlgoBranch );
4801 for ( ; it->More(); it->Next() ) {
4802 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4803 SALOMEDS::SObject_wrap myRefOnAlgo;
4804 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4806 //string myRefOnObject = myRefOnAlgo->GetID();
4807 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4808 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4809 int id = myStudyContext->findId( string( objStr.in() ) );
4810 //if ( myRefOnObject.length() > 0 ) {
4811 //aSize[ 0 ] = myRefOnObject.length() + 1;
4812 char algoName[ 30 ], algoId[ 30 ];
4813 sprintf( algoName, "Algo %d", ++algoNb );
4814 sprintf( algoId, "%d", id );
4815 aSize[ 0 ] = strlen( algoId ) + 1;
4816 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4817 aDataset->CreateOnDisk();
4818 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4819 aDataset->WriteOnDisk( algoId );
4820 aDataset->CloseOnDisk();
4824 aSubSubGroup->CloseOnDisk();
4826 // close submesh HDF group
4827 aSubGroup->CloseOnDisk();
4830 // close container of submeshes by type HDF group
4831 aGroup->CloseOnDisk();
4835 // store submesh order if any
4836 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4837 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4838 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4839 char order_list[ 30 ];
4840 strcpy( order_list, "Mesh Order" );
4841 // count number of submesh ids
4843 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4844 for ( ; idIt != theOrderIds.end(); idIt++ )
4845 nbIDs += (*idIt).size();
4846 // number of values = number of IDs +
4847 // number of lists (for separators) - 1
4848 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4849 idIt = theOrderIds.begin();
4850 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4851 const TListOfInt& idList = *idIt;
4852 if (idIt != theOrderIds.begin()) // not first list
4853 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4854 // dump submesh ids from current list
4855 TListOfInt::const_iterator id_smId = idList.begin();
4856 for( ; id_smId != idList.end(); id_smId++ )
4857 smIDs[ i++ ] = *id_smId;
4860 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4862 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4863 aDataset->CreateOnDisk();
4864 aDataset->WriteOnDisk( smIDs );
4865 aDataset->CloseOnDisk();
4869 if ( !theOrderIds.empty() && isNewOrederVersion )
4871 // convert ids to entries
4872 std::list< std::list< std::string > > orderEntryLists;
4873 for ( const TListOfInt& idList : theOrderIds )
4875 orderEntryLists.emplace_back();
4876 std::list< std::string > & entryList = orderEntryLists.back();
4877 for ( const int& id : idList )
4879 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4880 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4881 SALOMEDS::SObject_var so = ObjectToSObject( go );
4882 if ( !so->_is_nil() )
4884 CORBA::String_var entry = so->GetID();
4885 entryList.emplace_back( entry.in() );
4889 // convert orderEntryLists to string
4890 std::ostringstream ostream;
4891 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4892 std::string orderEntryString = ostream.str();
4895 aSize[ 0 ] = orderEntryString.size() + 1;
4896 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4897 aDataset->CreateOnDisk();
4898 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4899 aDataset->CloseOnDisk();
4902 // groups root sub-branch
4903 SALOMEDS::SObject_wrap myGroupsBranch;
4904 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4905 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4907 char name_group[ 30 ];
4908 if ( i == GetNodeGroupsTag() )
4909 strcpy( name_group, "Groups of Nodes" );
4910 else if ( i == GetEdgeGroupsTag() )
4911 strcpy( name_group, "Groups of Edges" );
4912 else if ( i == GetFaceGroupsTag() )
4913 strcpy( name_group, "Groups of Faces" );
4914 else if ( i == GetVolumeGroupsTag() )
4915 strcpy( name_group, "Groups of Volumes" );
4916 else if ( i == Get0DElementsGroupsTag() )
4917 strcpy( name_group, "Groups of 0D Elements" );
4918 else if ( i == GetBallElementsGroupsTag() )
4919 strcpy( name_group, "Groups of Balls" );
4921 aGroup = new HDFgroup( name_group, aTopGroup );
4922 aGroup->CreateOnDisk();
4924 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4925 for ( ; it->More(); it->Next() ) {
4926 SALOMEDS::SObject_wrap mySObject = it->Value();
4927 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4928 if ( !CORBA::is_nil( aSubObject ) ) {
4929 SMESH_GroupBase_i* myGroupImpl =
4930 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4933 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4937 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4938 int anId = myStudyContext->findId( string( objStr.in() ) );
4940 // For each group, create a dataset named "Group <group_persistent_id>"
4941 // and store the group's user name into it
4942 const char* grpName = aGrpBaseDS->GetStoreName();
4943 CORBA::String_var aUserName = myGroupImpl->GetName();
4944 aSize[ 0 ] = strlen( aUserName ) + 1;
4946 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4947 aDataset->CreateOnDisk();
4948 aDataset->WriteOnDisk( aUserName );
4949 aDataset->CloseOnDisk();
4952 // For each group, create a dataset named "Group <group_persistent_id> Color"
4953 // and store the group's color into it
4954 char grpColorName[ 30 ];
4955 sprintf( grpColorName, "ColorGroup %d", anId );
4956 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4958 anRGB[ 0 ] = aColor.R;
4959 anRGB[ 1 ] = aColor.G;
4960 anRGB[ 2 ] = aColor.B;
4962 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4963 aDataset->CreateOnDisk();
4964 aDataset->WriteOnDisk( anRGB );
4965 aDataset->CloseOnDisk();
4967 // Pass SMESHDS_Group to MED writer
4968 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4970 writer.AddGroup( aGrpDS );
4972 // write reference on a shape if exists
4973 SMESHDS_GroupOnGeom* aGeomGrp =
4974 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4976 SALOMEDS::SObject_wrap mySubRef, myShape;
4977 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4978 mySubRef->ReferencedObject( myShape.inout() ) &&
4979 !CORBA::is_nil( myShape->GetObject() ))
4981 CORBA::String_var myRefOnObject = myShape->GetID();
4982 if ( myRefOnObject.in()[0] ) {
4983 char aRefName[ 30 ];
4984 sprintf( aRefName, "Ref on shape %d", anId);
4985 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4986 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4987 aDataset->CreateOnDisk();
4988 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4989 aDataset->CloseOnDisk();
4992 else // shape ref is invalid:
4994 // save a group on geometry as ordinary group
4995 writer.AddGroup( aGeomGrp );
4998 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4999 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
5001 std::string str = aFilterGrp_i->FilterToString();
5002 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
5003 aSize[ 0 ] = str.length() + 1;
5004 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
5005 aDataset->CreateOnDisk();
5006 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
5007 aDataset->CloseOnDisk();
5011 aGroup->CloseOnDisk();
5015 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
5017 // Flush current mesh information into MED file
5020 // save info on nb of elements
5021 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
5023 // maybe a shape was deleted in the study
5024 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
5025 TopoDS_Shape nullShape;
5026 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
5029 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
5034 aGroup = new HDFgroup( "Submeshes", aTopGroup );
5035 aGroup->CreateOnDisk();
5037 // each element belongs to one or none submesh,
5038 // so for each node/element, we store a submesh ID
5040 // Store submesh IDs
5041 for ( int isNode = 0; isNode < 2; ++isNode )
5043 SMDS_ElemIteratorPtr eIt =
5044 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
5045 smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
5048 std::vector<int> smIDs; smIDs.reserve( nbElems );
5049 while ( eIt->more() )
5050 if ( const SMDS_MeshElement* e = eIt->next())
5051 smIDs.push_back( e->getshapeId() );
5053 aSize[ 0 ] = nbElems;
5054 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
5055 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5056 aDataset->CreateOnDisk();
5057 aDataset->WriteOnDisk( & smIDs[0] );
5058 aDataset->CloseOnDisk();
5061 aGroup->CloseOnDisk();
5063 // Store node positions on sub-shapes (SMDS_Position):
5064 // ----------------------------------------------------
5066 aGroup = new HDFgroup( "Node Positions", aTopGroup );
5067 aGroup->CreateOnDisk();
5069 // in aGroup, create 5 datasets to contain:
5070 // "Nodes on Edges" - ID of node on edge
5071 // "Edge positions" - U parameter on node on edge
5072 // "Nodes on Faces" - ID of node on face
5073 // "Face U positions" - U parameter of node on face
5074 // "Face V positions" - V parameter of node on face
5076 // Find out nb of nodes on edges and faces
5077 // Collect corresponding sub-meshes
5078 int nbEdgeNodes = 0, nbFaceNodes = 0;
5079 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5080 // loop on SMESHDS_SubMesh'es
5081 while ( smIt->more() )
5083 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5084 if ( aSubMesh->IsComplexSubmesh() )
5085 continue; // submesh containing other submeshs
5086 smIdType nbNodes = aSubMesh->NbNodes();
5087 if ( nbNodes == 0 ) continue;
5089 int aShapeID = aSubMesh->GetID();
5090 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5092 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5093 // write only SMDS_FacePosition and SMDS_EdgePosition
5094 switch ( aShapeType ) {
5096 nbFaceNodes += nbNodes;
5097 aFaceSM.push_back( aSubMesh );
5100 nbEdgeNodes += nbNodes;
5101 aEdgeSM.push_back( aSubMesh );
5107 // Treat positions on edges or faces
5108 for ( int onFace = 0; onFace < 2; onFace++ )
5110 // Create arrays to store in datasets
5111 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5112 if (!nbNodes) continue;
5113 int* aNodeIDs = new int [ nbNodes ];
5114 double* aUPos = new double [ nbNodes ];
5115 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5118 // loop on sub-meshes
5119 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5120 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5121 for ( ; itSM != pListSM->end(); itSM++ )
5123 SMESHDS_SubMesh* aSubMesh = (*itSM);
5125 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5126 // loop on nodes in aSubMesh
5127 while ( itNode->more() )
5130 const SMDS_MeshNode* node = itNode->next();
5131 aNodeIDs [ iNode ] = node->GetID();
5134 const SMDS_PositionPtr pos = node->GetPosition();
5135 if ( onFace ) { // on FACE
5136 SMDS_FacePositionPtr fPos = pos;
5138 aUPos[ iNode ] = fPos->GetUParameter();
5139 aVPos[ iNode ] = fPos->GetVParameter();
5146 SMDS_EdgePositionPtr ePos = pos;
5148 aUPos[ iNode ] = ePos->GetUParameter();
5154 } // loop on nodes in aSubMesh
5155 } // loop on sub-meshes
5160 aSize[ 0 ] = nbNodes;
5162 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5163 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5164 aDataset->CreateOnDisk();
5165 aDataset->WriteOnDisk( aNodeIDs );
5166 aDataset->CloseOnDisk();
5169 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5170 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5171 aDataset->CreateOnDisk();
5172 aDataset->WriteOnDisk( aUPos );
5173 aDataset->CloseOnDisk();
5176 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5177 aDataset->CreateOnDisk();
5178 aDataset->WriteOnDisk( aVPos );
5179 aDataset->CloseOnDisk();
5184 if ( aVPos ) delete [] aVPos;
5186 } // treat positions on edges or faces
5188 // close "Node Positions" group
5189 aGroup->CloseOnDisk();
5191 } // if ( there are submeshes in SMESHDS_Mesh )
5194 // close mesh HDF group
5195 aTopGroup->CloseOnDisk();
5203 aFile->CloseOnDisk();
5206 // Convert temporary files to stream
5207 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5209 // Remove temporary files and directory
5211 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5213 return aStreamFile._retn();
5216 //=============================================================================
5218 * SMESH_Gen_i::SaveASCII
5220 * Save SMESH module's data in ASCII format
5222 //=============================================================================
5224 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5226 bool isMultiFile ) {
5227 MESSAGE( "SMESH_Gen_i::SaveASCII" );
5228 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5229 return aStreamFile._retn();
5231 //after usual saving needs to encipher binary to text string
5232 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5233 int size = aStreamFile.in().length();
5234 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5235 for ( int i = 0; i < size; i++ )
5236 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5238 buffer[size * 3] = '\0';
5240 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5242 return anAsciiStreamFile._retn();
5245 //=============================================================================
5249 * Load SMESH module's data
5251 //=============================================================================
5253 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5254 const SALOMEDS::TMPFile& theStream,
5258 UpdateStudy(); // load geom data
5259 Kernel_Utils::Localizer loc;
5261 SALOMEDS::Study_var aStudy = getStudyServant();
5263 // Get temporary files location
5264 TCollection_AsciiString tmpDir =
5265 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5267 // Convert the stream into sequence of files to process
5268 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5271 TCollection_AsciiString aStudyName( "" );
5272 if ( isMultiFile ) {
5273 CORBA::WString_var url = aStudy->URL();
5274 SMESHUtils::ArrayDeleter<const char> urlMulibyte( Kernel_Utils::encode( url.in()) );
5275 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( urlMulibyte.get() ).c_str();
5277 // Set names of temporary files
5278 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5279 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5283 HDFdataset* aDataset;
5284 HDFgroup* aTopGroup;
5286 HDFgroup* aSubGroup;
5287 HDFgroup* aSubSubGroup;
5290 // ---> open HDF file
5291 aFile = new HDFfile( (char*) filename.ToCString() );
5293 aFile->OpenOnDisk( HDF_RDONLY );
5295 catch ( HDFexception ) {
5296 INFOS( "Load(): " << filename << " not found!" );
5300 TPythonDump pd(this); // prevent dump during loading
5302 // For PAL13473 ("Repetitive mesh") implementation.
5303 // New dependencies between SMESH objects are established:
5304 // now hypotheses can refer to meshes, shapes and other hypotheses.
5305 // To keep data consistent, the following order of data restoration
5307 // 1. Create hypotheses
5308 // 2. Create all meshes
5309 // 3. Load hypotheses' data
5312 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5313 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5314 list< SMESH::Filter_var > filters;
5316 // get total number of top-level groups
5317 int aNbGroups = aFile->nInternalObjects();
5318 if ( aNbGroups > 0 ) {
5319 // --> in first turn we should read&create hypotheses
5320 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5321 // open hypotheses root HDF group
5322 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5323 aTopGroup->OpenOnDisk();
5325 // get number of hypotheses
5326 int aNbObjects = aTopGroup->nInternalObjects();
5327 for ( int j = 0; j < aNbObjects; j++ ) {
5328 // try to identify hypothesis
5329 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5330 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5332 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5333 // open hypothesis group
5334 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5335 aGroup->OpenOnDisk();
5337 // --> get hypothesis id
5338 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5343 // get number of datasets
5344 int aNbSubObjects = aGroup->nInternalObjects();
5345 for ( int k = 0; k < aNbSubObjects; k++ ) {
5347 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5348 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5349 // --> get hypothesis name
5350 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5351 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5352 aDataset->OpenOnDisk();
5353 size = aDataset->GetSize();
5354 char* hypname_str = new char[ size ];
5355 aDataset->ReadFromDisk( hypname_str );
5356 hypname = string( hypname_str );
5357 delete [] hypname_str;
5358 aDataset->CloseOnDisk();
5360 // --> get hypothesis plugin library name
5361 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5362 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5363 aDataset->OpenOnDisk();
5364 size = aDataset->GetSize();
5365 char* libname_str = new char[ size ];
5366 aDataset->ReadFromDisk( libname_str );
5367 SCRUTE( libname_str );
5368 libname = string( libname_str );
5369 delete [] libname_str;
5370 aDataset->CloseOnDisk();
5372 // --> get hypothesis data
5373 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5374 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5375 aDataset->OpenOnDisk();
5376 size = aDataset->GetSize();
5377 char* hypdata_str = new char[ size ];
5378 aDataset->ReadFromDisk( hypdata_str );
5379 hypdata = string( hypdata_str );
5380 delete [] hypdata_str;
5381 aDataset->CloseOnDisk();
5384 // close hypothesis HDF group
5385 aGroup->CloseOnDisk();
5387 // --> restore hypothesis from data
5388 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5389 MESSAGE("VSR - load hypothesis : id = " << id <<
5390 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5391 SMESH::SMESH_Hypothesis_var myHyp;
5393 try { // protect persistence mechanism against exceptions
5394 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5397 INFOS( "Exception during hypothesis creation" );
5400 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5402 // myImpl->LoadFrom( hypdata.c_str() );
5403 hypDataList.push_back( make_pair( myImpl, hypdata ));
5404 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5405 int newId = myStudyContext->findId( iorString.in() );
5406 myStudyContext->mapOldToNew( id, newId );
5409 MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5413 // close hypotheses root HDF group
5414 aTopGroup->CloseOnDisk();
5418 // --> then we should read&create algorithms
5419 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5420 // open algorithms root HDF group
5421 aTopGroup = new HDFgroup( "Algorithms", aFile );
5422 aTopGroup->OpenOnDisk();
5424 // get number of algorithms
5425 int aNbObjects = aTopGroup->nInternalObjects();
5426 for ( int j = 0; j < aNbObjects; j++ ) {
5427 // try to identify algorithm
5428 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5429 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5431 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5432 // open algorithm group
5433 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5434 aGroup->OpenOnDisk();
5436 // --> get algorithm id
5437 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5442 // get number of datasets
5443 int aNbSubObjects = aGroup->nInternalObjects();
5444 for ( int k = 0; k < aNbSubObjects; k++ ) {
5446 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5447 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5448 // --> get algorithm name
5449 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5450 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5451 aDataset->OpenOnDisk();
5452 size = aDataset->GetSize();
5453 char* hypname_str = new char[ size ];
5454 aDataset->ReadFromDisk( hypname_str );
5455 hypname = string( hypname_str );
5456 delete [] hypname_str;
5457 aDataset->CloseOnDisk();
5459 // --> get algorithm plugin library name
5460 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5461 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5462 aDataset->OpenOnDisk();
5463 size = aDataset->GetSize();
5464 char* libname_str = new char[ size ];
5465 aDataset->ReadFromDisk( libname_str );
5466 SCRUTE( libname_str );
5467 libname = string( libname_str );
5468 delete [] libname_str;
5469 aDataset->CloseOnDisk();
5471 // --> get algorithm data
5472 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5473 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5474 aDataset->OpenOnDisk();
5475 size = aDataset->GetSize();
5476 char* hypdata_str = new char[ size ];
5477 aDataset->ReadFromDisk( hypdata_str );
5478 SCRUTE( hypdata_str );
5479 hypdata = string( hypdata_str );
5480 delete [] hypdata_str;
5481 aDataset->CloseOnDisk();
5484 // close algorithm HDF group
5485 aGroup->CloseOnDisk();
5487 // --> restore algorithm from data
5488 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5489 MESSAGE("VSR - load algo : id = " << id <<
5490 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5491 SMESH::SMESH_Hypothesis_var myHyp;
5493 try { // protect persistence mechanism against exceptions
5494 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5496 catch( SALOME::SALOME_Exception& ex )
5498 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5501 INFOS( "Exception during hypothesis creation" );
5504 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5506 //myImpl->LoadFrom( hypdata.c_str() );
5507 hypDataList.push_back( make_pair( myImpl, hypdata ));
5508 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5509 int newId = myStudyContext->findId( iorString.in() );
5510 myStudyContext->mapOldToNew( id, newId );
5513 MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5517 // close algorithms root HDF group
5518 aTopGroup->CloseOnDisk();
5522 // --> the rest groups should be meshes
5523 for ( int i = 0; i < aNbGroups; i++ ) {
5524 // identify next group
5525 char meshName[ HDF_NAME_MAX_LEN+1 ];
5526 aFile->InternalObjectIndentify( i, meshName );
5528 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5530 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5534 // open mesh HDF group
5535 aTopGroup = new HDFgroup( meshName, aFile );
5536 aTopGroup->OpenOnDisk();
5538 // get number of child HDF objects
5539 int aNbObjects = aTopGroup->nInternalObjects();
5540 if ( aNbObjects > 0 ) {
5542 MESSAGE( "VSR - load mesh : id = " << id );
5543 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5544 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5545 if ( !myNewMeshImpl )
5547 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5549 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5550 int newId = myStudyContext->findId( iorString.in() );
5551 myStudyContext->mapOldToNew( id, newId );
5554 // try to read and set auto color flag
5555 char aMeshAutoColorName[ 30 ];
5556 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5557 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5559 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5560 aDataset->OpenOnDisk();
5561 size = aDataset->GetSize();
5562 int* anAutoColor = new int[ size ];
5563 aDataset->ReadFromDisk( anAutoColor );
5564 aDataset->CloseOnDisk();
5565 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5566 delete [] anAutoColor;
5569 // try to read and set reference to shape
5570 GEOM::GEOM_Object_var aShapeObject;
5571 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5572 // load mesh "Ref on shape" - it's an entry to SObject
5573 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5574 aDataset->OpenOnDisk();
5575 size = aDataset->GetSize();
5576 char* refFromFile = new char[ size ];
5577 aDataset->ReadFromDisk( refFromFile );
5578 aDataset->CloseOnDisk();
5579 if ( strlen( refFromFile ) > 0 ) {
5580 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5581 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5582 if ( !CORBA::is_nil( shapeObject ) ) {
5583 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5584 if ( !aShapeObject->_is_nil() )
5585 myNewMeshImpl->SetShape( aShapeObject );
5588 delete [] refFromFile;
5591 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5592 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5594 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5595 aDataset->OpenOnDisk();
5596 size = aDataset->GetSize();
5597 int* meshPersistentId = new int[ size ];
5598 aDataset->ReadFromDisk( meshPersistentId );
5599 aDataset->CloseOnDisk();
5600 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5601 delete [] meshPersistentId;
5604 // Restore SMESH_Mesh_i::_mainShapeTick
5605 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5607 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5608 aDataset->OpenOnDisk();
5609 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5610 aDataset->ReadFromDisk( shapeTick );
5611 aDataset->CloseOnDisk();
5614 // Restore file info
5615 if ( aTopGroup->ExistInternalObject( "file info" ))
5617 aDataset = new HDFdataset( "file info", aTopGroup );
5618 aDataset->OpenOnDisk();
5619 size = aDataset->GetSize();
5620 std::string info( size, ' ');
5621 aDataset->ReadFromDisk( (char*) info.data() );
5622 aDataset->CloseOnDisk();
5623 myNewMeshImpl->FileInfoFromString( info );
5629 // As all objects that can be referred by hypothesis are created,
5630 // we can restore hypothesis data
5632 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5633 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5635 SMESH_Hypothesis_i* hyp = hyp_data->first;
5636 string & data = hyp_data->second;
5637 hyp->LoadFrom( data.c_str() );
5640 // Restore the rest mesh data
5642 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5643 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5645 aTopGroup = meshi_group->second;
5646 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5648 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5649 bool hasData = false;
5652 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5653 int newId = myStudyContext->findId( iorString.in() );
5654 int meshOldId = myStudyContext->getOldId( newId );
5656 // try to find mesh data dataset
5657 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5658 // load mesh "has data" flag
5659 aDataset = new HDFdataset( "Has data", aTopGroup );
5660 aDataset->OpenOnDisk();
5661 size = aDataset->GetSize();
5662 char* strHasData = new char[ size ];
5663 aDataset->ReadFromDisk( strHasData );
5664 aDataset->CloseOnDisk();
5665 if ( strcmp( strHasData, "1") == 0 ) {
5668 delete [] strHasData;
5671 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5672 // nodes and elements are not yet put into sub-meshes)
5673 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5674 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5675 aGroup->OpenOnDisk();
5676 // get number of applied algorithms
5677 int aNbSubObjects = aGroup->nInternalObjects();
5678 MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5679 for ( int j = 0; j < aNbSubObjects; j++ ) {
5680 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5681 aGroup->InternalObjectIndentify( j, name_dataset );
5682 // check if it is an algorithm
5683 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5684 aDataset = new HDFdataset( name_dataset, aGroup );
5685 aDataset->OpenOnDisk();
5686 size = aDataset->GetSize();
5687 char* refFromFile = new char[ size ];
5688 aDataset->ReadFromDisk( refFromFile );
5689 aDataset->CloseOnDisk();
5690 // san - it is impossible to recover applied algorithms using their entries within Load() method
5691 int id = atoi( refFromFile );
5692 delete [] refFromFile;
5693 string anIOR = myStudyContext->getIORbyOldId( id );
5694 if ( !anIOR.empty() ) {
5695 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5696 if ( !CORBA::is_nil( hypObject ) ) {
5697 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5698 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5699 || !myNewMeshImpl->HasShapeToMesh()) )
5700 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5705 aGroup->CloseOnDisk();
5708 // try to get applied hypotheses
5709 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5710 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5711 aGroup->OpenOnDisk();
5712 // get number of applied hypotheses
5713 int aNbSubObjects = aGroup->nInternalObjects();
5714 for ( int j = 0; j < aNbSubObjects; j++ ) {
5715 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5716 aGroup->InternalObjectIndentify( j, name_dataset );
5717 // check if it is a hypothesis
5718 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5719 aDataset = new HDFdataset( name_dataset, aGroup );
5720 aDataset->OpenOnDisk();
5721 size = aDataset->GetSize();
5722 char* refFromFile = new char[ size ];
5723 aDataset->ReadFromDisk( refFromFile );
5724 aDataset->CloseOnDisk();
5725 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5726 int id = atoi( refFromFile );
5727 delete [] refFromFile;
5728 string anIOR = myStudyContext->getIORbyOldId( id );
5729 if ( !anIOR.empty() ) {
5730 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5731 if ( !CORBA::is_nil( hypObject ) ) {
5732 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5733 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5734 || !myNewMeshImpl->HasShapeToMesh()) )
5735 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5740 aGroup->CloseOnDisk();
5743 // --> try to find SUB-MESHES containers for each type of submesh
5744 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5745 const char* name_meshgroup = 0;
5746 if ( j == GetSubMeshOnVertexTag() )
5747 name_meshgroup = "SubMeshes On Vertex";
5748 else if ( j == GetSubMeshOnEdgeTag() )
5749 name_meshgroup = "SubMeshes On Edge";
5750 else if ( j == GetSubMeshOnWireTag() )
5751 name_meshgroup = "SubMeshes On Wire";
5752 else if ( j == GetSubMeshOnFaceTag() )
5753 name_meshgroup = "SubMeshes On Face";
5754 else if ( j == GetSubMeshOnShellTag() )
5755 name_meshgroup = "SubMeshes On Shell";
5756 else if ( j == GetSubMeshOnSolidTag() )
5757 name_meshgroup = "SubMeshes On Solid";
5758 else if ( j == GetSubMeshOnCompoundTag() )
5759 name_meshgroup = "SubMeshes On Compound";
5761 // try to get submeshes container HDF group
5762 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5763 // open submeshes containers HDF group
5764 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5765 aGroup->OpenOnDisk();
5767 // get number of submeshes
5768 int aNbSubMeshes = aGroup->nInternalObjects();
5769 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5771 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5772 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5773 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5774 // --> get submesh id
5775 int subid = atoi( name_submeshgroup + 7 );
5778 // open submesh HDF group
5779 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5780 aSubGroup->OpenOnDisk();
5782 // try to read and set reference to subshape
5783 GEOM::GEOM_Object_var aSubShapeObject;
5784 SMESH::SMESH_subMesh_var aSubMesh;
5786 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5787 // load submesh "Ref on shape" - it's an entry to SObject
5788 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5789 aDataset->OpenOnDisk();
5790 size = aDataset->GetSize();
5791 char* refFromFile = new char[ size ];
5792 aDataset->ReadFromDisk( refFromFile );
5793 aDataset->CloseOnDisk();
5794 if ( strlen( refFromFile ) > 0 ) {
5795 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5796 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5797 if ( !CORBA::is_nil( subShapeObject ) ) {
5798 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5799 if ( !aSubShapeObject->_is_nil() )
5800 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5801 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5802 if ( aSubMesh->_is_nil() )
5804 string iorSubString = GetORB()->object_to_string( aSubMesh );
5805 int newSubId = myStudyContext->findId( iorSubString );
5806 myStudyContext->mapOldToNew( subid, newSubId );
5809 delete [] refFromFile;
5812 if ( aSubMesh->_is_nil() )
5815 // try to get applied algorithms
5816 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5817 // open "applied algorithms" HDF group
5818 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5819 aSubSubGroup->OpenOnDisk();
5820 // get number of applied algorithms
5821 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5822 for ( int l = 0; l < aNbSubObjects; l++ ) {
5823 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5824 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5825 // check if it is an algorithm
5826 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5827 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5828 aDataset->OpenOnDisk();
5829 size = aDataset->GetSize();
5830 char* refFromFile = new char[ size ];
5831 aDataset->ReadFromDisk( refFromFile );
5832 aDataset->CloseOnDisk();
5834 int id = atoi( refFromFile );
5835 string anIOR = myStudyContext->getIORbyOldId( id );
5836 if ( !anIOR.empty() ) {
5837 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5838 if ( !CORBA::is_nil( hypObject ) ) {
5839 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5840 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5841 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5844 delete [] refFromFile;
5847 // close "applied algorithms" HDF group
5848 aSubSubGroup->CloseOnDisk();
5851 // try to get applied hypotheses
5852 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5853 // open "applied hypotheses" HDF group
5854 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5855 aSubSubGroup->OpenOnDisk();
5856 // get number of applied hypotheses
5857 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5858 for ( int l = 0; l < aNbSubObjects; l++ ) {
5859 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5860 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5861 // check if it is a hypothesis
5862 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5863 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5864 aDataset->OpenOnDisk();
5865 size = aDataset->GetSize();
5866 char* refFromFile = new char[ size ];
5867 aDataset->ReadFromDisk( refFromFile );
5868 aDataset->CloseOnDisk();
5870 int id = atoi( refFromFile );
5871 string anIOR = myStudyContext->getIORbyOldId( id );
5872 if ( !anIOR.empty() ) {
5873 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5874 if ( !CORBA::is_nil( hypObject ) ) {
5875 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5876 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5877 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5880 delete [] refFromFile;
5883 // close "APPLIED HYPOTHESES" hdf group
5884 aSubSubGroup->CloseOnDisk();
5887 // close SUB-MESH hdf group
5888 aSubGroup->CloseOnDisk();
5891 // close SUB-MESHES containers hdf group
5892 aGroup->CloseOnDisk();
5896 // try to get GROUPS
5897 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5898 char name_group[ 30 ];
5899 if ( ii == GetNodeGroupsTag() )
5900 strcpy( name_group, "Groups of Nodes" );
5901 else if ( ii == GetEdgeGroupsTag() )
5902 strcpy( name_group, "Groups of Edges" );
5903 else if ( ii == GetFaceGroupsTag() )
5904 strcpy( name_group, "Groups of Faces" );
5905 else if ( ii == GetVolumeGroupsTag() )
5906 strcpy( name_group, "Groups of Volumes" );
5907 else if ( ii == Get0DElementsGroupsTag() )
5908 strcpy( name_group, "Groups of 0D Elements" );
5909 else if ( ii == GetBallElementsGroupsTag() )
5910 strcpy( name_group, "Groups of Balls" );
5912 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5913 aGroup = new HDFgroup( name_group, aTopGroup );
5914 aGroup->OpenOnDisk();
5915 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5916 // within aGroup->ExistInternalObject( name )
5917 std::vector< std::string > subNames;
5918 TColStd_MapOfAsciiString mapOfNames;
5919 aGroup->GetAllObjects( subNames );
5920 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5921 mapOfNames.Add( subNames[ iN ].c_str() );
5923 for ( size_t j = 0; j < subNames.size(); j++ ) {
5924 const std::string& name_dataset = subNames[ j ];
5925 // check if it is a group
5926 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5929 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5932 int groupID = -1; // group local ID (also persistent)
5934 groupID = atoi( endptr + 1 );
5935 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5936 aDataset->OpenOnDisk();
5938 // Retrieve actual group name
5939 size = aDataset->GetSize();
5940 char* nameFromFile = new char[ size ];
5941 aDataset->ReadFromDisk( nameFromFile );
5942 aDataset->CloseOnDisk();
5944 // Try to find a shape reference
5945 TopoDS_Shape aShape;
5946 char aRefName[ 30 ];
5947 sprintf( aRefName, "Ref on shape %d", subid);
5948 if ( mapOfNames.Contains( aRefName ))
5950 // load mesh "Ref on shape" - it's an entry to SObject
5951 aDataset = new HDFdataset( aRefName, aGroup );
5952 aDataset->OpenOnDisk();
5953 size = aDataset->GetSize();
5954 char* refFromFile = new char[ size ];
5955 aDataset->ReadFromDisk( refFromFile );
5956 aDataset->CloseOnDisk();
5957 if ( strlen( refFromFile ) > 0 ) {
5958 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5959 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5960 if ( !CORBA::is_nil( shapeObject ) ) {
5961 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5962 if ( !aShapeObject->_is_nil() )
5963 aShape = GeomObjectToShape( aShapeObject );
5966 delete [] refFromFile;
5968 // Try to read a filter of SMESH_GroupOnFilter
5969 SMESH::Filter_var filter;
5970 SMESH_PredicatePtr predicate;
5971 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5972 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5974 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5975 aDataset->OpenOnDisk();
5976 size = aDataset->GetSize();
5977 char* persistStr = new char[ size ];
5978 aDataset->ReadFromDisk( persistStr );
5979 aDataset->CloseOnDisk();
5980 if ( strlen( persistStr ) > 0 ) {
5981 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5982 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5983 filters.push_back( filter );
5985 delete [] persistStr;
5988 // Create group servant
5989 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5990 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5991 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5992 delete [] nameFromFile;
5993 // Obtain a SMESHDS_Group object
5994 if ( aNewGroup->_is_nil() )
5997 CORBA::String_var iorSubStringVar = GetORB()->object_to_string( aNewGroup );
5998 string iorSubString(iorSubStringVar.in());
5999 int newSubId = myStudyContext->findId( iorSubString );
6000 myStudyContext->mapOldToNew( subid, newSubId );
6002 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
6006 if ( SMESH_GroupOnFilter_i* aFilterGroup =
6007 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
6009 aFilterGroup->SetFilter( filter );
6010 filter->UnRegister();
6012 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
6013 if ( !aGroupBaseDS )
6016 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
6019 // Read color of the group
6020 char aGroupColorName[ 30 ];
6021 sprintf( aGroupColorName, "ColorGroup %d", subid);
6022 if ( mapOfNames.Contains( aGroupColorName ))
6024 aDataset = new HDFdataset( aGroupColorName, aGroup );
6025 aDataset->OpenOnDisk();
6026 size = aDataset->GetSize();
6027 double* anRGB = new double[ size ];
6028 aDataset->ReadFromDisk( anRGB );
6029 aDataset->CloseOnDisk();
6030 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
6031 aGroupBaseDS->SetColor( aColor );
6036 aGroup->CloseOnDisk();
6040 // instead of reading mesh data, we read only brief information of all
6041 // objects: mesh, groups, sub-meshes (issue 0021208)
6044 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
6045 meshfile.ToCString(), filename.ToCString(),
6049 // read Sub-Mesh ORDER if any
6050 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
6051 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
6052 aDataset->OpenOnDisk();
6053 size = aDataset->GetSize();
6054 int* smIDs = new int[ size ];
6055 aDataset->ReadFromDisk( smIDs );
6056 aDataset->CloseOnDisk();
6057 TListOfListOfInt anOrderIds;
6058 anOrderIds.push_back( TListOfInt() );
6059 for ( int i = 0; i < size; i++ )
6060 if ( smIDs[ i ] < 0 ) // is separator
6061 anOrderIds.push_back( TListOfInt() );
6063 anOrderIds.back().push_back(smIDs[ i ]);
6065 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6068 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
6070 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
6071 aDataset->OpenOnDisk();
6072 size = aDataset->GetSize();
6073 std::string dataString; dataString.resize( size );
6074 aDataset->ReadFromDisk((char*) dataString.data() );
6075 aDataset->CloseOnDisk();
6077 std::list< std::list< std::string > > orderEntryLists;
6078 SMESHUtils::BoostTxtArchive( dataString ) >> orderEntryLists;
6080 TListOfListOfInt anOrderIds;
6081 for ( const std::list< std::string >& entryList : orderEntryLists )
6083 anOrderIds.emplace_back();
6084 for ( const std::string & entry : entryList )
6086 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6087 TopoDS_Shape shape = GeomObjectToShape( go );
6088 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6089 anOrderIds.back().emplace_back( sm->GetId() );
6092 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6096 // update hyps needing full mesh data restored (issue 20918)
6097 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6099 SMESH_Hypothesis_i* hyp = hyp_data->first;
6100 hyp->UpdateAsMeshesRestored();
6103 // notify algos on completed restoration to set sub-mesh event listeners
6104 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6106 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6107 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6109 TopoDS_Shape myLocShape;
6110 if(myLocMesh.HasShapeToMesh())
6111 myLocShape = myLocMesh.GetShapeToMesh();
6113 myLocShape = SMESH_Mesh::PseudoShape();
6115 myLocMesh.GetSubMesh(myLocShape)->
6116 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6119 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6120 list< SMESH::Filter_var >::iterator f = filters.begin();
6121 for ( ; f != filters.end(); ++f )
6122 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6123 fi->FindBaseObjects();
6128 aTopGroup->CloseOnDisk();
6131 aFile->CloseOnDisk();
6134 // Remove temporary files created from the stream
6137 SMESH_File meshFile( meshfile.ToCString() );
6138 if ( !meshFile ) // no meshfile exists
6140 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6144 Engines::Container_var container = GetContainerRef();
6145 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6147 container_i->registerTemporaryFile( filename.ToCString() );
6148 container_i->registerTemporaryFile( meshfile.ToCString() );
6149 container_i->registerTemporaryFile( tmpDir.ToCString() );
6154 // creation of tree nodes for all data objects in the study
6155 // to support tree representation customization and drag-n-drop:
6156 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6157 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6158 useCaseBuilder->SetRootCurrent();
6159 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6160 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6161 for (it->InitEx(true); it->More(); it->Next()) {
6162 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6169 //=============================================================================
6171 * SMESH_Gen_i::LoadASCII
6173 * Load SMESH module's data in ASCII format
6175 //=============================================================================
6177 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6178 const SALOMEDS::TMPFile& theStream,
6180 bool isMultiFile ) {
6181 MESSAGE( "SMESH_Gen_i::LoadASCII" );
6182 return Load( theComponent, theStream, theURL, isMultiFile );
6184 //before call main ::Load method it's need for decipher text format to
6185 //binary ( "|xx" => x' )
6186 int size = theStream.length();
6187 if ( int((size / 3 )*3) != size ) //error size of buffer
6190 int real_size = int(size / 3);
6192 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6195 unsigned int c = -1;
6196 for ( int i = 0; i < real_size; i++ )
6198 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6199 sscanf( tmp, "%x", &c );
6200 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6203 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6205 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6208 //=============================================================================
6210 * SMESH_Gen_i::Close
6212 * Clears study-connected data when it is closed
6214 //=============================================================================
6216 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6218 MESSAGE( "SMESH_Gen_i::Close" );
6220 // Clear study contexts data
6221 myStudyContext->Clear();
6223 // remove the tmp files meshes are loaded from
6224 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6226 // Clean trace of API methods calls
6232 //=============================================================================
6234 * SMESH_Gen_i::ComponentDataType
6236 * Get component data type
6238 //=============================================================================
6240 char* SMESH_Gen_i::ComponentDataType()
6242 MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6243 return CORBA::string_dup( "SMESH" );
6247 //=============================================================================
6249 * SMESH_Gen_i::IORToLocalPersistentID
6251 * Transform data from transient form to persistent
6253 //=============================================================================
6255 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6256 const char* IORString,
6257 CORBA::Boolean /*isMultiFile*/,
6258 CORBA::Boolean /*isASCII*/ )
6260 MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6262 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6263 int anId = myStudyContext->findId( IORString );
6265 MESSAGE( "VSR " << anId );
6267 sprintf( strId, "%d", anId );
6268 return CORBA::string_dup( strId );
6271 return CORBA::string_dup( "" );
6274 //=============================================================================
6276 * SMESH_Gen_i::LocalPersistentIDToIOR
6278 * Transform data from persistent form to transient
6280 //=============================================================================
6282 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6283 const char* aLocalPersistentID,
6284 CORBA::Boolean /*isMultiFile*/,
6285 CORBA::Boolean /*isASCII*/ )
6287 MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6289 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6290 int anId = atoi( aLocalPersistentID );
6291 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6293 return CORBA::string_dup( "" );
6296 //=======================================================================
6297 //function : RegisterObject
6299 //=======================================================================
6301 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6303 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6304 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6305 return myStudyContext->addObject( string( iorString.in() ) );
6310 //================================================================================
6312 * \brief Return id of registered object
6313 * \param theObject - the Object
6314 * \retval int - Object id
6316 //================================================================================
6318 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6320 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6321 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6322 string iorStringCpp(iorString.in());
6323 return myStudyContext->findId( iorStringCpp );
6328 //=============================================================================
6330 * SMESH_Gen_i::SetName
6332 * Set a new object name
6334 //=============================================================================
6336 void SMESH_Gen_i::SetName(const char* theIOR,
6337 const char* theName)
6339 if ( theIOR && strcmp( theIOR, "" ) ) {
6340 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6341 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6342 if ( !aSO->_is_nil() ) {
6343 SetName( aSO, theName );
6348 // Version information
6349 char* SMESH_Gen_i::getVersion()
6351 #if SMESH_DEVELOPMENT
6352 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6354 return CORBA::string_dup(SMESH_VERSION_STR);
6358 //=================================================================================
6359 // function : Move()
6360 // purpose : Moves objects to the specified position.
6361 // Is used in the drag-n-drop functionality.
6362 //=================================================================================
6364 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6365 SALOMEDS::SObject_ptr where,
6368 if ( CORBA::is_nil( where ) ) return;
6370 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6371 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6372 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6373 std::string dataType = father->ComponentDataType();
6374 if ( dataType != "SMESH" ) return; // not a SMESH component
6376 SALOMEDS::SObject_var objAfter;
6377 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6378 // insert at given row -> find insertion position
6379 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6381 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6382 if ( i == row && useCaseIt->More() ) {
6383 objAfter = useCaseIt->Value();
6387 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6388 SALOMEDS::SObject_var sobj = what[i];
6389 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6390 // insert the object to the use case tree
6391 if ( !CORBA::is_nil( objAfter ) )
6392 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6394 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6398 //================================================================================
6400 * \brief Collect indices of elements, which are located inside the sphere
6402 //================================================================================
6404 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6405 SMESH::ElementType theElemType,
6411 SMESH::long_array_var aResult = new SMESH::long_array();
6412 if ( meshPart->_is_nil() )
6413 return aResult._retn();
6415 // 1. Create geometrical object
6416 gp_Pnt aP( theX, theY, theZ );
6417 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6419 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6421 if ( lst.size() > 0 ) {
6422 aResult->length( lst.size() );
6423 for ( size_t i = 0; i < lst.size(); i++ ) {
6424 aResult[i] = lst[i];
6427 return aResult._retn();
6430 //================================================================================
6432 * \brief Collect indices of elements, which are located inside the box
6434 //================================================================================
6436 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6437 SMESH::ElementType theElemType,
6438 CORBA::Double theX1,
6439 CORBA::Double theY1,
6440 CORBA::Double theZ1,
6441 CORBA::Double theX2,
6442 CORBA::Double theY2,
6443 CORBA::Double theZ2)
6445 SMESH::long_array_var aResult = new SMESH::long_array();
6446 if( meshPart->_is_nil() )
6447 return aResult._retn();
6449 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6450 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6452 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6454 if( lst.size() > 0 ) {
6455 aResult->length( lst.size() );
6456 for ( size_t i = 0; i < lst.size(); i++ ) {
6457 aResult[i] = lst[i];
6460 return aResult._retn();
6463 //================================================================================
6465 * \brief Collect indices of elements, which are located inside the cylinder
6467 //================================================================================
6469 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6470 SMESH::ElementType theElemType,
6474 CORBA::Double theDX,
6475 CORBA::Double theDY,
6476 CORBA::Double theDZ,
6478 CORBA::Double theR )
6480 SMESH::long_array_var aResult = new SMESH::long_array();
6481 if( meshPart->_is_nil() )
6482 return aResult._retn();
6484 gp_Pnt aP( theX, theY, theZ );
6485 gp_Vec aV( theDX, theDY, theDZ );
6486 gp_Ax2 anAxes (aP, aV);
6488 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6490 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6492 if( lst.size() > 0 ) {
6493 aResult->length( lst.size() );
6494 for ( size_t i = 0; i < lst.size(); i++ ) {
6495 aResult[i] = lst[i];
6498 return aResult._retn();
6501 //================================================================================
6503 * \brief Collect indices of elements, which are located inside the geom object
6505 //================================================================================
6507 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6508 SMESH::ElementType theElemType,
6509 GEOM::GEOM_Object_ptr theGeom,
6510 CORBA::Double theTolerance )
6512 SMESH::long_array_var aResult = new SMESH::long_array();
6513 if( meshPart->_is_nil() || theGeom->_is_nil() )
6514 return aResult._retn();
6516 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6518 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6520 if( lst.size() > 0 ) {
6521 aResult->length( lst.size() );
6522 for ( size_t i = 0; i < lst.size(); i++ ) {
6523 aResult[i] = lst[i];
6526 return aResult._retn();
6529 //================================================================================
6531 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6533 //================================================================================
6535 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6536 SMESH::ElementType theElemType,
6537 const TopoDS_Shape& theShape,
6538 double* theTolerance) {
6540 std::vector<long> res;
6541 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6543 if ( mesh->_is_nil() )
6546 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6550 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6555 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6556 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6557 anElementsOnShape->SetAllNodes( true );
6558 anElementsOnShape->SetMesh( meshDS );
6559 anElementsOnShape->SetShape( theShape, aType );
6562 anElementsOnShape->SetTolerance(*theTolerance);
6564 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6565 if ( !msource->_is_nil() ) { // Mesh case
6566 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6568 while ( elemIt->more() ) {
6569 const SMDS_MeshElement* anElem = elemIt->next();
6570 long anId = anElem->GetID();
6571 if ( anElementsOnShape->IsSatisfy( anId ) )
6572 res.push_back( anId );
6576 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6577 if ( !gsource->_is_nil() ) {
6578 if(theElemType == SMESH::NODE) {
6579 SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6580 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6581 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6582 long anId = node->GetID();
6583 if ( anElementsOnShape->IsSatisfy( anId ) )
6584 res.push_back( anId );
6587 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6588 SMESH::smIdType_array_var elems = gsource->GetListOfID();
6589 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6590 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6591 long anId = elem->GetID();
6592 if ( anElementsOnShape->IsSatisfy( anId ) )
6593 res.push_back( anId );
6598 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6599 if ( !smsource->_is_nil() ) {
6600 SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6601 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6602 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6604 long anId = elem->GetID();
6605 if ( anElementsOnShape->IsSatisfy( anId ) )
6606 res.push_back( anId );
6613 //================================================================================
6615 * \brief Returns true if algorithm can be used to mesh a given geometry
6616 * \param [in] theAlgoType - the algorithm type
6617 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6618 * \param [in] theGeomObject - the geometry to mesh
6619 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6620 * else, returns \c True if at least one shape is meshable
6621 * \return CORBA::Boolean - can or can't
6623 //================================================================================
6625 #undef SMY_OWN_CATCH
6626 #define SMY_OWN_CATCH // prevent re-throwing SALOME::SALOME_Exception in IsApplicable()
6628 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6629 const char* theLibName,
6630 GEOM::GEOM_Object_ptr theGeomObject,
6631 CORBA::Boolean toCheckAll)
6635 std::string aPlatformLibName;
6636 GenericHypothesisCreator_i* aCreator =
6637 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6640 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6641 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6642 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6649 SMESH_CATCH( SMESH::doNothing );
6651 MESSAGE("SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : ""));