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 + "\", \"" +
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);
2869 PyRun_String(cmd.c_str(), Py_file_input, py_dict, py_dict);
2871 if (PyErr_Occurred()) {
2872 // Restrieving python error
2873 MESSAGE("Catching error");
2874 PyObject *errtype, *errvalue, *traceback;
2875 PyErr_Fetch(&errtype, &errvalue, &traceback);
2876 if(errvalue != NULL) {
2877 MESSAGE("Error has a value");
2878 PyObject *s = PyObject_Str(errvalue);
2880 std::string msg = PyUnicode_AsUTF8AndSize(s, &size);
2881 msg = "Issue with the execution of create_dual_mesh:\n"+msg;
2882 MESSAGE("throwing exception");
2883 // We need to deactivate the GIL before throwing the exception
2884 PyGILState_Release(gstate);
2885 THROW_SALOME_CORBA_EXCEPTION(msg.c_str(), SALOME::INTERNAL_ERROR );
2888 Py_XDECREF(errvalue);
2889 Py_XDECREF(errtype);
2890 Py_XDECREF(traceback);
2893 PyGILState_Release(gstate);
2895 MESSAGE("Mesh created in " + dual_mesh_file.string());
2897 // Import created MED
2898 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2899 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2901 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2902 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2903 if ( !meshSO->_is_nil() )
2905 SetName( meshSO, meshName, meshName );
2906 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2908 int ret = newMesh_i->ImportMEDFile(dual_mesh_file.string().c_str(), meshName);
2910 THROW_SALOME_CORBA_EXCEPTION( "Issue when importing mesh", SALOME::INTERNAL_ERROR );
2913 SMESH_Mesh& newMesh2 = newMesh_i->GetImpl();
2916 MESSAGE("Loading file: " << dual_mesh_file.string() << " with mesh " << meshName);
2917 int ret = newMesh2.MEDToMesh(dual_mesh_file.c_str(), meshName);
2920 newMesh_i->GetImpl().GetMeshDS()->Modified();
2922 *pyDump << newMesh << " = " << this
2923 << ".CreateDualMesh("
2925 << "'" << mesh_name << "', "
2928 pyDumpDeleter.reset(); // allow dump in GetGroups()
2930 if ( srcMesh_i->GetImpl().GetGroupIds().size() > 0 ) // dump created groups
2931 MESSAGE("Dump of groups");
2932 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2934 return newMesh._retn();
2937 //================================================================================
2939 * \brief Create a mesh by copying a part of another mesh
2940 * \param meshPart - a part of mesh to copy
2941 * \param toCopyGroups - to create in the new mesh groups
2942 * the copied elements belongs to
2943 * \param toKeepIDs - to preserve IDs of the copied elements or not
2944 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2946 //================================================================================
2948 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2949 const char* meshName,
2950 CORBA::Boolean toCopyGroups,
2951 CORBA::Boolean toKeepIDs)
2953 Unexpect aCatch(SALOME_SalomeException);
2955 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2956 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2958 // 1. Get source mesh
2960 if ( CORBA::is_nil( meshPart ))
2961 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2963 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2964 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2966 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2968 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2970 // 2. Make a new mesh
2972 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2973 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2975 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2976 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2977 if ( !meshSO->_is_nil() )
2979 SetName( meshSO, meshName, "Mesh" );
2980 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2982 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2983 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2984 ::SMESH_MeshEditor::ElemFeatures elemType;
2986 // 3. Get elements to copy
2988 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2989 TIDSortedElemSet srcElems;
2990 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2991 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2994 srcElemIt = srcMeshDS->elementsIterator();
2995 srcNodeIt = srcMeshDS->nodesIterator();
2999 SMESH::smIdType_array_var ids = meshPart->GetIDs();
3000 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
3002 for ( CORBA::ULong i=0; i < ids->length(); i++ )
3003 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
3004 srcElems.insert( elem );
3008 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
3009 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
3010 srcElems.insert( elem );
3012 if ( srcElems.empty() )
3013 return newMesh._retn();
3015 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
3016 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
3021 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
3022 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
3023 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
3025 const SMDS_MeshNode *nSrc, *nTgt;
3026 vector< const SMDS_MeshNode* > nodes;
3027 while ( srcElemIt->more() )
3029 const SMDS_MeshElement * elem = srcElemIt->next();
3031 nodes.resize( elem->NbNodes());
3032 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3034 for ( iN = 0; nIt->more(); ++iN )
3036 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3037 nTgt = newMeshDS->FindNode( nSrc->GetID());
3039 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3044 for ( iN = 0; nIt->more(); ++iN )
3046 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3047 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
3049 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3050 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
3054 if ( elem->GetType() != SMDSAbs_Node )
3056 elemType.Init( elem, /*basicOnly=*/false );
3057 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
3059 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
3060 if ( toCopyGroups && !toKeepIDs )
3061 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
3063 } // while ( srcElemIt->more() )
3065 // 4(b). Copy free nodes
3067 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3069 while ( srcNodeIt->more() )
3071 nSrc = srcNodeIt->next();
3072 if ( nSrc->NbInverseElements() == 0 )
3075 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3077 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3084 int nbNewGroups = 0;
3087 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3088 while ( gIt->more() )
3090 SMESH_Group* group = gIt->next();
3091 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3093 // Check group type. We copy nodal groups containing nodes of copied element
3094 SMDSAbs_ElementType groupType = groupDS->GetType();
3095 if ( groupType != SMDSAbs_Node &&
3096 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3097 continue; // group type differs from types of meshPart
3099 // Find copied elements in the group
3100 vector< const SMDS_MeshElement* > groupElems;
3101 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3104 const SMDS_MeshElement* foundElem;
3105 if ( groupType == SMDSAbs_Node )
3107 while ( eIt->more() )
3108 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3109 groupElems.push_back( foundElem );
3113 while ( eIt->more() )
3114 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3115 groupElems.push_back( foundElem );
3120 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3121 if ( e2eMap.empty() ) continue;
3122 smIdType minID = e2eMap.begin()->first->GetID();
3123 smIdType maxID = e2eMap.rbegin()->first->GetID();
3124 TE2EMap::iterator e2e;
3125 while ( eIt->more() && groupElems.size() < e2eMap.size())
3127 const SMDS_MeshElement* e = eIt->next();
3128 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3129 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3130 groupElems.push_back( e2e->second );
3134 if ( !groupElems.empty() )
3136 SMESH::SMESH_Group_var newGroupObj =
3137 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3138 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3140 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3141 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3142 for ( unsigned i = 0; i < groupElems.size(); ++i )
3143 smdsGroup.Add( groupElems[i] );
3151 newMeshDS->Modified();
3153 *pyDump << newMesh << " = " << this
3154 << ".CopyMesh( " << meshPart << ", "
3155 << "'" << meshName << "', "
3156 << toCopyGroups << ", "
3157 << toKeepIDs << ")";
3159 pyDumpDeleter.reset(); // allow dump in GetGroups()
3161 if ( nbNewGroups > 0 ) // dump created groups
3162 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3164 return newMesh._retn();
3168 namespace // utils for CopyMeshWithGeom()
3170 typedef std::map< std::string, std::string > TStr2StrMap;
3171 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3172 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3173 typedef std::map< std::string, int > TName2IndexMap;
3175 //================================================================================
3177 * \brief Return a new sub-shape corresponding to an old one
3179 //================================================================================
3183 SMESH_Mesh_i* mySrcMesh_i;
3184 SMESH_Mesh_i* myNewMesh_i;
3185 SMESH_Gen_i* myGen_i;
3189 TStr2StrMap myOld2NewEntryMap; // map of study entries
3191 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3192 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3193 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3196 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3198 // not directly relating to shape search
3199 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3201 //================================================================================
3203 * \brief Constructor
3205 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3206 SMESH_Mesh_i* newMesh_i,
3207 SMESH_Gen_i* smeshGen_i )
3208 : mySrcMesh_i( srcMesh_i ),
3209 myNewMesh_i( newMesh_i ),
3210 myGen_i ( smeshGen_i ),
3211 myToPublish( smeshGen_i->IsEnablePublish() ),
3212 myGIPMapDone( false )
3214 // retrieve from the study shape mapping made thanks to
3215 // "Set presentation parameters and sub-shapes from arguments" option
3217 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3218 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3219 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3220 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3221 if ( newSO->_is_nil() )
3223 myToPublish = false;
3226 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3228 CORBA::String_var oldEntry = oldSO->GetID();
3229 CORBA::String_var newEntry = newSO->GetID();
3230 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3231 std::string( newEntry.in() )));
3232 std::string newMainEntry = newEntry.in();
3234 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3235 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3236 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3237 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3238 /*groupsOnly=*/false );
3239 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3241 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3242 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3243 bool refFound = false;
3244 for ( ; anIter->More(); anIter->Next() )
3246 SALOMEDS::SObject_wrap so = anIter->Value();
3247 if ( so->ReferencedObject( oldSO.inout() ))
3249 oldEntry = oldSO->GetID();
3250 newEntry = newSO->GetID();
3251 if (( refFound = ( newMainEntry != oldEntry.in() )))
3252 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3253 std::string( newEntry.in() )));
3258 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3259 if ( father->_is_equivalent( mainShapeNew ))
3261 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3262 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3263 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3264 CORBA::String_var name = newSO->GetName();
3266 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3272 //================================================================================
3274 * \brief Find a new sub-shape corresponding to an old one
3276 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3279 return GEOM::GEOM_Object::_duplicate( oldShape );
3281 GEOM::GEOM_Object_var newShape;
3283 if ( CORBA::is_nil( oldShape ))
3284 return newShape._retn();
3286 if ( !isChildOfOld( oldShape ))
3287 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3289 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3290 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3292 // try to find by entry or name
3295 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3296 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3297 if ( o2nID != myOld2NewEntryMap.end() )
3299 newShape = getShapeByEntry( o2nID->second );
3301 if ( newShape->_is_nil() )
3303 CORBA::String_var name = oldShape->GetName();
3304 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3305 if ( n2ind != myName2SubshapeIndex.end() )
3307 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3308 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3309 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3310 if ( oldIndices->length() == 0 ||
3311 newIndices->length() == 0 ||
3312 getShapeType( myNewMesh_i, newIndices[0] ) !=
3313 getShapeType( mySrcMesh_i, oldIndices[0] ))
3314 newShape = GEOM::GEOM_Object::_nil();
3319 if ( newShape->_is_nil() )
3321 // try to construct a new sub-shape using myGIPMap
3323 std::vector< int > newIndices;
3324 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3325 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3327 findNewIDs( oldIndices[i], newIndices );
3329 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3332 newShape = getInPlace( oldShape );
3334 if ( !newIndices.empty() && newShape->_is_nil() )
3336 // search for a sub-shape with same ids
3337 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3338 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3339 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3340 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3342 if ( newShape->_is_nil() )
3345 // create a new shape
3346 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3348 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3350 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3351 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3353 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3354 newIndicesList->length( newIndices.size() );
3355 for ( size_t i = 0; i < newIndices.size(); ++i )
3356 newIndicesList[ i ] = newIndices[ i ];
3357 grOp->UnionIDs( newShape, newIndicesList );
3361 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3362 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3371 if ( !newShape->_is_nil() && myToPublish )
3373 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3374 if ( !newEntry.in() || !newEntry.in()[0] )
3376 CORBA::String_var name = oldShape->GetName();
3377 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3378 newEntry = newShape->GetStudyEntry();
3379 oldEntry = oldShape->GetStudyEntry();
3380 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3381 std::string( newEntry.in() )));
3385 return newShape._retn();
3388 //================================================================================
3390 * \brief Return a study entry of a new shape by study entry of the old one
3392 std::string FindNew( const std::string & oldEntry )
3397 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3398 if ( o2nID != myOld2NewEntryMap.end() )
3399 return o2nID->second;
3401 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3402 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3405 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3406 if ( newShape->_is_nil() )
3407 return std::string();
3409 CORBA::String_var newEntry = newShape->GetStudyEntry();
3410 return newEntry.in();
3413 //================================================================================
3415 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3416 * Return zero if not found or there are more than one new ID
3418 int FindNew( int oldID )
3427 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3429 if ( myGIPMap[ oldID ].length() == 1 )
3431 newID = myGIPMap[ oldID ][ 0 ];
3433 else if ( myGIPMap[ oldID ].length() > 1 &&
3434 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3436 // select a meshed VERTEX
3437 SMESH_subMesh* newSM;
3438 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3439 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3440 ( !newSM->IsEmpty() ))
3441 newID = myGIPMap[ oldID ][ i ];
3447 //================================================================================
3449 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3450 * Return zero if the old shape is not kept as is in the new shape.
3452 int FindNewNotChanged( SMESH_subMesh* oldSM )
3455 return oldSM->GetId();
3457 int newID = FindNew( oldSM->GetId() );
3461 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3465 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3466 // one new sub-shape of the same type.
3468 if ( oldSM->DependsOn().size() !=
3469 newSM->DependsOn().size() )
3472 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3473 while ( srcSMIt->more() )
3475 oldSM = srcSMIt->next();
3476 int newSubID = FindNew( oldSM->GetId() );
3477 if ( getShapeType( myNewMesh_i, newSubID ) !=
3478 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3484 //================================================================================
3486 * \brief Return shape by study entry
3488 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3490 GEOM::GEOM_Object_var shape;
3491 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3492 if ( !so->_is_nil() )
3494 CORBA::Object_var obj = so->GetObject();
3495 shape = GEOM::GEOM_Object::_narrow( obj );
3497 return shape._retn();
3500 //================================================================================
3502 * \brief Fill myGIPMap by calling GetInPlaceMap()
3506 if ( !myGIPMapDone )
3508 myGIPMapDone = true;
3510 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3511 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3512 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3513 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3516 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3520 myGIPMap = new GEOM::ListOfListOfLong();
3525 //================================================================================
3527 * \brief Get new sub-shape by calling GetInPlace()
3529 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3531 GEOM::GEOM_Object_var newShape;
3533 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3534 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3535 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3538 newShape = op->GetInPlace( mainShapeNew, oldShape );
3543 return newShape._retn();
3546 //================================================================================
3548 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3549 * number of found IDs
3551 int findNewIDs( int oldID, std::vector< int >& newIDs )
3553 size_t prevNbIDs = newIDs.size();
3555 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3557 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3558 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3560 return newIDs.size() - prevNbIDs;
3563 //================================================================================
3565 * \brief Check if an object relates to the old shape
3567 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3569 if ( CORBA::is_nil( oldShape ))
3571 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3572 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3573 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3574 mainShapeOld1->_is_equivalent( oldShape ));
3577 //================================================================================
3579 * \brief Return shape type by shape ID
3581 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3583 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3584 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3585 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3588 //================================================================================
3590 * \brief Store a source sub-shape for which a counterpart not found and
3591 * a smesh object invalid due to that
3593 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3594 SALOMEDS::SObject_wrap smeshSO )
3596 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3597 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3599 CORBA::String_var smeshEntry = smeshSO->GetID();
3600 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3604 //================================================================================
3606 * \brief Store a source sub-shape for which a counterpart not found and
3607 * a smesh object invalid due to that
3609 void AddInvalid( std::string geomEntry,
3610 SALOMEDS::SObject_wrap smeshSO )
3612 if ( !geomEntry.empty() )
3614 CORBA::String_var smeshEntry = smeshSO->GetID();
3615 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3619 //================================================================================
3621 * \brief Store a source sub-shape for which a counterpart not found and
3622 * a smesh object invalid due to that
3624 void AddInvalid( int oldGeomID,
3625 SALOMEDS::SObject_wrap smeshSO )
3627 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3628 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3631 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3632 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3634 SMESH_Comment geomName( typeName[ shapeType ]);
3635 geomName << " #" << oldGeomID;
3637 CORBA::String_var smeshEntry = smeshSO->GetID();
3638 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3641 //================================================================================
3643 * \brief Return entries of a source sub-shape for which a counterpart not found and
3644 * of smesh objects invalid due to that
3646 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3647 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3650 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3651 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3653 nbSO += 1 + entry2entrySet->second.size();
3655 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3656 theInvalidEntries->length ( nbSO );
3657 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3659 entry2entrySet = myInvalidMap.begin();
3660 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3662 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3664 std::set< std::string > & entrySet = entry2entrySet->second;
3665 std::set< std::string >::iterator entry = entrySet.begin();
3666 for ( ; entry != entrySet.end(); ++entry )
3668 theInvalidEntries[ iEntry++ ] = entry->c_str();
3670 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3671 if ( !so->_is_nil() )
3672 theInvalidMeshSObjects[ iSO++ ] = so;
3677 }; // struct ShapeMapper
3679 //================================================================================
3681 * \brief Append an item to a CORBA sequence
3683 template < class CORBA_seq, class ITEM >
3684 void append( CORBA_seq& seq, ITEM item )
3686 if ( !CORBA::is_nil( item ))
3688 seq->length( 1 + seq->length() );
3689 seq[ seq->length() - 1 ] = item;
3692 } // namespace // utils for CopyMeshWithGeom()
3694 //================================================================================
3696 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3697 * \param [in] sourceMesh - a mesh to copy
3698 * \param [in] newGeometry - a new geometry
3699 * \param [in] toCopyGroups - to create groups in the new mesh
3700 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3701 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3702 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3703 * \param [out] newMesh - return a new mesh
3704 * \param [out] newGroups - return new groups
3705 * \param [out] newSubmeshes - return new sub-meshes
3706 * \param [out] newHypotheses - return new algorithms and hypotheses
3707 * \param [out] invalidEntries - return study entries of objects whose
3708 * counterparts are not found in the newGeometry, followed by entries
3709 * of mesh sub-objects that are invalid because they depend on a not found
3710 * preceding sub-shape
3711 * \return CORBA::Boolean - is a success
3713 //================================================================================
3715 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3716 GEOM::GEOM_Object_ptr theNewGeometry,
3717 const char* theMeshName,
3718 CORBA::Boolean theToCopyGroups,
3719 CORBA::Boolean theToReuseHypotheses,
3720 CORBA::Boolean theToCopyElements,
3721 SMESH::SMESH_Mesh_out theNewMesh,
3722 SMESH::ListOfGroups_out theNewGroups,
3723 SMESH::submesh_array_out theNewSubmeshes,
3724 SMESH::ListOfHypothesis_out theNewHypotheses,
3725 SMESH::string_array_out theInvalidEntries)
3727 if ( CORBA::is_nil( theSourceMesh ) ||
3728 CORBA::is_nil( theNewGeometry ))
3729 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3731 if ( !theSourceMesh->HasShapeToMesh() )
3732 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3737 TPythonDump pyDump(this); // prevent dump from CreateMesh()
3739 theNewMesh = CreateMesh( theNewGeometry );
3740 theNewGroups = new SMESH::ListOfGroups();
3741 theNewSubmeshes = new SMESH::submesh_array();
3742 theNewHypotheses = new SMESH::ListOfHypothesis();
3743 theInvalidEntries = new SMESH::string_array();
3745 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3747 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3748 GEOM::GEOM_Object_var geom, newGeom;
3749 SALOMEDS::SObject_wrap so;
3751 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3752 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3755 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3757 // treat hypotheses of mesh and sub-meshes
3758 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3759 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3761 bool isSubMesh = ( iSM < smList->length() );
3764 // create a new sub-mesh
3765 SMESH::SMESH_subMesh_var newSM;
3766 geom = smList[iSM]->GetSubShape();
3767 so = ObjectToSObject( smList[iSM] );
3768 CORBA::String_var name;
3769 if ( !so->_is_nil() )
3770 name = so->GetName();
3771 newGeom = shapeMapper.FindNew( geom );
3772 if ( newGeom->_is_nil() )
3774 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3775 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3780 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3782 append( theNewSubmeshes, newSM );
3784 if ( newGeom->_is_nil() )
3785 continue; // don't assign hypotheses
3789 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3791 so = ObjectToSObject( theNewMesh );
3792 SetName( so, theMeshName, "Mesh" );
3795 // assign hypotheses
3796 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3797 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3799 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3800 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3802 // get geometry hyp depends on
3803 std::vector< std::string > entryArray;
3804 std::vector< int > subIDArray;
3805 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3807 if ( !theToReuseHypotheses || dependsOnGeom )
3809 // create a new hypothesis
3810 CORBA::String_var type = hyp->GetName();
3811 CORBA::String_var lib = hyp->GetLibName();
3812 CORBA::String_var data = hyp_i->SaveTo();
3815 hyp = CreateHypothesis( type, lib );
3816 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3817 hyp_i->LoadFrom( data.in() );
3818 append( theNewHypotheses, hyp );
3822 // update geometry hyp depends on
3823 if ( dependsOnGeom )
3825 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3827 if ( !entryArray[ iGeo ].empty() )
3829 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3830 if ( newEntry.empty() )
3833 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3834 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3836 entryArray[ iGeo ] = newEntry;
3839 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3841 if ( subIDArray[ iGeo ] > 0 )
3843 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3847 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3848 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3850 subIDArray[ iGeo ] = newID;
3853 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3857 CORBA::String_var errorText;
3858 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3859 if ( errorText.in()[0] )
3862 } // loop on hypotheses
3863 } // loop on sub-meshes and mesh
3866 // copy mesh elements, keeping IDs
3867 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3868 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3870 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3871 ::SMESH_MeshEditor::ElemFeatures elemData;
3873 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3874 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3875 /*vertexLast=*/false);
3876 while ( srcSMIt->more() )
3878 SMESH_subMesh* srcSM = srcSMIt->next();
3879 if ( srcSM->IsEmpty() )
3880 continue; // not yet computed
3881 int newID = shapeMapper.FindNewNotChanged( srcSM );
3885 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3886 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3887 while ( nIt->more() )
3889 SMESH_NodeXYZ node( nIt->next() );
3890 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3892 const SMDS_PositionPtr pos = node->GetPosition();
3893 const double* uv = pos->GetParameters();
3894 switch ( pos->GetTypeOfPosition() )
3896 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3897 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3898 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3899 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3903 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3904 while( eIt->more() )
3906 const SMDS_MeshElement* e = eIt->next();
3907 elemData.Init( e, /*basicOnly=*/false );
3908 elemData.SetID( e->GetID() );
3909 elemData.myNodes.resize( e->NbNodes() );
3910 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3912 for ( iN = 0; nnIt->more(); ++iN )
3914 const SMDS_MeshNode* srcNode = nnIt->next();
3915 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3916 if ( !elemData.myNodes[ iN ])
3919 if ( iN == elemData.myNodes.size() )
3920 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3921 newMeshDS->SetMeshElementOnShape( newElem, newID );
3923 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3924 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3927 newMeshDS->Modified();
3933 TStr2StrMap old2newGroupMap;
3935 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3937 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3938 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3939 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3941 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3942 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3943 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3945 CORBA::String_var name = groups[ i ]->GetName();
3946 SMESH::ElementType elemType = groups[ i ]->GetType();
3948 SMESH::SMESH_GroupBase_var newGroup;
3950 if ( !stdlGroup->_is_nil() )
3952 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3954 SMESH::smIdType_array_var elemIDs = stdlGroup->GetIDs();
3955 const bool isElem = ( elemType != SMESH::NODE );
3956 CORBA::ULong iE = 0;
3957 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3958 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3960 if ( iE < elemIDs->length() )
3962 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3963 stdlGroup->Add( elemIDs );
3964 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3968 else if ( !geomGroup->_is_nil() )
3970 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3971 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3972 if ( newGeom->_is_nil() )
3974 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3975 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3980 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3983 else if ( !fltrGroup->_is_nil() )
3985 // replace geometry in a filter
3986 SMESH::Filter_var filter = fltrGroup->GetFilter();
3987 SMESH::Filter::Criteria_var criteria;
3988 filter->GetCriteria( criteria.out() );
3990 bool isMissingGroup = false;
3991 std::vector< std::string > badEntries;
3993 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3995 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3996 switch ( criteria[ iCr ].Type )
3998 case SMESH::FT_BelongToMeshGroup:
4000 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
4001 btgg->SetGroupID( thresholdID );
4002 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
4003 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
4004 if ( refGroupSO->_is_nil() )
4006 CORBA::String_var refID = refGroupSO->GetID();
4007 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
4008 if ( o2nID == old2newGroupMap.end() )
4010 isMissingGroup = true; // corresponding new group not yet created
4013 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
4015 if ( o2nID->second.empty() ) // new referred group is invalid
4016 badEntries.push_back( refID.in() );
4019 case SMESH::FT_BelongToGeom:
4020 case SMESH::FT_BelongToPlane:
4021 case SMESH::FT_BelongToCylinder:
4022 case SMESH::FT_BelongToGenSurface:
4023 case SMESH::FT_LyingOnGeom:
4025 std::string newID = shapeMapper.FindNew( thresholdID );
4026 criteria[ iCr ].ThresholdID = newID.c_str();
4027 if ( newID.empty() )
4028 badEntries.push_back( thresholdID );
4031 case SMESH::FT_ConnectedElements:
4033 if ( thresholdID && thresholdID[0] )
4035 std::string newID = shapeMapper.FindNew( thresholdID );
4036 criteria[ iCr ].ThresholdID = newID.c_str();
4037 if ( newID.empty() )
4038 badEntries.push_back( thresholdID );
4044 } // loop on criteria
4046 if ( isMissingGroup && i < nbGroups )
4048 // to treat the group again
4049 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
4053 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
4054 newFilter->SetCriteria( criteria );
4056 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
4057 newFilter->UnRegister();
4059 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4060 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
4061 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
4063 if ( isMissingGroup ) // all groups treated but a referred groups still not found
4065 invalidSObjects.push_back( ObjectToSObject( newGroup ));
4068 if ( !badEntries.empty() )
4071 } // treat a group on filter
4073 append( theNewGroups, newGroup );
4075 // fill old2newGroupMap
4076 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4077 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4078 if ( !srcSO->_is_nil() )
4080 CORBA::String_var srcID, newID("");
4081 srcID = srcSO->GetID();
4082 if ( !newSO->_is_nil() )
4083 newID = newSO->GetID();
4084 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4085 std::string( newID.in() )));
4088 if ( newGroup->_is_nil() )
4093 newMeshDS->CompactMesh();
4096 if ( !theMeshName || !theMeshName[0] )
4098 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4099 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4100 CORBA::String_var oldName = soOld->GetName();
4101 SetName( soNew, oldName.in(), "Mesh" );
4103 // mark invalid objects
4104 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4106 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4107 highLightInvalid( invalidSObjects[i].in(), true );
4110 << theNewMesh << ", "
4111 << theNewGroups << ", "
4112 << *theNewSubmeshes.ptr() << ", "
4113 << *theNewHypotheses.ptr() << ", "
4114 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4115 << theSourceMesh << ", "
4116 << theNewGeometry << ", "
4117 << "'" << theMeshName << "', "
4118 << theToCopyGroups << ", "
4119 << theToReuseHypotheses << ", "
4120 << theToCopyElements << " )";
4122 SMESH_CATCH( SMESH::throwCorbaException );
4127 //================================================================================
4129 * \brief Get version of MED format being used.
4131 //================================================================================
4133 char* SMESH_Gen_i::GetMEDFileVersion()
4135 MED::TInt majeur, mineur, release;
4136 majeur = mineur = release = 0;
4137 MED::GetVersionRelease(majeur, mineur, release);
4138 std::ostringstream version;
4139 version << majeur << "." << mineur << "." << release;
4140 return CORBA::string_dup( version.str().c_str() );
4143 //================================================================================
4145 * SMESH_Gen_i::GetMEDVersion
4147 * Get MED version of the file by its name
4149 //================================================================================
4151 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4153 std::string version = MED::GetMEDVersion( theFileName );
4154 return CORBA::string_dup( version.c_str() );
4157 //================================================================================
4159 * SMESH_Gen_i::CheckCompatibility
4161 * Check compatibility of file with MED format being used, read only.
4163 //================================================================================
4165 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4167 return MED::CheckCompatibility( theFileName );
4170 //================================================================================
4172 * SMESH_Gen_i::CheckWriteCompatibility
4174 * Check compatibility of file with MED format being used, for append on write.
4176 //================================================================================
4178 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4180 return MED::CheckCompatibility( theFileName, true );
4183 //================================================================================
4185 * SMESH_Gen_i::GetMeshNames
4187 * Get names of meshes defined in file with the specified name
4189 //================================================================================
4190 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4193 SMESH::string_array_var aResult = new SMESH::string_array();
4194 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4196 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4198 aResult->length( aNbMeshes );
4199 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4200 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4201 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4204 return aResult._retn();
4207 //=============================================================================
4211 * Save SMESH module's data
4213 //=============================================================================
4215 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4220 Kernel_Utils::Localizer loc;
4222 if (!myStudyContext)
4225 // Store study contents as a set of python commands
4228 SALOMEDS::Study_var aStudy = getStudyServant();
4230 // Declare a byte stream
4231 SALOMEDS::TMPFile_var aStreamFile;
4233 // Obtain a temporary dir
4234 TCollection_AsciiString tmpDir =
4235 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4237 // Create a sequence of files processed
4238 SALOMEDS_Tool::ListOfFiles aFileSeq;
4239 aFileSeq.reserve( NUM_TMP_FILES );
4241 TCollection_AsciiString aStudyName( "" );
4243 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4245 // Set names of temporary files
4246 TCollection_AsciiString filename =
4247 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4248 TCollection_AsciiString meshfile =
4249 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4250 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4251 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4252 filename = tmpDir + filename;
4253 meshfile = tmpDir + meshfile;
4256 HDFdataset* aDataset;
4257 HDFgroup* aTopGroup;
4259 HDFgroup* aSubGroup;
4260 HDFgroup* aSubSubGroup;
4261 hdf_size aSize[ 1 ];
4264 //Remove the files if they exist: BugID: 11225
4265 #ifndef WIN32 /* unix functionality */
4266 TCollection_AsciiString cmd("rm -f \"");
4268 TCollection_AsciiString cmd("del /F \"");
4278 system(cmd.ToCString());
4280 // MED writer to be used by storage process
4281 DriverMED_W_SMESHDS_Mesh writer;
4282 writer.SetFile( meshfile.ToCString() );
4283 //writer.SetSaveNumbers( false ); // bos #24400 -- it leads to change of element IDs
4286 // SetStoreName() to groups before storing hypotheses to let them refer to
4287 // groups using "store name", which is "Group <group_persistent_id>"
4289 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4290 for ( ; itBig->More(); itBig->Next() ) {
4291 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4292 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4293 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4294 if ( !CORBA::is_nil( anObject ) ) {
4295 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4296 if ( !myMesh->_is_nil() ) {
4297 myMesh->Load(); // load from study file if not yet done
4298 TPythonDump pd(this); // not to dump GetGroups()
4299 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4300 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4302 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4305 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4306 int anId = myStudyContext->findId( string( objStr.in() ) );
4308 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4309 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4310 aGrpBaseDS->SetStoreName( grpName );
4320 // ---> create HDF file
4321 aFile = new HDFfile( (char*) filename.ToCString() );
4322 aFile->CreateOnDisk();
4324 // --> iterator for top-level objects
4325 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4326 for ( ; itBig->More(); itBig->Next() ) {
4327 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4329 // --> hypotheses root branch (only one for the study)
4330 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4331 // create hypotheses root HDF group
4332 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4333 aTopGroup->CreateOnDisk();
4335 // iterator for all hypotheses
4336 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4337 for ( ; it->More(); it->Next() ) {
4338 SALOMEDS::SObject_wrap mySObject = it->Value();
4339 CORBA::Object_var anObject = SObjectToObject( mySObject );
4340 if ( !CORBA::is_nil( anObject ) ) {
4341 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4342 if ( !myHyp->_is_nil() ) {
4343 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4345 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4346 std::string hypname = hn.in();
4347 std::string libname = ln.in();
4349 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4350 // WIN32 and ".so" for X-system) must be deleted
4351 int libname_len = libname.length();
4353 if( libname_len > 4 )
4354 libname.resize( libname_len - 4 );
4356 // PAL17753 (Regression: missing hypothesis in restored study)
4357 // "lib" also should be removed from the beginning
4358 if( libname_len > 6 )
4359 libname = libname.substr( 3, libname_len - 3 - 3 );
4361 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4362 CORBA::String_var hypdata = myImpl->SaveTo();
4363 int id = myStudyContext->findId( string( objStr.in() ));
4365 // for each hypothesis create HDF group basing on its id
4366 char hypGrpName[30];
4367 sprintf( hypGrpName, "Hypothesis %d", id );
4368 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4369 aGroup->CreateOnDisk();
4370 // --> type name of hypothesis
4371 aSize[ 0 ] = hypname.length() + 1;
4372 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4373 aDataset->CreateOnDisk();
4374 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4375 aDataset->CloseOnDisk();
4376 // --> server plugin library name of hypothesis
4377 aSize[ 0 ] = libname.length() + 1;
4378 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4379 aDataset->CreateOnDisk();
4380 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4381 aDataset->CloseOnDisk();
4382 // --> persistent data of hypothesis
4383 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4384 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4385 aDataset->CreateOnDisk();
4386 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4387 aDataset->CloseOnDisk();
4388 // close hypothesis HDF group
4389 aGroup->CloseOnDisk();
4394 // close hypotheses root HDF group
4395 aTopGroup->CloseOnDisk();
4397 // --> algorithms root branch (only one for the study)
4398 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4399 // create algorithms root HDF group
4400 aTopGroup = new HDFgroup( "Algorithms", aFile );
4401 aTopGroup->CreateOnDisk();
4403 // iterator for all algorithms
4404 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4405 for ( ; it->More(); it->Next() ) {
4406 SALOMEDS::SObject_wrap mySObject = it->Value();
4407 CORBA::Object_var anObject = SObjectToObject( mySObject );
4408 if ( !CORBA::is_nil( anObject ) ) {
4409 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4410 if ( !myHyp->_is_nil() ) {
4411 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4413 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4414 std::string hypname = hn.in();
4415 std::string libname = ln.in();
4417 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4418 // WIN32 and ".so" for X-system) must be deleted
4419 int libname_len = libname.length();
4421 if( libname_len > 4 )
4422 libname.resize( libname_len - 4 );
4424 // PAL17753 (Regression: missing hypothesis in restored study)
4425 // "lib" also should be removed from the beginning
4426 if( libname_len > 6 )
4427 libname = libname.substr( 3, libname_len - 3 - 3 );
4429 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4430 CORBA::String_var hypdata = myImpl->SaveTo();
4431 int id = myStudyContext->findId( string( objStr.in() ) );
4433 // for each algorithm create HDF group basing on its id
4434 char hypGrpName[30];
4435 sprintf( hypGrpName, "Algorithm %d", id );
4436 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4437 aGroup->CreateOnDisk();
4438 // --> type name of algorithm
4439 aSize[0] = hypname.length() + 1;
4440 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4441 aDataset->CreateOnDisk();
4442 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4443 aDataset->CloseOnDisk();
4444 // --> server plugin library name of hypothesis
4445 aSize[0] = libname.length() + 1;
4446 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4447 aDataset->CreateOnDisk();
4448 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4449 aDataset->CloseOnDisk();
4450 // --> persistent data of algorithm
4451 aSize[0] = strlen( hypdata.in() ) + 1;
4452 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4453 aDataset->CreateOnDisk();
4454 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4455 aDataset->CloseOnDisk();
4456 // close algorithm HDF group
4457 aGroup->CloseOnDisk();
4462 // close algorithms root HDF group
4463 aTopGroup->CloseOnDisk();
4465 // --> mesh objects roots branches
4466 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4467 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4468 if ( !CORBA::is_nil( anObject ) ) {
4469 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4470 if ( !myMesh->_is_nil() ) {
4471 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4473 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4474 int id = myStudyContext->findId( string( objStr.in() ) );
4475 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4476 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4477 bool hasShape = myLocMesh.HasShapeToMesh();
4479 // for each mesh open the HDF group basing on its id
4480 char meshGrpName[ 30 ];
4481 sprintf( meshGrpName, "Mesh %d", id );
4482 aTopGroup = new HDFgroup( meshGrpName, aFile );
4483 aTopGroup->CreateOnDisk();
4485 // --> put dataset to hdf file which is a flag that mesh has data
4486 string strHasData = "0";
4487 // check if the mesh is not empty
4488 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4489 // write mesh data to med file
4490 writer.SetMesh( mySMESHDSMesh );
4491 writer.SetMeshId( id );
4494 aSize[ 0 ] = strHasData.length() + 1;
4495 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4496 aDataset->CreateOnDisk();
4497 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4498 aDataset->CloseOnDisk();
4501 // for each mesh open the HDF group basing on its auto color parameter
4502 char meshAutoColorName[ 30 ];
4503 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4505 anAutoColor[0] = myImpl->GetAutoColor();
4507 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4508 aDataset->CreateOnDisk();
4509 aDataset->WriteOnDisk( anAutoColor );
4510 aDataset->CloseOnDisk();
4512 // issue 0020693. Store _isModified flag
4513 int isModified = myLocMesh.GetIsModified();
4515 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4516 aDataset->CreateOnDisk();
4517 aDataset->WriteOnDisk( &isModified );
4518 aDataset->CloseOnDisk();
4520 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4521 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4523 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4524 aDataset->CreateOnDisk();
4525 aDataset->WriteOnDisk( &meshPersistentId );
4526 aDataset->CloseOnDisk();
4528 // Store SMESH_Mesh_i::_mainShapeTick
4529 int shapeTick = myImpl->MainShapeTick();
4531 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4532 aDataset->CreateOnDisk();
4533 aDataset->WriteOnDisk( &shapeTick );
4534 aDataset->CloseOnDisk();
4536 // write reference on a shape if exists
4537 SALOMEDS::SObject_wrap myRef;
4538 bool shapeRefFound = false;
4539 bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4541 SALOMEDS::SObject_wrap myShape;
4542 bool ok = myRef->ReferencedObject( myShape.inout() );
4544 CORBA::Object_var shapeObj = myShape->GetObject();
4545 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4546 CORBA::String_var myRefOnObject = myShape->GetID();
4547 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4548 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4549 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4550 aDataset->CreateOnDisk();
4551 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4552 aDataset->CloseOnDisk();
4558 std::string info = myImpl->FileInfoToString();
4559 if ( !info.empty() )
4561 aSize[ 0 ] = info.size();
4562 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4563 aDataset->CreateOnDisk();
4564 aDataset->WriteOnDisk( (char*) info.data() );
4565 aDataset->CloseOnDisk();
4568 // write applied hypotheses if exist
4569 SALOMEDS::SObject_wrap myHypBranch;
4570 found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4571 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4572 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4574 if ( found && (shapeRefFound || !hasShape) ) {
4575 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4576 aGroup->CreateOnDisk();
4578 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4580 for ( ; it->More(); it->Next() ) {
4581 SALOMEDS::SObject_wrap mySObject = it->Value();
4582 SALOMEDS::SObject_wrap myRefOnHyp;
4583 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4585 // san - it is impossible to recover applied hypotheses
4586 // using their entries within Load() method,
4587 // for there are no AttributeIORs in the study when Load() is working.
4588 // Hence, it is better to store persistent IDs of hypotheses as references to them
4590 //string myRefOnObject = myRefOnHyp->GetID();
4591 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4592 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4593 int id = myStudyContext->findId( string( objStr.in() ) );
4594 //if ( myRefOnObject.length() > 0 ) {
4595 //aSize[ 0 ] = myRefOnObject.length() + 1;
4596 char hypName[ 30 ], hypId[ 30 ];
4597 sprintf( hypName, "Hyp %d", ++hypNb );
4598 sprintf( hypId, "%d", id );
4599 aSize[ 0 ] = strlen( hypId ) + 1;
4600 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4601 aDataset->CreateOnDisk();
4602 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4603 aDataset->WriteOnDisk( hypId );
4604 aDataset->CloseOnDisk();
4608 aGroup->CloseOnDisk();
4611 // write applied algorithms if exist
4612 SALOMEDS::SObject_wrap myAlgoBranch;
4613 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4614 myAlgoBranch.inout() );
4615 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4616 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4618 if ( found && (shapeRefFound || !hasShape)) {
4619 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4620 aGroup->CreateOnDisk();
4622 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4624 for ( ; it->More(); it->Next() ) {
4625 SALOMEDS::SObject_wrap mySObject = it->Value();
4626 SALOMEDS::SObject_wrap myRefOnAlgo;
4627 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4629 // san - it is impossible to recover applied algorithms
4630 // using their entries within Load() method,
4631 // for there are no AttributeIORs in the study when Load() is working.
4632 // Hence, it is better to store persistent IDs of algorithms as references to them
4634 //string myRefOnObject = myRefOnAlgo->GetID();
4635 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4636 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4637 int id = myStudyContext->findId( string( objStr.in() ) );
4638 //if ( myRefOnObject.length() > 0 ) {
4639 //aSize[ 0 ] = myRefOnObject.length() + 1;
4640 char algoName[ 30 ], algoId[ 30 ];
4641 sprintf( algoName, "Algo %d", ++algoNb );
4642 sprintf( algoId, "%d", id );
4643 aSize[ 0 ] = strlen( algoId ) + 1;
4644 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4645 aDataset->CreateOnDisk();
4646 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4647 aDataset->WriteOnDisk( algoId );
4648 aDataset->CloseOnDisk();
4652 aGroup->CloseOnDisk();
4655 // --> submesh objects sub-branches
4657 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4658 SALOMEDS::SObject_wrap mySubmeshBranch;
4659 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4661 if ( found ) // check if there is shape reference in submeshes
4663 bool hasShapeRef = false;
4664 SALOMEDS::ChildIterator_wrap itSM =
4665 aStudy->NewChildIterator( mySubmeshBranch );
4666 for ( ; itSM->More(); itSM->Next() ) {
4667 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4668 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4669 mySubRef->ReferencedObject( myShape.inout() );
4670 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4673 { // remove one submesh
4674 if ( shapeRefFound )
4675 { // unassign hypothesis
4676 SMESH::SMESH_subMesh_var mySubMesh =
4677 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4678 if ( !mySubMesh->_is_nil() ) {
4679 int shapeID = mySubMesh->GetId();
4680 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4681 const list<const SMESHDS_Hypothesis*>& hypList =
4682 mySMESHDSMesh->GetHypothesis( S );
4683 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4684 while ( hyp != hypList.end() ) {
4685 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4686 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4690 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4692 } // loop on submeshes of a type
4693 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4694 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4697 } // end check if there is shape reference in submeshes
4699 char name_meshgroup[ 30 ];
4700 if ( i == GetSubMeshOnVertexTag() )
4701 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4702 else if ( i == GetSubMeshOnEdgeTag() )
4703 strcpy( name_meshgroup, "SubMeshes On Edge" );
4704 else if ( i == GetSubMeshOnWireTag() )
4705 strcpy( name_meshgroup, "SubMeshes On Wire" );
4706 else if ( i == GetSubMeshOnFaceTag() )
4707 strcpy( name_meshgroup, "SubMeshes On Face" );
4708 else if ( i == GetSubMeshOnShellTag() )
4709 strcpy( name_meshgroup, "SubMeshes On Shell" );
4710 else if ( i == GetSubMeshOnSolidTag() )
4711 strcpy( name_meshgroup, "SubMeshes On Solid" );
4712 else if ( i == GetSubMeshOnCompoundTag() )
4713 strcpy( name_meshgroup, "SubMeshes On Compound" );
4715 // for each type of submeshes create container HDF group
4716 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4717 aGroup->CreateOnDisk();
4719 // iterator for all submeshes of given type
4720 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4721 for ( ; itSM->More(); itSM->Next() ) {
4722 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4723 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4724 if ( !CORBA::is_nil( anSubObject ))
4726 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4727 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4728 int subid = myStudyContext->findId( string( objStr.in() ) );
4730 // for each mesh open the HDF group basing on its id
4731 char submeshGrpName[ 30 ];
4732 sprintf( submeshGrpName, "SubMesh %d", subid );
4733 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4734 aSubGroup->CreateOnDisk();
4736 // write reference on a shape, already checked if it exists
4737 SALOMEDS::SObject_wrap mySubRef, myShape;
4738 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4739 mySubRef->ReferencedObject( myShape.inout() );
4740 string myRefOnObject = myShape->GetID();
4741 if ( myRefOnObject.length() > 0 ) {
4742 aSize[ 0 ] = myRefOnObject.length() + 1;
4743 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4744 aDataset->CreateOnDisk();
4745 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4746 aDataset->CloseOnDisk();
4749 // write applied hypotheses if exist
4750 SALOMEDS::SObject_wrap mySubHypBranch;
4751 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4752 mySubHypBranch.inout() );
4754 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4755 aSubSubGroup->CreateOnDisk();
4757 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4759 for ( ; it->More(); it->Next() ) {
4760 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4761 SALOMEDS::SObject_wrap myRefOnHyp;
4762 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4764 //string myRefOnObject = myRefOnHyp->GetID();
4765 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4766 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4767 int id = myStudyContext->findId( string( objStr.in() ) );
4768 //if ( myRefOnObject.length() > 0 ) {
4769 //aSize[ 0 ] = myRefOnObject.length() + 1;
4770 char hypName[ 30 ], hypId[ 30 ];
4771 sprintf( hypName, "Hyp %d", ++hypNb );
4772 sprintf( hypId, "%d", id );
4773 aSize[ 0 ] = strlen( hypId ) + 1;
4774 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4775 aDataset->CreateOnDisk();
4776 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4777 aDataset->WriteOnDisk( hypId );
4778 aDataset->CloseOnDisk();
4782 aSubSubGroup->CloseOnDisk();
4785 // write applied algorithms if exist
4786 SALOMEDS::SObject_wrap mySubAlgoBranch;
4787 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4788 mySubAlgoBranch.inout() );
4790 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4791 aSubSubGroup->CreateOnDisk();
4793 SALOMEDS::ChildIterator_wrap it =
4794 aStudy->NewChildIterator( mySubAlgoBranch );
4796 for ( ; it->More(); it->Next() ) {
4797 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4798 SALOMEDS::SObject_wrap myRefOnAlgo;
4799 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4801 //string myRefOnObject = myRefOnAlgo->GetID();
4802 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4803 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4804 int id = myStudyContext->findId( string( objStr.in() ) );
4805 //if ( myRefOnObject.length() > 0 ) {
4806 //aSize[ 0 ] = myRefOnObject.length() + 1;
4807 char algoName[ 30 ], algoId[ 30 ];
4808 sprintf( algoName, "Algo %d", ++algoNb );
4809 sprintf( algoId, "%d", id );
4810 aSize[ 0 ] = strlen( algoId ) + 1;
4811 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4812 aDataset->CreateOnDisk();
4813 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4814 aDataset->WriteOnDisk( algoId );
4815 aDataset->CloseOnDisk();
4819 aSubSubGroup->CloseOnDisk();
4821 // close submesh HDF group
4822 aSubGroup->CloseOnDisk();
4825 // close container of submeshes by type HDF group
4826 aGroup->CloseOnDisk();
4830 // store submesh order if any
4831 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4832 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4833 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4834 char order_list[ 30 ];
4835 strcpy( order_list, "Mesh Order" );
4836 // count number of submesh ids
4838 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4839 for ( ; idIt != theOrderIds.end(); idIt++ )
4840 nbIDs += (*idIt).size();
4841 // number of values = number of IDs +
4842 // number of lists (for separators) - 1
4843 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4844 idIt = theOrderIds.begin();
4845 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4846 const TListOfInt& idList = *idIt;
4847 if (idIt != theOrderIds.begin()) // not first list
4848 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4849 // dump submesh ids from current list
4850 TListOfInt::const_iterator id_smId = idList.begin();
4851 for( ; id_smId != idList.end(); id_smId++ )
4852 smIDs[ i++ ] = *id_smId;
4855 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4857 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4858 aDataset->CreateOnDisk();
4859 aDataset->WriteOnDisk( smIDs );
4860 aDataset->CloseOnDisk();
4864 if ( !theOrderIds.empty() && isNewOrederVersion )
4866 // convert ids to entries
4867 std::list< std::list< std::string > > orderEntryLists;
4868 for ( const TListOfInt& idList : theOrderIds )
4870 orderEntryLists.emplace_back();
4871 std::list< std::string > & entryList = orderEntryLists.back();
4872 for ( const int& id : idList )
4874 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4875 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4876 SALOMEDS::SObject_var so = ObjectToSObject( go );
4877 if ( !so->_is_nil() )
4879 CORBA::String_var entry = so->GetID();
4880 entryList.emplace_back( entry.in() );
4884 // convert orderEntryLists to string
4885 std::ostringstream ostream;
4886 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4887 std::string orderEntryString = ostream.str();
4890 aSize[ 0 ] = orderEntryString.size() + 1;
4891 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4892 aDataset->CreateOnDisk();
4893 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4894 aDataset->CloseOnDisk();
4897 // groups root sub-branch
4898 SALOMEDS::SObject_wrap myGroupsBranch;
4899 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4900 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4902 char name_group[ 30 ];
4903 if ( i == GetNodeGroupsTag() )
4904 strcpy( name_group, "Groups of Nodes" );
4905 else if ( i == GetEdgeGroupsTag() )
4906 strcpy( name_group, "Groups of Edges" );
4907 else if ( i == GetFaceGroupsTag() )
4908 strcpy( name_group, "Groups of Faces" );
4909 else if ( i == GetVolumeGroupsTag() )
4910 strcpy( name_group, "Groups of Volumes" );
4911 else if ( i == Get0DElementsGroupsTag() )
4912 strcpy( name_group, "Groups of 0D Elements" );
4913 else if ( i == GetBallElementsGroupsTag() )
4914 strcpy( name_group, "Groups of Balls" );
4916 aGroup = new HDFgroup( name_group, aTopGroup );
4917 aGroup->CreateOnDisk();
4919 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4920 for ( ; it->More(); it->Next() ) {
4921 SALOMEDS::SObject_wrap mySObject = it->Value();
4922 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4923 if ( !CORBA::is_nil( aSubObject ) ) {
4924 SMESH_GroupBase_i* myGroupImpl =
4925 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4928 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4932 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4933 int anId = myStudyContext->findId( string( objStr.in() ) );
4935 // For each group, create a dataset named "Group <group_persistent_id>"
4936 // and store the group's user name into it
4937 const char* grpName = aGrpBaseDS->GetStoreName();
4938 CORBA::String_var aUserName = myGroupImpl->GetName();
4939 aSize[ 0 ] = strlen( aUserName ) + 1;
4941 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4942 aDataset->CreateOnDisk();
4943 aDataset->WriteOnDisk( aUserName );
4944 aDataset->CloseOnDisk();
4947 // For each group, create a dataset named "Group <group_persistent_id> Color"
4948 // and store the group's color into it
4949 char grpColorName[ 30 ];
4950 sprintf( grpColorName, "ColorGroup %d", anId );
4951 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4953 anRGB[ 0 ] = aColor.R;
4954 anRGB[ 1 ] = aColor.G;
4955 anRGB[ 2 ] = aColor.B;
4957 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4958 aDataset->CreateOnDisk();
4959 aDataset->WriteOnDisk( anRGB );
4960 aDataset->CloseOnDisk();
4962 // Pass SMESHDS_Group to MED writer
4963 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4965 writer.AddGroup( aGrpDS );
4967 // write reference on a shape if exists
4968 SMESHDS_GroupOnGeom* aGeomGrp =
4969 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4971 SALOMEDS::SObject_wrap mySubRef, myShape;
4972 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4973 mySubRef->ReferencedObject( myShape.inout() ) &&
4974 !CORBA::is_nil( myShape->GetObject() ))
4976 CORBA::String_var myRefOnObject = myShape->GetID();
4977 if ( myRefOnObject.in()[0] ) {
4978 char aRefName[ 30 ];
4979 sprintf( aRefName, "Ref on shape %d", anId);
4980 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4981 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4982 aDataset->CreateOnDisk();
4983 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4984 aDataset->CloseOnDisk();
4987 else // shape ref is invalid:
4989 // save a group on geometry as ordinary group
4990 writer.AddGroup( aGeomGrp );
4993 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4994 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4996 std::string str = aFilterGrp_i->FilterToString();
4997 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4998 aSize[ 0 ] = str.length() + 1;
4999 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
5000 aDataset->CreateOnDisk();
5001 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
5002 aDataset->CloseOnDisk();
5006 aGroup->CloseOnDisk();
5010 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
5012 // Flush current mesh information into MED file
5015 // save info on nb of elements
5016 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
5018 // maybe a shape was deleted in the study
5019 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
5020 TopoDS_Shape nullShape;
5021 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
5024 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
5029 aGroup = new HDFgroup( "Submeshes", aTopGroup );
5030 aGroup->CreateOnDisk();
5032 // each element belongs to one or none submesh,
5033 // so for each node/element, we store a submesh ID
5035 // Store submesh IDs
5036 for ( int isNode = 0; isNode < 2; ++isNode )
5038 SMDS_ElemIteratorPtr eIt =
5039 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
5040 smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
5043 std::vector<int> smIDs; smIDs.reserve( nbElems );
5044 while ( eIt->more() )
5045 if ( const SMDS_MeshElement* e = eIt->next())
5046 smIDs.push_back( e->getshapeId() );
5048 aSize[ 0 ] = nbElems;
5049 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
5050 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5051 aDataset->CreateOnDisk();
5052 aDataset->WriteOnDisk( & smIDs[0] );
5053 aDataset->CloseOnDisk();
5056 aGroup->CloseOnDisk();
5058 // Store node positions on sub-shapes (SMDS_Position):
5059 // ----------------------------------------------------
5061 aGroup = new HDFgroup( "Node Positions", aTopGroup );
5062 aGroup->CreateOnDisk();
5064 // in aGroup, create 5 datasets to contain:
5065 // "Nodes on Edges" - ID of node on edge
5066 // "Edge positions" - U parameter on node on edge
5067 // "Nodes on Faces" - ID of node on face
5068 // "Face U positions" - U parameter of node on face
5069 // "Face V positions" - V parameter of node on face
5071 // Find out nb of nodes on edges and faces
5072 // Collect corresponding sub-meshes
5073 int nbEdgeNodes = 0, nbFaceNodes = 0;
5074 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5075 // loop on SMESHDS_SubMesh'es
5076 while ( smIt->more() )
5078 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5079 if ( aSubMesh->IsComplexSubmesh() )
5080 continue; // submesh containing other submeshs
5081 smIdType nbNodes = aSubMesh->NbNodes();
5082 if ( nbNodes == 0 ) continue;
5084 int aShapeID = aSubMesh->GetID();
5085 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5087 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5088 // write only SMDS_FacePosition and SMDS_EdgePosition
5089 switch ( aShapeType ) {
5091 nbFaceNodes += nbNodes;
5092 aFaceSM.push_back( aSubMesh );
5095 nbEdgeNodes += nbNodes;
5096 aEdgeSM.push_back( aSubMesh );
5102 // Treat positions on edges or faces
5103 for ( int onFace = 0; onFace < 2; onFace++ )
5105 // Create arrays to store in datasets
5106 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5107 if (!nbNodes) continue;
5108 int* aNodeIDs = new int [ nbNodes ];
5109 double* aUPos = new double [ nbNodes ];
5110 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5113 // loop on sub-meshes
5114 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5115 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5116 for ( ; itSM != pListSM->end(); itSM++ )
5118 SMESHDS_SubMesh* aSubMesh = (*itSM);
5120 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5121 // loop on nodes in aSubMesh
5122 while ( itNode->more() )
5125 const SMDS_MeshNode* node = itNode->next();
5126 aNodeIDs [ iNode ] = node->GetID();
5129 const SMDS_PositionPtr pos = node->GetPosition();
5130 if ( onFace ) { // on FACE
5131 SMDS_FacePositionPtr fPos = pos;
5133 aUPos[ iNode ] = fPos->GetUParameter();
5134 aVPos[ iNode ] = fPos->GetVParameter();
5141 SMDS_EdgePositionPtr ePos = pos;
5143 aUPos[ iNode ] = ePos->GetUParameter();
5149 } // loop on nodes in aSubMesh
5150 } // loop on sub-meshes
5155 aSize[ 0 ] = nbNodes;
5157 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5158 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5159 aDataset->CreateOnDisk();
5160 aDataset->WriteOnDisk( aNodeIDs );
5161 aDataset->CloseOnDisk();
5164 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5165 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5166 aDataset->CreateOnDisk();
5167 aDataset->WriteOnDisk( aUPos );
5168 aDataset->CloseOnDisk();
5171 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5172 aDataset->CreateOnDisk();
5173 aDataset->WriteOnDisk( aVPos );
5174 aDataset->CloseOnDisk();
5179 if ( aVPos ) delete [] aVPos;
5181 } // treat positions on edges or faces
5183 // close "Node Positions" group
5184 aGroup->CloseOnDisk();
5186 } // if ( there are submeshes in SMESHDS_Mesh )
5189 // close mesh HDF group
5190 aTopGroup->CloseOnDisk();
5198 aFile->CloseOnDisk();
5201 // Convert temporary files to stream
5202 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5204 // Remove temporary files and directory
5206 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5208 return aStreamFile._retn();
5211 //=============================================================================
5213 * SMESH_Gen_i::SaveASCII
5215 * Save SMESH module's data in ASCII format
5217 //=============================================================================
5219 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5221 bool isMultiFile ) {
5222 MESSAGE( "SMESH_Gen_i::SaveASCII" );
5223 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5224 return aStreamFile._retn();
5226 //after usual saving needs to encipher binary to text string
5227 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5228 int size = aStreamFile.in().length();
5229 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5230 for ( int i = 0; i < size; i++ )
5231 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5233 buffer[size * 3] = '\0';
5235 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5237 return anAsciiStreamFile._retn();
5240 //=============================================================================
5244 * Load SMESH module's data
5246 //=============================================================================
5248 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5249 const SALOMEDS::TMPFile& theStream,
5253 UpdateStudy(); // load geom data
5254 Kernel_Utils::Localizer loc;
5256 SALOMEDS::Study_var aStudy = getStudyServant();
5258 // Get temporary files location
5259 TCollection_AsciiString tmpDir =
5260 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5262 // Convert the stream into sequence of files to process
5263 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5266 TCollection_AsciiString aStudyName( "" );
5267 if ( isMultiFile ) {
5268 CORBA::WString_var url = aStudy->URL();
5269 SMESHUtils::ArrayDeleter<const char> urlMulibyte( Kernel_Utils::encode( url.in()) );
5270 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( urlMulibyte.get() ).c_str();
5272 // Set names of temporary files
5273 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5274 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5278 HDFdataset* aDataset;
5279 HDFgroup* aTopGroup;
5281 HDFgroup* aSubGroup;
5282 HDFgroup* aSubSubGroup;
5285 // ---> open HDF file
5286 aFile = new HDFfile( (char*) filename.ToCString() );
5288 aFile->OpenOnDisk( HDF_RDONLY );
5290 catch ( HDFexception ) {
5291 INFOS( "Load(): " << filename << " not found!" );
5295 TPythonDump pd(this); // prevent dump during loading
5297 // For PAL13473 ("Repetitive mesh") implementation.
5298 // New dependencies between SMESH objects are established:
5299 // now hypotheses can refer to meshes, shapes and other hypotheses.
5300 // To keep data consistent, the following order of data restoration
5302 // 1. Create hypotheses
5303 // 2. Create all meshes
5304 // 3. Load hypotheses' data
5307 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5308 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5309 list< SMESH::Filter_var > filters;
5311 // get total number of top-level groups
5312 int aNbGroups = aFile->nInternalObjects();
5313 if ( aNbGroups > 0 ) {
5314 // --> in first turn we should read&create hypotheses
5315 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5316 // open hypotheses root HDF group
5317 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5318 aTopGroup->OpenOnDisk();
5320 // get number of hypotheses
5321 int aNbObjects = aTopGroup->nInternalObjects();
5322 for ( int j = 0; j < aNbObjects; j++ ) {
5323 // try to identify hypothesis
5324 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5325 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5327 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5328 // open hypothesis group
5329 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5330 aGroup->OpenOnDisk();
5332 // --> get hypothesis id
5333 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5338 // get number of datasets
5339 int aNbSubObjects = aGroup->nInternalObjects();
5340 for ( int k = 0; k < aNbSubObjects; k++ ) {
5342 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5343 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5344 // --> get hypothesis name
5345 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5346 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5347 aDataset->OpenOnDisk();
5348 size = aDataset->GetSize();
5349 char* hypname_str = new char[ size ];
5350 aDataset->ReadFromDisk( hypname_str );
5351 hypname = string( hypname_str );
5352 delete [] hypname_str;
5353 aDataset->CloseOnDisk();
5355 // --> get hypothesis plugin library name
5356 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5357 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5358 aDataset->OpenOnDisk();
5359 size = aDataset->GetSize();
5360 char* libname_str = new char[ size ];
5361 aDataset->ReadFromDisk( libname_str );
5362 SCRUTE( libname_str );
5363 libname = string( libname_str );
5364 delete [] libname_str;
5365 aDataset->CloseOnDisk();
5367 // --> get hypothesis data
5368 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5369 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5370 aDataset->OpenOnDisk();
5371 size = aDataset->GetSize();
5372 char* hypdata_str = new char[ size ];
5373 aDataset->ReadFromDisk( hypdata_str );
5374 hypdata = string( hypdata_str );
5375 delete [] hypdata_str;
5376 aDataset->CloseOnDisk();
5379 // close hypothesis HDF group
5380 aGroup->CloseOnDisk();
5382 // --> restore hypothesis from data
5383 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5384 MESSAGE("VSR - load hypothesis : id = " << id <<
5385 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5386 SMESH::SMESH_Hypothesis_var myHyp;
5388 try { // protect persistence mechanism against exceptions
5389 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5392 INFOS( "Exception during hypothesis creation" );
5395 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5397 // myImpl->LoadFrom( hypdata.c_str() );
5398 hypDataList.push_back( make_pair( myImpl, hypdata ));
5399 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5400 int newId = myStudyContext->findId( iorString.in() );
5401 myStudyContext->mapOldToNew( id, newId );
5404 MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5408 // close hypotheses root HDF group
5409 aTopGroup->CloseOnDisk();
5413 // --> then we should read&create algorithms
5414 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5415 // open algorithms root HDF group
5416 aTopGroup = new HDFgroup( "Algorithms", aFile );
5417 aTopGroup->OpenOnDisk();
5419 // get number of algorithms
5420 int aNbObjects = aTopGroup->nInternalObjects();
5421 for ( int j = 0; j < aNbObjects; j++ ) {
5422 // try to identify algorithm
5423 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5424 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5426 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5427 // open algorithm group
5428 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5429 aGroup->OpenOnDisk();
5431 // --> get algorithm id
5432 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5437 // get number of datasets
5438 int aNbSubObjects = aGroup->nInternalObjects();
5439 for ( int k = 0; k < aNbSubObjects; k++ ) {
5441 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5442 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5443 // --> get algorithm name
5444 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5445 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5446 aDataset->OpenOnDisk();
5447 size = aDataset->GetSize();
5448 char* hypname_str = new char[ size ];
5449 aDataset->ReadFromDisk( hypname_str );
5450 hypname = string( hypname_str );
5451 delete [] hypname_str;
5452 aDataset->CloseOnDisk();
5454 // --> get algorithm plugin library name
5455 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5456 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5457 aDataset->OpenOnDisk();
5458 size = aDataset->GetSize();
5459 char* libname_str = new char[ size ];
5460 aDataset->ReadFromDisk( libname_str );
5461 SCRUTE( libname_str );
5462 libname = string( libname_str );
5463 delete [] libname_str;
5464 aDataset->CloseOnDisk();
5466 // --> get algorithm data
5467 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5468 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5469 aDataset->OpenOnDisk();
5470 size = aDataset->GetSize();
5471 char* hypdata_str = new char[ size ];
5472 aDataset->ReadFromDisk( hypdata_str );
5473 SCRUTE( hypdata_str );
5474 hypdata = string( hypdata_str );
5475 delete [] hypdata_str;
5476 aDataset->CloseOnDisk();
5479 // close algorithm HDF group
5480 aGroup->CloseOnDisk();
5482 // --> restore algorithm from data
5483 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5484 MESSAGE("VSR - load algo : id = " << id <<
5485 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5486 SMESH::SMESH_Hypothesis_var myHyp;
5488 try { // protect persistence mechanism against exceptions
5489 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5491 catch( SALOME::SALOME_Exception& ex )
5493 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5496 INFOS( "Exception during hypothesis creation" );
5499 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5501 //myImpl->LoadFrom( hypdata.c_str() );
5502 hypDataList.push_back( make_pair( myImpl, hypdata ));
5503 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5504 int newId = myStudyContext->findId( iorString.in() );
5505 myStudyContext->mapOldToNew( id, newId );
5508 MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5512 // close algorithms root HDF group
5513 aTopGroup->CloseOnDisk();
5517 // --> the rest groups should be meshes
5518 for ( int i = 0; i < aNbGroups; i++ ) {
5519 // identify next group
5520 char meshName[ HDF_NAME_MAX_LEN+1 ];
5521 aFile->InternalObjectIndentify( i, meshName );
5523 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5525 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5529 // open mesh HDF group
5530 aTopGroup = new HDFgroup( meshName, aFile );
5531 aTopGroup->OpenOnDisk();
5533 // get number of child HDF objects
5534 int aNbObjects = aTopGroup->nInternalObjects();
5535 if ( aNbObjects > 0 ) {
5537 MESSAGE( "VSR - load mesh : id = " << id );
5538 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5539 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5540 if ( !myNewMeshImpl )
5542 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5544 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5545 int newId = myStudyContext->findId( iorString.in() );
5546 myStudyContext->mapOldToNew( id, newId );
5549 // try to read and set auto color flag
5550 char aMeshAutoColorName[ 30 ];
5551 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5552 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5554 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5555 aDataset->OpenOnDisk();
5556 size = aDataset->GetSize();
5557 int* anAutoColor = new int[ size ];
5558 aDataset->ReadFromDisk( anAutoColor );
5559 aDataset->CloseOnDisk();
5560 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5561 delete [] anAutoColor;
5564 // try to read and set reference to shape
5565 GEOM::GEOM_Object_var aShapeObject;
5566 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5567 // load mesh "Ref on shape" - it's an entry to SObject
5568 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5569 aDataset->OpenOnDisk();
5570 size = aDataset->GetSize();
5571 char* refFromFile = new char[ size ];
5572 aDataset->ReadFromDisk( refFromFile );
5573 aDataset->CloseOnDisk();
5574 if ( strlen( refFromFile ) > 0 ) {
5575 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5576 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5577 if ( !CORBA::is_nil( shapeObject ) ) {
5578 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5579 if ( !aShapeObject->_is_nil() )
5580 myNewMeshImpl->SetShape( aShapeObject );
5583 delete [] refFromFile;
5586 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5587 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5589 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5590 aDataset->OpenOnDisk();
5591 size = aDataset->GetSize();
5592 int* meshPersistentId = new int[ size ];
5593 aDataset->ReadFromDisk( meshPersistentId );
5594 aDataset->CloseOnDisk();
5595 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5596 delete [] meshPersistentId;
5599 // Restore SMESH_Mesh_i::_mainShapeTick
5600 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5602 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5603 aDataset->OpenOnDisk();
5604 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5605 aDataset->ReadFromDisk( shapeTick );
5606 aDataset->CloseOnDisk();
5609 // Restore file info
5610 if ( aTopGroup->ExistInternalObject( "file info" ))
5612 aDataset = new HDFdataset( "file info", aTopGroup );
5613 aDataset->OpenOnDisk();
5614 size = aDataset->GetSize();
5615 std::string info( size, ' ');
5616 aDataset->ReadFromDisk( (char*) info.data() );
5617 aDataset->CloseOnDisk();
5618 myNewMeshImpl->FileInfoFromString( info );
5624 // As all objects that can be referred by hypothesis are created,
5625 // we can restore hypothesis data
5627 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5628 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5630 SMESH_Hypothesis_i* hyp = hyp_data->first;
5631 string & data = hyp_data->second;
5632 hyp->LoadFrom( data.c_str() );
5635 // Restore the rest mesh data
5637 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5638 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5640 aTopGroup = meshi_group->second;
5641 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5643 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5644 bool hasData = false;
5647 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5648 int newId = myStudyContext->findId( iorString.in() );
5649 int meshOldId = myStudyContext->getOldId( newId );
5651 // try to find mesh data dataset
5652 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5653 // load mesh "has data" flag
5654 aDataset = new HDFdataset( "Has data", aTopGroup );
5655 aDataset->OpenOnDisk();
5656 size = aDataset->GetSize();
5657 char* strHasData = new char[ size ];
5658 aDataset->ReadFromDisk( strHasData );
5659 aDataset->CloseOnDisk();
5660 if ( strcmp( strHasData, "1") == 0 ) {
5663 delete [] strHasData;
5666 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5667 // nodes and elements are not yet put into sub-meshes)
5668 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5669 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5670 aGroup->OpenOnDisk();
5671 // get number of applied algorithms
5672 int aNbSubObjects = aGroup->nInternalObjects();
5673 MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5674 for ( int j = 0; j < aNbSubObjects; j++ ) {
5675 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5676 aGroup->InternalObjectIndentify( j, name_dataset );
5677 // check if it is an algorithm
5678 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5679 aDataset = new HDFdataset( name_dataset, aGroup );
5680 aDataset->OpenOnDisk();
5681 size = aDataset->GetSize();
5682 char* refFromFile = new char[ size ];
5683 aDataset->ReadFromDisk( refFromFile );
5684 aDataset->CloseOnDisk();
5685 // san - it is impossible to recover applied algorithms using their entries within Load() method
5686 int id = atoi( refFromFile );
5687 delete [] refFromFile;
5688 string anIOR = myStudyContext->getIORbyOldId( id );
5689 if ( !anIOR.empty() ) {
5690 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5691 if ( !CORBA::is_nil( hypObject ) ) {
5692 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5693 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5694 || !myNewMeshImpl->HasShapeToMesh()) )
5695 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5700 aGroup->CloseOnDisk();
5703 // try to get applied hypotheses
5704 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5705 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5706 aGroup->OpenOnDisk();
5707 // get number of applied hypotheses
5708 int aNbSubObjects = aGroup->nInternalObjects();
5709 for ( int j = 0; j < aNbSubObjects; j++ ) {
5710 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5711 aGroup->InternalObjectIndentify( j, name_dataset );
5712 // check if it is a hypothesis
5713 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5714 aDataset = new HDFdataset( name_dataset, aGroup );
5715 aDataset->OpenOnDisk();
5716 size = aDataset->GetSize();
5717 char* refFromFile = new char[ size ];
5718 aDataset->ReadFromDisk( refFromFile );
5719 aDataset->CloseOnDisk();
5720 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5721 int id = atoi( refFromFile );
5722 delete [] refFromFile;
5723 string anIOR = myStudyContext->getIORbyOldId( id );
5724 if ( !anIOR.empty() ) {
5725 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5726 if ( !CORBA::is_nil( hypObject ) ) {
5727 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5728 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5729 || !myNewMeshImpl->HasShapeToMesh()) )
5730 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5735 aGroup->CloseOnDisk();
5738 // --> try to find SUB-MESHES containers for each type of submesh
5739 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5740 const char* name_meshgroup = 0;
5741 if ( j == GetSubMeshOnVertexTag() )
5742 name_meshgroup = "SubMeshes On Vertex";
5743 else if ( j == GetSubMeshOnEdgeTag() )
5744 name_meshgroup = "SubMeshes On Edge";
5745 else if ( j == GetSubMeshOnWireTag() )
5746 name_meshgroup = "SubMeshes On Wire";
5747 else if ( j == GetSubMeshOnFaceTag() )
5748 name_meshgroup = "SubMeshes On Face";
5749 else if ( j == GetSubMeshOnShellTag() )
5750 name_meshgroup = "SubMeshes On Shell";
5751 else if ( j == GetSubMeshOnSolidTag() )
5752 name_meshgroup = "SubMeshes On Solid";
5753 else if ( j == GetSubMeshOnCompoundTag() )
5754 name_meshgroup = "SubMeshes On Compound";
5756 // try to get submeshes container HDF group
5757 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5758 // open submeshes containers HDF group
5759 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5760 aGroup->OpenOnDisk();
5762 // get number of submeshes
5763 int aNbSubMeshes = aGroup->nInternalObjects();
5764 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5766 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5767 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5768 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5769 // --> get submesh id
5770 int subid = atoi( name_submeshgroup + 7 );
5773 // open submesh HDF group
5774 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5775 aSubGroup->OpenOnDisk();
5777 // try to read and set reference to subshape
5778 GEOM::GEOM_Object_var aSubShapeObject;
5779 SMESH::SMESH_subMesh_var aSubMesh;
5781 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5782 // load submesh "Ref on shape" - it's an entry to SObject
5783 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5784 aDataset->OpenOnDisk();
5785 size = aDataset->GetSize();
5786 char* refFromFile = new char[ size ];
5787 aDataset->ReadFromDisk( refFromFile );
5788 aDataset->CloseOnDisk();
5789 if ( strlen( refFromFile ) > 0 ) {
5790 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5791 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5792 if ( !CORBA::is_nil( subShapeObject ) ) {
5793 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5794 if ( !aSubShapeObject->_is_nil() )
5795 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5796 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5797 if ( aSubMesh->_is_nil() )
5799 string iorSubString = GetORB()->object_to_string( aSubMesh );
5800 int newSubId = myStudyContext->findId( iorSubString );
5801 myStudyContext->mapOldToNew( subid, newSubId );
5804 delete [] refFromFile;
5807 if ( aSubMesh->_is_nil() )
5810 // try to get applied algorithms
5811 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5812 // open "applied algorithms" HDF group
5813 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5814 aSubSubGroup->OpenOnDisk();
5815 // get number of applied algorithms
5816 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5817 for ( int l = 0; l < aNbSubObjects; l++ ) {
5818 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5819 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5820 // check if it is an algorithm
5821 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5822 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5823 aDataset->OpenOnDisk();
5824 size = aDataset->GetSize();
5825 char* refFromFile = new char[ size ];
5826 aDataset->ReadFromDisk( refFromFile );
5827 aDataset->CloseOnDisk();
5829 int id = atoi( refFromFile );
5830 string anIOR = myStudyContext->getIORbyOldId( id );
5831 if ( !anIOR.empty() ) {
5832 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5833 if ( !CORBA::is_nil( hypObject ) ) {
5834 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5835 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5836 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5839 delete [] refFromFile;
5842 // close "applied algorithms" HDF group
5843 aSubSubGroup->CloseOnDisk();
5846 // try to get applied hypotheses
5847 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5848 // open "applied hypotheses" HDF group
5849 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5850 aSubSubGroup->OpenOnDisk();
5851 // get number of applied hypotheses
5852 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5853 for ( int l = 0; l < aNbSubObjects; l++ ) {
5854 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5855 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5856 // check if it is a hypothesis
5857 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5858 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5859 aDataset->OpenOnDisk();
5860 size = aDataset->GetSize();
5861 char* refFromFile = new char[ size ];
5862 aDataset->ReadFromDisk( refFromFile );
5863 aDataset->CloseOnDisk();
5865 int id = atoi( refFromFile );
5866 string anIOR = myStudyContext->getIORbyOldId( id );
5867 if ( !anIOR.empty() ) {
5868 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5869 if ( !CORBA::is_nil( hypObject ) ) {
5870 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5871 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5872 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5875 delete [] refFromFile;
5878 // close "APPLIED HYPOTHESES" hdf group
5879 aSubSubGroup->CloseOnDisk();
5882 // close SUB-MESH hdf group
5883 aSubGroup->CloseOnDisk();
5886 // close SUB-MESHES containers hdf group
5887 aGroup->CloseOnDisk();
5891 // try to get GROUPS
5892 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5893 char name_group[ 30 ];
5894 if ( ii == GetNodeGroupsTag() )
5895 strcpy( name_group, "Groups of Nodes" );
5896 else if ( ii == GetEdgeGroupsTag() )
5897 strcpy( name_group, "Groups of Edges" );
5898 else if ( ii == GetFaceGroupsTag() )
5899 strcpy( name_group, "Groups of Faces" );
5900 else if ( ii == GetVolumeGroupsTag() )
5901 strcpy( name_group, "Groups of Volumes" );
5902 else if ( ii == Get0DElementsGroupsTag() )
5903 strcpy( name_group, "Groups of 0D Elements" );
5904 else if ( ii == GetBallElementsGroupsTag() )
5905 strcpy( name_group, "Groups of Balls" );
5907 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5908 aGroup = new HDFgroup( name_group, aTopGroup );
5909 aGroup->OpenOnDisk();
5910 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5911 // within aGroup->ExistInternalObject( name )
5912 std::vector< std::string > subNames;
5913 TColStd_MapOfAsciiString mapOfNames;
5914 aGroup->GetAllObjects( subNames );
5915 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5916 mapOfNames.Add( subNames[ iN ].c_str() );
5918 for ( size_t j = 0; j < subNames.size(); j++ ) {
5919 const std::string& name_dataset = subNames[ j ];
5920 // check if it is a group
5921 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5924 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5927 int groupID = -1; // group local ID (also persistent)
5929 groupID = atoi( endptr + 1 );
5930 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5931 aDataset->OpenOnDisk();
5933 // Retrieve actual group name
5934 size = aDataset->GetSize();
5935 char* nameFromFile = new char[ size ];
5936 aDataset->ReadFromDisk( nameFromFile );
5937 aDataset->CloseOnDisk();
5939 // Try to find a shape reference
5940 TopoDS_Shape aShape;
5941 char aRefName[ 30 ];
5942 sprintf( aRefName, "Ref on shape %d", subid);
5943 if ( mapOfNames.Contains( aRefName ))
5945 // load mesh "Ref on shape" - it's an entry to SObject
5946 aDataset = new HDFdataset( aRefName, aGroup );
5947 aDataset->OpenOnDisk();
5948 size = aDataset->GetSize();
5949 char* refFromFile = new char[ size ];
5950 aDataset->ReadFromDisk( refFromFile );
5951 aDataset->CloseOnDisk();
5952 if ( strlen( refFromFile ) > 0 ) {
5953 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5954 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5955 if ( !CORBA::is_nil( shapeObject ) ) {
5956 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5957 if ( !aShapeObject->_is_nil() )
5958 aShape = GeomObjectToShape( aShapeObject );
5961 delete [] refFromFile;
5963 // Try to read a filter of SMESH_GroupOnFilter
5964 SMESH::Filter_var filter;
5965 SMESH_PredicatePtr predicate;
5966 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5967 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5969 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5970 aDataset->OpenOnDisk();
5971 size = aDataset->GetSize();
5972 char* persistStr = new char[ size ];
5973 aDataset->ReadFromDisk( persistStr );
5974 aDataset->CloseOnDisk();
5975 if ( strlen( persistStr ) > 0 ) {
5976 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5977 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5978 filters.push_back( filter );
5980 delete [] persistStr;
5983 // Create group servant
5984 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5985 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5986 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5987 delete [] nameFromFile;
5988 // Obtain a SMESHDS_Group object
5989 if ( aNewGroup->_is_nil() )
5992 CORBA::String_var iorSubStringVar = GetORB()->object_to_string( aNewGroup );
5993 string iorSubString(iorSubStringVar.in());
5994 int newSubId = myStudyContext->findId( iorSubString );
5995 myStudyContext->mapOldToNew( subid, newSubId );
5997 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
6001 if ( SMESH_GroupOnFilter_i* aFilterGroup =
6002 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
6004 aFilterGroup->SetFilter( filter );
6005 filter->UnRegister();
6007 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
6008 if ( !aGroupBaseDS )
6011 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
6014 // Read color of the group
6015 char aGroupColorName[ 30 ];
6016 sprintf( aGroupColorName, "ColorGroup %d", subid);
6017 if ( mapOfNames.Contains( aGroupColorName ))
6019 aDataset = new HDFdataset( aGroupColorName, aGroup );
6020 aDataset->OpenOnDisk();
6021 size = aDataset->GetSize();
6022 double* anRGB = new double[ size ];
6023 aDataset->ReadFromDisk( anRGB );
6024 aDataset->CloseOnDisk();
6025 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
6026 aGroupBaseDS->SetColor( aColor );
6031 aGroup->CloseOnDisk();
6035 // instead of reading mesh data, we read only brief information of all
6036 // objects: mesh, groups, sub-meshes (issue 0021208)
6039 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
6040 meshfile.ToCString(), filename.ToCString(),
6044 // read Sub-Mesh ORDER if any
6045 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
6046 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
6047 aDataset->OpenOnDisk();
6048 size = aDataset->GetSize();
6049 int* smIDs = new int[ size ];
6050 aDataset->ReadFromDisk( smIDs );
6051 aDataset->CloseOnDisk();
6052 TListOfListOfInt anOrderIds;
6053 anOrderIds.push_back( TListOfInt() );
6054 for ( int i = 0; i < size; i++ )
6055 if ( smIDs[ i ] < 0 ) // is separator
6056 anOrderIds.push_back( TListOfInt() );
6058 anOrderIds.back().push_back(smIDs[ i ]);
6060 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6063 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
6065 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
6066 aDataset->OpenOnDisk();
6067 size = aDataset->GetSize();
6068 std::string dataString; dataString.resize( size );
6069 aDataset->ReadFromDisk((char*) dataString.data() );
6070 aDataset->CloseOnDisk();
6072 std::list< std::list< std::string > > orderEntryLists;
6073 SMESHUtils::BoostTxtArchive( dataString ) >> orderEntryLists;
6075 TListOfListOfInt anOrderIds;
6076 for ( const std::list< std::string >& entryList : orderEntryLists )
6078 anOrderIds.emplace_back();
6079 for ( const std::string & entry : entryList )
6081 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6082 TopoDS_Shape shape = GeomObjectToShape( go );
6083 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6084 anOrderIds.back().emplace_back( sm->GetId() );
6087 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6091 // update hyps needing full mesh data restored (issue 20918)
6092 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6094 SMESH_Hypothesis_i* hyp = hyp_data->first;
6095 hyp->UpdateAsMeshesRestored();
6098 // notify algos on completed restoration to set sub-mesh event listeners
6099 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6101 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6102 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6104 TopoDS_Shape myLocShape;
6105 if(myLocMesh.HasShapeToMesh())
6106 myLocShape = myLocMesh.GetShapeToMesh();
6108 myLocShape = SMESH_Mesh::PseudoShape();
6110 myLocMesh.GetSubMesh(myLocShape)->
6111 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6114 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6115 list< SMESH::Filter_var >::iterator f = filters.begin();
6116 for ( ; f != filters.end(); ++f )
6117 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6118 fi->FindBaseObjects();
6123 aTopGroup->CloseOnDisk();
6126 aFile->CloseOnDisk();
6129 // Remove temporary files created from the stream
6132 SMESH_File meshFile( meshfile.ToCString() );
6133 if ( !meshFile ) // no meshfile exists
6135 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6139 Engines::Container_var container = GetContainerRef();
6140 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6142 container_i->registerTemporaryFile( filename.ToCString() );
6143 container_i->registerTemporaryFile( meshfile.ToCString() );
6144 container_i->registerTemporaryFile( tmpDir.ToCString() );
6149 // creation of tree nodes for all data objects in the study
6150 // to support tree representation customization and drag-n-drop:
6151 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6152 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6153 useCaseBuilder->SetRootCurrent();
6154 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6155 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6156 for (it->InitEx(true); it->More(); it->Next()) {
6157 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6164 //=============================================================================
6166 * SMESH_Gen_i::LoadASCII
6168 * Load SMESH module's data in ASCII format
6170 //=============================================================================
6172 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6173 const SALOMEDS::TMPFile& theStream,
6175 bool isMultiFile ) {
6176 MESSAGE( "SMESH_Gen_i::LoadASCII" );
6177 return Load( theComponent, theStream, theURL, isMultiFile );
6179 //before call main ::Load method it's need for decipher text format to
6180 //binary ( "|xx" => x' )
6181 int size = theStream.length();
6182 if ( int((size / 3 )*3) != size ) //error size of buffer
6185 int real_size = int(size / 3);
6187 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6190 unsigned int c = -1;
6191 for ( int i = 0; i < real_size; i++ )
6193 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6194 sscanf( tmp, "%x", &c );
6195 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6198 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6200 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6203 //=============================================================================
6205 * SMESH_Gen_i::Close
6207 * Clears study-connected data when it is closed
6209 //=============================================================================
6211 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6213 MESSAGE( "SMESH_Gen_i::Close" );
6215 // Clear study contexts data
6216 myStudyContext->Clear();
6218 // remove the tmp files meshes are loaded from
6219 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6221 // Clean trace of API methods calls
6227 //=============================================================================
6229 * SMESH_Gen_i::ComponentDataType
6231 * Get component data type
6233 //=============================================================================
6235 char* SMESH_Gen_i::ComponentDataType()
6237 MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6238 return CORBA::string_dup( "SMESH" );
6242 //=============================================================================
6244 * SMESH_Gen_i::IORToLocalPersistentID
6246 * Transform data from transient form to persistent
6248 //=============================================================================
6250 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6251 const char* IORString,
6252 CORBA::Boolean /*isMultiFile*/,
6253 CORBA::Boolean /*isASCII*/ )
6255 MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6257 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6258 int anId = myStudyContext->findId( IORString );
6260 MESSAGE( "VSR " << anId );
6262 sprintf( strId, "%d", anId );
6263 return CORBA::string_dup( strId );
6266 return CORBA::string_dup( "" );
6269 //=============================================================================
6271 * SMESH_Gen_i::LocalPersistentIDToIOR
6273 * Transform data from persistent form to transient
6275 //=============================================================================
6277 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6278 const char* aLocalPersistentID,
6279 CORBA::Boolean /*isMultiFile*/,
6280 CORBA::Boolean /*isASCII*/ )
6282 MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6284 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6285 int anId = atoi( aLocalPersistentID );
6286 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6288 return CORBA::string_dup( "" );
6291 //=======================================================================
6292 //function : RegisterObject
6294 //=======================================================================
6296 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6298 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6299 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6300 return myStudyContext->addObject( string( iorString.in() ) );
6305 //================================================================================
6307 * \brief Return id of registered object
6308 * \param theObject - the Object
6309 * \retval int - Object id
6311 //================================================================================
6313 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6315 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6316 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6317 string iorStringCpp(iorString.in());
6318 return myStudyContext->findId( iorStringCpp );
6323 //=============================================================================
6325 * SMESH_Gen_i::SetName
6327 * Set a new object name
6329 //=============================================================================
6331 void SMESH_Gen_i::SetName(const char* theIOR,
6332 const char* theName)
6334 if ( theIOR && strcmp( theIOR, "" ) ) {
6335 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6336 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6337 if ( !aSO->_is_nil() ) {
6338 SetName( aSO, theName );
6343 // Version information
6344 char* SMESH_Gen_i::getVersion()
6346 #if SMESH_DEVELOPMENT
6347 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6349 return CORBA::string_dup(SMESH_VERSION_STR);
6353 //=================================================================================
6354 // function : Move()
6355 // purpose : Moves objects to the specified position.
6356 // Is used in the drag-n-drop functionality.
6357 //=================================================================================
6359 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6360 SALOMEDS::SObject_ptr where,
6363 if ( CORBA::is_nil( where ) ) return;
6365 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6366 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6367 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6368 std::string dataType = father->ComponentDataType();
6369 if ( dataType != "SMESH" ) return; // not a SMESH component
6371 SALOMEDS::SObject_var objAfter;
6372 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6373 // insert at given row -> find insertion position
6374 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6376 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6377 if ( i == row && useCaseIt->More() ) {
6378 objAfter = useCaseIt->Value();
6382 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6383 SALOMEDS::SObject_var sobj = what[i];
6384 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6385 // insert the object to the use case tree
6386 if ( !CORBA::is_nil( objAfter ) )
6387 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6389 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6393 //================================================================================
6395 * \brief Collect indices of elements, which are located inside the sphere
6397 //================================================================================
6399 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6400 SMESH::ElementType theElemType,
6406 SMESH::long_array_var aResult = new SMESH::long_array();
6407 if ( meshPart->_is_nil() )
6408 return aResult._retn();
6410 // 1. Create geometrical object
6411 gp_Pnt aP( theX, theY, theZ );
6412 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6414 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6416 if ( lst.size() > 0 ) {
6417 aResult->length( lst.size() );
6418 for ( size_t i = 0; i < lst.size(); i++ ) {
6419 aResult[i] = lst[i];
6422 return aResult._retn();
6425 //================================================================================
6427 * \brief Collect indices of elements, which are located inside the box
6429 //================================================================================
6431 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6432 SMESH::ElementType theElemType,
6433 CORBA::Double theX1,
6434 CORBA::Double theY1,
6435 CORBA::Double theZ1,
6436 CORBA::Double theX2,
6437 CORBA::Double theY2,
6438 CORBA::Double theZ2)
6440 SMESH::long_array_var aResult = new SMESH::long_array();
6441 if( meshPart->_is_nil() )
6442 return aResult._retn();
6444 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6445 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6447 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6449 if( lst.size() > 0 ) {
6450 aResult->length( lst.size() );
6451 for ( size_t i = 0; i < lst.size(); i++ ) {
6452 aResult[i] = lst[i];
6455 return aResult._retn();
6458 //================================================================================
6460 * \brief Collect indices of elements, which are located inside the cylinder
6462 //================================================================================
6464 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6465 SMESH::ElementType theElemType,
6469 CORBA::Double theDX,
6470 CORBA::Double theDY,
6471 CORBA::Double theDZ,
6473 CORBA::Double theR )
6475 SMESH::long_array_var aResult = new SMESH::long_array();
6476 if( meshPart->_is_nil() )
6477 return aResult._retn();
6479 gp_Pnt aP( theX, theY, theZ );
6480 gp_Vec aV( theDX, theDY, theDZ );
6481 gp_Ax2 anAxes (aP, aV);
6483 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6485 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6487 if( lst.size() > 0 ) {
6488 aResult->length( lst.size() );
6489 for ( size_t i = 0; i < lst.size(); i++ ) {
6490 aResult[i] = lst[i];
6493 return aResult._retn();
6496 //================================================================================
6498 * \brief Collect indices of elements, which are located inside the geom object
6500 //================================================================================
6502 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6503 SMESH::ElementType theElemType,
6504 GEOM::GEOM_Object_ptr theGeom,
6505 CORBA::Double theTolerance )
6507 SMESH::long_array_var aResult = new SMESH::long_array();
6508 if( meshPart->_is_nil() || theGeom->_is_nil() )
6509 return aResult._retn();
6511 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6513 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6515 if( lst.size() > 0 ) {
6516 aResult->length( lst.size() );
6517 for ( size_t i = 0; i < lst.size(); i++ ) {
6518 aResult[i] = lst[i];
6521 return aResult._retn();
6524 //================================================================================
6526 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6528 //================================================================================
6530 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6531 SMESH::ElementType theElemType,
6532 const TopoDS_Shape& theShape,
6533 double* theTolerance) {
6535 std::vector<long> res;
6536 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6538 if ( mesh->_is_nil() )
6541 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6545 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6550 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6551 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6552 anElementsOnShape->SetAllNodes( true );
6553 anElementsOnShape->SetMesh( meshDS );
6554 anElementsOnShape->SetShape( theShape, aType );
6557 anElementsOnShape->SetTolerance(*theTolerance);
6559 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6560 if ( !msource->_is_nil() ) { // Mesh case
6561 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6563 while ( elemIt->more() ) {
6564 const SMDS_MeshElement* anElem = elemIt->next();
6565 long anId = anElem->GetID();
6566 if ( anElementsOnShape->IsSatisfy( anId ) )
6567 res.push_back( anId );
6571 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6572 if ( !gsource->_is_nil() ) {
6573 if(theElemType == SMESH::NODE) {
6574 SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6575 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6576 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6577 long anId = node->GetID();
6578 if ( anElementsOnShape->IsSatisfy( anId ) )
6579 res.push_back( anId );
6582 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6583 SMESH::smIdType_array_var elems = gsource->GetListOfID();
6584 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6585 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6586 long anId = elem->GetID();
6587 if ( anElementsOnShape->IsSatisfy( anId ) )
6588 res.push_back( anId );
6593 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6594 if ( !smsource->_is_nil() ) {
6595 SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6596 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6597 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6599 long anId = elem->GetID();
6600 if ( anElementsOnShape->IsSatisfy( anId ) )
6601 res.push_back( anId );
6608 //================================================================================
6610 * \brief Returns true if algorithm can be used to mesh a given geometry
6611 * \param [in] theAlgoType - the algorithm type
6612 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6613 * \param [in] theGeomObject - the geometry to mesh
6614 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6615 * else, returns \c True if at least one shape is meshable
6616 * \return CORBA::Boolean - can or can't
6618 //================================================================================
6620 #undef SMY_OWN_CATCH
6621 #define SMY_OWN_CATCH // prevent re-throwing SALOME::SALOME_Exception in IsApplicable()
6623 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6624 const char* theLibName,
6625 GEOM::GEOM_Object_ptr theGeomObject,
6626 CORBA::Boolean toCheckAll)
6630 std::string aPlatformLibName;
6631 GenericHypothesisCreator_i* aCreator =
6632 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6635 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6636 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6637 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6644 SMESH_CATCH( SMESH::doNothing );
6646 MESSAGE("SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : ""));