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
165 static int MYDEBUG = 0;
167 static int MYDEBUG = 0;
170 // Static variables definition
171 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
172 CORBA::ORB_var SMESH_Gen_i::myOrb;
173 PortableServer::POA_var SMESH_Gen_i::myPoa;
174 SALOME_NamingService_Abstract* SMESH_Gen_i::myNS = nullptr;
175 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = nullptr;
176 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = nullptr;
179 const int nbElemPerDiagonal = 10;
181 //=============================================================================
183 * GetServant [ static ]
185 * Get servant of the CORBA object
187 //=============================================================================
189 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
191 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
194 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
197 catch (PortableServer::POA::ObjectNotActive &ex)
199 MESSAGE("GetServant: ObjectNotActive");
202 catch (PortableServer::POA::WrongAdapter &ex)
204 MESSAGE("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
207 catch (PortableServer::POA::WrongPolicy &ex)
209 MESSAGE("GetServant: WrongPolicy");
214 MESSAGE( "GetServant - Unknown exception was caught!!!" );
219 //=============================================================================
221 * SObjectToObject [ static ]
223 * Get CORBA object corresponding to the SALOMEDS::SObject
225 //=============================================================================
227 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
229 SALOMEDS::GenericAttribute_wrap anAttr;
230 CORBA::Object_var anObj;
231 if ( !theSObject->_is_nil() ) {
233 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
234 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
235 CORBA::String_var aValue = anIOR->Value();
236 if( strcmp( aValue, "" ) != 0 )
237 anObj = GetORB()->string_to_object( aValue );
241 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
247 // Set Naming Service object
248 void SMESH_Gen_i::SetNS(SALOME_NamingService_Abstract *ns)
255 //=============================================================================
259 * Get SALOME_NamingService object
261 //=============================================================================
263 SALOME_NamingService_Abstract* SMESH_Gen_i::GetNS()
266 myNS = SINGLETON_<SALOME_NamingService>::Instance();
267 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
268 myNS->init_orb( GetORB() );
273 //=============================================================================
277 * Get SALOME_LifeCycleCORBA object
279 //=============================================================================
281 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
283 if ( myLCC == NULL ) {
284 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
289 //=============================================================================
291 * GetGeomEngine [ static ]
293 * Get GEOM::GEOM_Gen reference
295 //=============================================================================
297 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
299 GEOM::GEOM_Gen_ptr gen = GEOM::GEOM_Gen::_nil();
300 if ( !CORBA::is_nil( go ))
305 //=============================================================================
307 * SMESH_Gen_i::SMESH_Gen_i
309 * Default constructor: not for use
311 //=============================================================================
313 SMESH_Gen_i::SMESH_Gen_i()
317 //=============================================================================
319 * SMESH_Gen_i::SMESH_Gen_i
321 * Standard constructor, used with Container
323 //=============================================================================
325 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
326 PortableServer::POA_ptr poa,
327 PortableServer::ObjectId* contId,
328 const char* instanceName,
329 const char* interfaceName,
331 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName, false, checkNS )
334 myOrb = CORBA::ORB::_duplicate(orb);
335 myPoa = PortableServer::POA::_duplicate(poa);
338 _id = myPoa->activate_object( _thisObj );
340 myStudyContext = new StudyContext;
342 myIsEmbeddedMode = false;
343 myIsEnablePublish = true;
344 myShapeReader = NULL; // shape reader
346 myIsHistoricalPythonDump = true;
347 myToForgetMeshDataOnHypModif = false;
349 // set it in standalone mode only
350 //OSD::SetSignal( true );
352 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
353 // find out mode (embedded or standalone) here else
354 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
355 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
358 if ( SALOME_NamingService_Abstract* ns = GetNS() )
360 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
361 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
362 if ( !session->_is_nil() )
364 CORBA::String_var str_host = session->getHostname();
365 CORBA::Long s_pid = session->getPID();
366 string my_host = Kernel_Utils::GetHostname();
368 long my_pid = (long)_getpid();
370 long my_pid = (long) getpid();
372 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
378 //=============================================================================
380 * SMESH_Gen_i::~SMESH_Gen_i
384 //=============================================================================
386 SMESH_Gen_i::~SMESH_Gen_i()
388 // delete hypothesis creators
389 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
390 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
392 // same creator can be mapped under different names
393 GenericHypothesisCreator_i* creator = (*itHyp).second;
397 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
398 if ( creator == (*itHyp2).second )
399 (*itHyp2).second = 0;
401 myHypCreatorMap.clear();
403 // Clear study contexts data
404 delete myStudyContext;
406 // delete shape reader
408 delete myShapeReader;
411 //=============================================================================
413 * SMESH_Gen_i::getHypothesisCreator
415 * Get hypothesis creator
417 //=============================================================================
419 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
420 const char* theLibName,
421 std::string& thePlatformLibName)
423 std::string aPlatformLibName;
424 /* It's Need to translate lib name for WIN32 or X platform */
425 if ( theLibName && theLibName[0] != '\0' )
427 int libNameLen = strlen(theLibName);
428 //check for old format "libXXXXXXX.so"
429 if (libNameLen > 7 &&
430 !strncmp( theLibName, "lib", 3 ) &&
431 !strcmp( theLibName+libNameLen-3, ".so" ))
435 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
436 #elif defined(__APPLE__)
437 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
439 aPlatformLibName = theLibName;
444 //try to use new format
446 aPlatformLibName = theLibName;
447 aPlatformLibName += ".dll";
448 #elif defined(__APPLE__)
449 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
451 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
455 thePlatformLibName = aPlatformLibName;
457 Unexpect aCatch(SALOME_SalomeException);
458 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
460 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
461 GenericHypothesisCreator_i* aCreator;
464 // check, if creator for this hypothesis type already exists
465 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
467 // load plugin library
468 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
471 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
472 SMESHUtils::ArrayDeleter<const wchar_t> deleter( path );
474 const char* path = aPlatformLibName.c_str();
477 const char* path = aPlatformLibName.c_str();
479 LibHandle libHandle = LoadLib( path );
483 // report any error, if occurred
485 const char* anError = dlerror();
486 throw(SALOME_Exception( anError ));
488 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
489 << aPlatformLibName));
493 // get method, returning hypothesis creator
494 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
495 GetHypothesisCreator procHandle =
496 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
499 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
500 << aPlatformLibName ));
501 UnLoadLib(libHandle);
504 // get hypothesis creator
505 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
506 aCreator = procHandle(theHypName);
509 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
510 << aPlatformLibName));
512 // map hypothesis creator to a hypothesis name
513 myHypCreatorMap[string(theHypName)] = aCreator;
518 return myHypCreatorMap[string(theHypName)];
521 catch (SALOME_Exception& S_ex)
523 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
528 //=============================================================================
530 * SMESH_Gen_i::createHypothesis
532 * Create hypothesis of given type
534 //=============================================================================
536 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
537 const char* theLibName)
539 SMESH_Hypothesis_i* myHypothesis_i = 0;
540 SMESH::SMESH_Hypothesis_var hypothesis_i;
541 std::string aPlatformLibName;
542 GenericHypothesisCreator_i* aCreator =
543 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
545 // create a new hypothesis object, store its ref. in studyContext
546 myHypothesis_i = aCreator->Create(myPoa, &myGen);
549 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
550 CORBA::String_var hypName = myHypothesis_i->GetName();
551 myHypCreatorMap[ hypName.in() ] = aCreator;
553 // activate the CORBA servant of hypothesis
554 hypothesis_i = myHypothesis_i->_this();
555 int nextId = RegisterObject( hypothesis_i );
556 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
557 else { (void)nextId; } // avoid "unused variable" warning in release mode
559 return hypothesis_i._retn();
562 //=============================================================================
564 * SMESH_Gen_i::createMesh
566 * Create empty mesh on shape
568 //=============================================================================
570 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
572 Unexpect aCatch(SALOME_SalomeException);
573 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
575 // Get or create the GEOM_Client instance
577 // create a new mesh object servant, store it in a map in study context
578 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
579 // create a new mesh object
580 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
581 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
583 // activate the CORBA servant of Mesh
584 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
585 int nextId = RegisterObject( mesh );
586 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
587 else { (void)nextId; } // avoid "unused variable" warning in release mode
590 catch (SALOME_Exception& S_ex) {
591 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
593 return SMESH::SMESH_Mesh::_nil();
596 //=============================================================================
598 * SMESH_Gen_i::GetShapeReader
602 //=============================================================================
604 GEOM_Client* SMESH_Gen_i::GetShapeReader()
606 // create shape reader if necessary
607 if ( !myShapeReader )
608 myShapeReader = new GEOM_Client(GetContainerRef());
609 ASSERT( myShapeReader );
610 return myShapeReader;
613 //=============================================================================
615 * SMESH_Gen_i::SetGeomEngine
617 * Set GEOM::GEOM_Gen reference
619 //=============================================================================
621 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
623 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
626 //=============================================================================
628 * SMESH_Gen_i::SetEmbeddedMode
632 //=============================================================================
634 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
636 myIsEmbeddedMode = theMode;
638 if ( !myIsEmbeddedMode ) {
639 //PAL10867: disable signals catching with "noexcepthandler" option
640 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
641 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
646 char* envDisableFPE = getenv("DISABLE_FPE");
647 if (envDisableFPE && atoi(envDisableFPE))
652 OSD::SetSignal( raiseFPE );
654 // else OSD::SetSignal() is called in GUI
658 //=============================================================================
660 * SMESH_Gen_i::IsEmbeddedMode
664 //=============================================================================
666 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
668 return myIsEmbeddedMode;
671 //=============================================================================
673 * SMESH_Gen_i::SetEnablePublish
675 * Set enable publishing in the study
677 //=============================================================================
679 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
681 myIsEnablePublish = theIsEnablePublish;
684 //=============================================================================
686 * SMESH_Gen_i::IsEnablePublish
688 * Check enable publishing
690 //=============================================================================
692 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
694 return myIsEnablePublish;
697 //=============================================================================
699 * SMESH_Gen_i::UpdateStudy
701 * Update study (needed at switching GEOM->SMESH)
703 //=============================================================================
705 void SMESH_Gen_i::UpdateStudy()
707 if ( !myStudyContext )
708 myStudyContext = new StudyContext;
710 SALOMEDS::Study_var aStudy = getStudyServant();
711 if ( !CORBA::is_nil( aStudy ) )
713 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
715 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
716 if( !GEOM_var->_is_nil() )
717 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
719 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
720 if( !GEOM_var->_is_nil() )
721 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
723 // NPAL16168, issue 0020210
724 // Let meshes update their data depending on GEOM groups that could change
725 CORBA::String_var compDataType = ComponentDataType();
726 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
727 if ( !me->_is_nil() ) {
728 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
729 for ( ; anIter->More(); anIter->Next() ) {
730 SALOMEDS::SObject_wrap so = anIter->Value();
731 CORBA::Object_var ior = SObjectToObject( so );
732 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
733 mesh->CheckGeomModif();
739 //================================================================================
741 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
743 //================================================================================
745 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
747 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
748 SALOMEDS::GenericAttribute_wrap attr;
749 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
751 SALOMEDS::AttributePixMap_wrap pm = attr;
752 CORBA::String_var ico = pm->GetPixMap();
753 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
758 //=================================================================================
759 // function : hasObjectInfo()
760 // purpose : shows if module provides information for its objects
761 //=================================================================================
763 bool SMESH_Gen_i::hasObjectInfo()
768 //=================================================================================
769 // function : getObjectInfo()
770 // purpose : returns an information for a given object by its entry
771 //=================================================================================
773 char* SMESH_Gen_i::getObjectInfo( const char* entry )
775 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
776 // for the rest, "module 'SMESH', ID=0:1:2:*"
780 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
781 CORBA::Object_var obj = SObjectToObject( so );
782 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
783 if ( isGeomModifIcon( mesh ))
785 txt << "The geometry was changed and the mesh needs to be recomputed";
790 CORBA::String_var compType = ComponentDataType();
791 txt << "module '" << compType << "', ID=" << entry;
793 return CORBA::string_dup( txt );
796 //=============================================================================
798 * SMESH_Gen_i::GetStudyContext
802 //=============================================================================
804 StudyContext* SMESH_Gen_i::GetStudyContext()
806 return myStudyContext;
809 //=============================================================================
811 * SMESH_Gen_i::CreateHypothesis
813 * Create hypothesis/algorithm of given type and publish it in the study
815 //=============================================================================
817 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
818 const char* theLibName )
820 Unexpect aCatch(SALOME_SalomeException);
821 // Create hypothesis/algorithm
822 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
824 // Publish hypothesis/algorithm in the study
825 if ( CanPublishInStudy( hyp ) ) {
826 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
827 if ( !aSO->_is_nil() ) {
828 // Update Python script
829 TPythonDump(this) << aSO << " = " << this << ".CreateHypothesis('"
830 << theHypName << "', '" << theLibName << "')";
837 //================================================================================
839 * \brief Return a hypothesis initialized by given average length.
840 * \param theHypType - hypothesis type name
841 * \param theLibName - plugin library name
842 * \param theAverageLength - average length
843 * \param theQuadDominated - is quad-dominated flag
844 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
846 //================================================================================
848 SMESH::SMESH_Hypothesis_ptr
849 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
850 const char* theLibName,
851 CORBA::Double theAverageLength,
852 CORBA::Boolean theQuadDominated)
854 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
855 theAverageLength, theQuadDominated };
857 SMESH::SMESH_Hypothesis_var hyp =
858 GetHypothesisParameterValues( theHypType, theLibName,
859 SMESH::SMESH_Mesh::_nil(),
860 GEOM::GEOM_Object::_nil(),
862 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
864 TPythonDump(this) << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
865 << theHypType << "', '"
866 << theLibName << "', "
867 << theAverageLength << ", "
868 << theQuadDominated << " )";
873 //================================================================================
875 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
876 * existing on the given geometry or to size of the geometry.
877 * \param theHypType - hypothesis type name
878 * \param theLibName - plugin library name
879 * \param theMesh - The mesh of interest
880 * \param theGeom - The shape to get parameter values from
881 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
882 * in a study and used to compute the mesh, or a temporary one created just to pass
885 //================================================================================
887 SMESH::SMESH_Hypothesis_ptr
888 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
889 const char* theLibName,
890 SMESH::SMESH_Mesh_ptr theMesh,
891 GEOM::GEOM_Object_ptr theGeom,
892 const SMESH::HypInitParams& theParams)
894 Unexpect aCatch(SALOME_SalomeException);
896 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
897 if ( byMesh && CORBA::is_nil( theMesh ) )
898 return SMESH::SMESH_Hypothesis::_nil();
899 if ( byMesh && CORBA::is_nil( theGeom ) )
900 return SMESH::SMESH_Hypothesis::_nil();
902 // -----------------------------------------------
903 // find hypothesis used to mesh theGeom
904 // -----------------------------------------------
906 // get mesh and shape
907 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
908 TopoDS_Shape shape = GeomObjectToShape( theGeom );
909 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
910 return SMESH::SMESH_Hypothesis::_nil();
911 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
913 // create a temporary hypothesis to know its dimension
914 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
915 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
917 return SMESH::SMESH_Hypothesis::_nil();
918 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
921 // look for a hypothesis of theHypType used to mesh the shape
922 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
925 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
926 int nbLocalHyps = aHypList->length();
927 for ( int i = 0; i < nbLocalHyps; i++ ) {
928 CORBA::String_var hypName = aHypList[i]->GetName();
929 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
930 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
932 // check super shapes
933 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
934 while ( nbLocalHyps == 0 && itShape.More() ) {
935 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
936 if ( ! CORBA::is_nil( geomObj )) {
937 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
938 nbLocalHyps = aHypList->length();
939 for ( int i = 0; i < nbLocalHyps; i++ )
940 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
941 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
947 // let the temporary hypothesis find out somehow parameter values by mesh
948 if ( hyp->SetParametersByMesh( mesh, shape ))
949 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
953 ::SMESH_Hypothesis::TDefaults dflts;
954 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
955 dflts._nbSegments = myGen.GetDefaultNbSegments();
956 dflts._elemLength = theParams.averageLength;
957 dflts._quadDominated = theParams.quadDominated;
958 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
961 dflts._diagonal = mesh->GetShapeDiagonalSize();
963 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
964 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
965 dflts._shape = &shape;
968 // let the hypothesis initialize it's values
969 if ( hyp->SetParametersByDefaults( dflts, mesh ))
970 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
973 return SMESH::SMESH_Hypothesis::_nil();
976 //=============================================================================
978 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
979 * \param [in] theHyp - the hypothesis of interest
980 * \param [out] theMesh - the sole mesh using \a theHyp
981 * \param [out] theShape - the sole geometry \a theHyp is assigned to
982 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
984 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
985 * considered as SAME sub-mesh => result is \c true.
986 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
987 * a shape to which an hyp being edited is assigned.
989 //=============================================================================
991 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
992 SMESH::SMESH_Mesh_out theMesh,
993 GEOM::GEOM_Object_out theShape)
995 if ( CORBA::is_nil( theHyp ))
998 // get Mesh component SO
999 CORBA::String_var compDataType = ComponentDataType();
1000 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
1001 if ( CORBA::is_nil( comp ))
1004 // look for child SO of meshes
1005 SMESH::SMESH_Mesh_var foundMesh;
1006 TopoDS_Shape foundShape;
1008 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1009 for ( ; meshIter->More() && isSole; meshIter->Next() )
1011 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1012 CORBA::Object_var obj = SObjectToObject( curSO );
1013 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1017 // look for a sole shape where theHyp is assigned
1018 bool isHypFound = false;
1019 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1020 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1021 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1023 const THypList& hyps = s2hypsIt.Value();
1024 THypList::const_iterator h = hyps.begin();
1025 for ( ; h != hyps.end(); ++h )
1026 if ( (*h)->GetID() == theHyp->GetId() )
1028 if ( h != hyps.end()) // theHyp found
1031 if ( ! foundShape.IsNull() &&
1032 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1034 foundShape.Nullify();
1038 foundShape = s2hypsIt.Key();
1040 } // loop on assigned hyps
1042 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1044 if ( !foundMesh->_is_nil() ) // not a sole mesh
1046 if ( !foundMesh->HasShapeToMesh() ||
1047 !mesh_i ->HasShapeToMesh() )
1049 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1053 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1054 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1055 isSole = s1->IsSame( s2 );
1058 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1064 ! foundMesh->_is_nil() &&
1065 ! foundShape.IsNull() )
1067 theMesh = foundMesh._retn();
1068 theShape = ShapeToGeomObject( foundShape );
1069 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1074 //=============================================================================
1076 * Set number of segments per diagonal of boundary box of geometry by which
1077 * default segment length of appropriate 1D hypotheses is defined
1079 //=============================================================================
1081 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1083 if ( theNbSegments > 0 )
1084 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1086 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1089 //=============================================================================
1091 * \brief Set default number of segments per edge
1093 //=============================================================================
1095 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1097 if ( theNbSegments > 0 )
1098 myGen.SetDefaultNbSegments( int(theNbSegments) );
1100 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1103 //=============================================================================
1105 * Set an option value
1107 //=============================================================================
1109 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1111 if ( name && value && strlen( value ) > 0 )
1114 if ( strcmp(name, "historical_python_dump") == 0 )
1116 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1117 msgToGUI = "preferences/SMESH/historical_python_dump/";
1118 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1120 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1122 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1123 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1124 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1126 else if ( strcmp(name, "default_grp_color") == 0 )
1130 // color must be presented as a string of following form:
1131 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1132 str = str.substr(1);
1133 for ( size_t i = 0; i < str.length()/2; i++ )
1134 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1135 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1137 else if ( value ) { // rgb color ("255,170,0", for example)
1138 string tempValue( value );
1139 char* colorValue = strtok( &tempValue[0], "," );
1140 while ( colorValue != NULL ) {
1141 int c_value = atoi( colorValue );
1142 if ( c_value >= 0 && c_value <= 255 )
1143 color.push_back( c_value );
1144 colorValue = strtok( NULL, "," );
1147 if ( color.size() == 3 ) { // color must have three valid component
1148 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1149 myDefaultGroupColor = value;
1150 msgToGUI = "preferences/SMESH/default_grp_color/";
1155 // update preferences in case if SetOption() is invoked from python console
1156 if ( !msgToGUI.empty() )
1158 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1159 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1160 if ( !CORBA::is_nil( session ) )
1161 session->emitMessageOneWay(msgToGUI.c_str());
1166 //=============================================================================
1168 * Return an option value
1170 //=============================================================================
1172 char* SMESH_Gen_i::GetOption(const char* name)
1176 if ( strcmp(name, "historical_python_dump") == 0 )
1178 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1180 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1182 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1184 if ( strcmp(name, "default_grp_color") == 0 )
1186 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1189 return CORBA::string_dup( "" );
1192 //=============================================================================
1194 * SMESH_Gen_i::CreateMesh
1196 * Create empty mesh on a shape and publish it in the study
1198 //=============================================================================
1200 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1202 Unexpect aCatch(SALOME_SalomeException);
1203 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1205 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1207 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1208 ASSERT( meshServant );
1209 meshServant->SetShape( theShapeObject );
1211 // publish mesh in the study
1212 if ( CanPublishInStudy( mesh ) ) {
1213 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1214 aStudyBuilder->NewCommand(); // There is a transaction
1215 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1216 aStudyBuilder->CommitCommand();
1217 if ( !aSO->_is_nil() ) {
1218 // Update Python script
1219 TPythonDump(this) << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1223 return mesh._retn();
1226 //=============================================================================
1228 * SMESH_Gen_i::CreateEmptyMesh
1232 //=============================================================================
1234 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1236 Unexpect aCatch(SALOME_SalomeException);
1237 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1239 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1241 // publish mesh in the study
1242 if ( CanPublishInStudy( mesh ) ) {
1243 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1244 aStudyBuilder->NewCommand(); // There is a transaction
1245 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1246 aStudyBuilder->CommitCommand();
1247 if ( !aSO->_is_nil() ) {
1248 // Update Python script
1249 TPythonDump(this) << aSO << " = " << this << ".CreateEmptyMesh()";
1253 return mesh._retn();
1258 //================================================================================
1260 * \brief Throw an exception in case if the file can't be read
1262 //================================================================================
1264 void checkFileReadable( const char* theFileName )
1266 SMESH_File f ( theFileName );
1269 if ( !f.error().empty() )
1270 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1272 THROW_SALOME_CORBA_EXCEPTION
1273 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1274 SALOME::BAD_PARAM );
1279 //=============================================================================
1281 * SMESH_Gen_i::CreateMeshFromUNV
1283 * Create mesh and import data from UNV file
1285 //=============================================================================
1287 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1289 Unexpect aCatch(SALOME_SalomeException);
1291 checkFileReadable( theFileName );
1293 SMESH::SMESH_Mesh_var aMesh = createMesh();
1295 // publish mesh in the study
1296 if ( CanPublishInStudy( aMesh ) ) {
1297 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1298 aStudyBuilder->NewCommand(); // There is a transaction
1299 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1300 aStudyBuilder->CommitCommand();
1301 if ( !aSO->_is_nil() ) {
1302 // Update Python script
1303 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1307 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1309 aServant->ImportUNVFile( theFileName );
1311 // Dump creation of groups
1312 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1314 aServant->GetImpl().GetMeshDS()->Modified();
1315 return aMesh._retn();
1318 //=============================================================================
1320 * SMESH_Gen_i::CreateMeshFromMED
1322 * Create mesh and import data from MED file
1324 //=============================================================================
1326 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1327 SMESH::DriverMED_ReadStatus& theStatus )
1329 checkFileReadable( theFileName );
1332 char bname[ _MAX_FNAME ];
1333 _splitpath( theFileName, NULL, NULL, bname, NULL );
1334 string aFileName = bname;
1336 string aFileName = basename( const_cast<char *>( theFileName ));
1338 // Retrieve mesh names from the file
1339 DriverMED_R_SMESHDS_Mesh myReader;
1340 myReader.SetFile( theFileName );
1341 myReader.SetMeshId( -1 );
1342 Driver_Mesh::Status aStatus;
1343 list<string> aNames = myReader.GetMeshNames(aStatus);
1344 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1345 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1347 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1350 TPythonDump aPythonDump(this);
1351 aPythonDump << "([";
1353 if (theStatus == SMESH::DRS_OK)
1355 SALOMEDS::StudyBuilder_var aStudyBuilder;
1356 aStudyBuilder = getStudyServant()->NewBuilder();
1357 aStudyBuilder->NewCommand(); // There is a transaction
1359 aResult->length( aNames.size() );
1362 // Iterate through all meshes and create mesh objects
1363 for ( const std::string & meshName : aNames )
1366 if (i > 0) aPythonDump << ", ";
1369 SMESH::SMESH_Mesh_var mesh = createMesh();
1371 // publish mesh in the study
1372 SALOMEDS::SObject_wrap aSO;
1373 if ( CanPublishInStudy( mesh ) )
1374 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1377 if ( !aSO->_is_nil() ) {
1380 aPythonDump << "mesh_" << i;
1383 // Read mesh data (groups are published automatically by ImportMEDFile())
1384 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1385 ASSERT( meshServant );
1386 SMESH::DriverMED_ReadStatus status1 =
1387 meshServant->ImportMEDFile( theFileName, meshName.c_str() );
1388 if (status1 > theStatus)
1389 theStatus = status1;
1391 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1392 meshServant->GetImpl().GetMeshDS()->Modified();
1394 if ( !aStudyBuilder->_is_nil() )
1395 aStudyBuilder->CommitCommand();
1398 // Update Python script
1399 aPythonDump << "], status) = " << this << ".CreateMeshesFromMED( r'" << theFileName << "' )";
1401 // Dump creation of groups
1402 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1403 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1405 return aResult._retn();
1408 //=============================================================================
1410 * SMESH_Gen_i::CreateMeshFromSTL
1412 * Create mesh and import data from STL file
1414 //=============================================================================
1416 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1418 Unexpect aCatch(SALOME_SalomeException);
1419 checkFileReadable( theFileName );
1421 SMESH::SMESH_Mesh_var aMesh = createMesh();
1424 char bname[ _MAX_FNAME ];
1425 _splitpath( theFileName, NULL, NULL, bname, NULL );
1426 string aFileName = bname;
1428 string aFileName = basename( const_cast<char *>(theFileName) );
1430 // publish mesh in the study
1431 if ( CanPublishInStudy( aMesh ) ) {
1432 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1433 aStudyBuilder->NewCommand(); // There is a transaction
1434 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1435 aStudyBuilder->CommitCommand();
1436 if ( !aSO->_is_nil() ) {
1437 // Update Python script
1438 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1442 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1444 aServant->ImportSTLFile( theFileName );
1445 aServant->GetImpl().GetMeshDS()->Modified();
1446 return aMesh._retn();
1449 //================================================================================
1451 * \brief Create meshes and import data from the CGSN file
1453 //================================================================================
1455 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1456 SMESH::DriverMED_ReadStatus& theStatus)
1458 Unexpect aCatch(SALOME_SalomeException);
1459 checkFileReadable( theFileName );
1461 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1464 // Retrieve nb meshes from the file
1465 DriverCGNS_Read myReader;
1466 myReader.SetFile( theFileName );
1467 Driver_Mesh::Status aStatus;
1468 int nbMeshes = myReader.GetNbMeshes(aStatus);
1469 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1471 aResult->length( nbMeshes );
1473 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1476 TPythonDump aPythonDump(this);
1477 aPythonDump << "([";
1479 if (theStatus == SMESH::DRS_OK)
1481 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1482 aStudyBuilder->NewCommand(); // There is a transaction
1486 // Iterate through all meshes and create mesh objects
1487 for ( ; i < nbMeshes; ++i )
1490 if (i > 0) aPythonDump << ", ";
1493 SMESH::SMESH_Mesh_var mesh = createMesh();
1494 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1496 // Read mesh data (groups are published automatically by ImportMEDFile())
1497 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1498 ASSERT( meshServant );
1500 SMESH::DriverMED_ReadStatus status1 =
1501 meshServant->ImportCGNSFile( theFileName, i, meshName );
1502 if (status1 > theStatus)
1503 theStatus = status1;
1505 meshServant->GetImpl().GetMeshDS()->Modified();
1506 // publish mesh in the study
1507 SALOMEDS::SObject_wrap aSO;
1508 if ( CanPublishInStudy( mesh ) )
1509 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1512 if ( !aSO->_is_nil() ) {
1516 aPythonDump << "mesh_" << i;
1519 aStudyBuilder->CommitCommand();
1522 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1524 // Dump creation of groups
1525 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1526 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1528 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1531 return aResult._retn();
1534 //================================================================================
1536 * \brief Create a mesh and import data from a GMF file
1538 //================================================================================
1540 SMESH::SMESH_Mesh_ptr
1541 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1542 CORBA::Boolean theMakeRequiredGroups,
1543 SMESH::ComputeError_out theError)
1545 Unexpect aCatch(SALOME_SalomeException);
1546 checkFileReadable( theFileName );
1548 SMESH::SMESH_Mesh_var aMesh = createMesh();
1550 char bname[ _MAX_FNAME ];
1551 _splitpath( theFileName, NULL, NULL, bname, NULL );
1552 string aFileName = bname;
1554 string aFileName = basename( const_cast<char *>(theFileName) );
1556 // publish mesh in the study
1557 if ( CanPublishInStudy( aMesh ) ) {
1558 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1559 aStudyBuilder->NewCommand(); // There is a transaction
1560 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1561 aStudyBuilder->CommitCommand();
1562 if ( !aSO->_is_nil() ) {
1563 // Update Python script
1564 TPythonDump(this) << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1565 << theFileName << "', "
1566 << theMakeRequiredGroups << " )";
1569 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1571 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1572 aServant->GetImpl().GetMeshDS()->Modified();
1573 return aMesh._retn();
1577 //=============================================================================
1579 * SMESH_Gen_i::IsReadyToCompute
1581 * Return true if mesh contains enough data to be computed
1583 //=============================================================================
1585 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1586 GEOM::GEOM_Object_ptr theShapeObject )
1588 Unexpect aCatch(SALOME_SalomeException);
1589 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1591 if ( CORBA::is_nil( theShapeObject ) )
1592 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1593 SALOME::BAD_PARAM );
1594 if ( CORBA::is_nil( theMesh ) )
1595 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1596 SALOME::BAD_PARAM );
1599 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1600 ASSERT( meshServant );
1601 if ( meshServant ) {
1602 // get local TopoDS_Shape
1603 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1604 // call implementation
1605 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1606 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1609 catch ( SALOME_Exception& S_ex ) {
1610 INFOS( "catch exception "<< S_ex.what() );
1615 //================================================================================
1617 * \brief Find SObject for an algo
1619 //================================================================================
1621 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1624 SALOMEDS::Study_var aStudy = getStudyServant();
1625 if ( !aStudy->_is_nil() ) {
1626 // find algo in the study
1627 CORBA::String_var compDataType = ComponentDataType();
1628 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1629 if ( !father->_is_nil() ) {
1630 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1631 for ( ; itBig->More(); itBig->Next() ) {
1632 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1633 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1634 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1635 for ( ; algoIt->More(); algoIt->Next() ) {
1636 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1637 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1638 if ( !CORBA::is_nil( algoIOR )) {
1639 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1640 if ( impl && impl->GetImpl() == algo )
1641 return algoSO._retn();
1643 } // loop on algo SO's
1646 } // SMESH component iterator
1650 return SALOMEDS::SObject::_nil();
1653 //================================================================================
1655 * \brief Return errors of mesh computation
1657 //================================================================================
1659 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1660 GEOM::GEOM_Object_ptr theSubObject )
1662 Unexpect aCatch(SALOME_SalomeException);
1663 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1665 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1666 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1668 if ( CORBA::is_nil( theMesh ) )
1669 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1671 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1673 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1676 if(theMesh->HasShapeToMesh())
1677 shape = GeomObjectToShape( theSubObject );
1679 shape = SMESH_Mesh::PseudoShape();
1681 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1683 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1686 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1687 const bool includeSelf = true, complexShapeFirst = true;
1688 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1690 while ( smIt->more() )
1693 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1695 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1696 if ( error && !error->IsOK() )
1698 if ( !( error->myAlgo ) &&
1699 !( error->myAlgo = sm->GetAlgo() ))
1701 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1702 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1703 errStruct.comment = error->myComment.c_str();
1704 errStruct.subShapeID = sm->GetId();
1705 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1706 if ( !algoSO->_is_nil() ) {
1707 CORBA::String_var algoName = algoSO->GetName();
1708 errStruct.algoName = algoName;
1711 errStruct.algoName = error->myAlgo->GetName();
1713 errStruct.hasBadMesh = error->HasBadElems();
1716 error_array->length( nbErr );
1719 catch ( SALOME_Exception& S_ex ) {
1720 INFOS( "catch exception "<< S_ex.what() );
1723 return error_array._retn();
1726 //================================================================================
1728 * \brief Return mesh elements preventing computation of a subshape
1730 //================================================================================
1732 SMESH::MeshPreviewStruct*
1733 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1734 CORBA::Short theSubShapeID )
1736 Unexpect aCatch(SALOME_SalomeException);
1737 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1739 if ( CORBA::is_nil( theMesh ) )
1740 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1742 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1745 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1747 // mesh implementation
1748 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1749 // submesh by subshape id
1750 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1753 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1754 if ( error && error->HasBadElems() )
1756 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1757 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1759 // get nodes of elements and count elements
1760 TNode2LocalIDMap mapNode2LocalID;
1761 list< TNodeLocalID > connectivity;
1762 int i, nbElements = 0, nbConnNodes = 0;
1764 const list<const SMDS_MeshElement*>& badElems =
1765 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1766 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1767 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1768 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1770 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1771 while ( nIt->more() )
1772 connectivity.push_back
1773 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1775 // fill node coords and assign local ids to the nodes
1776 int nbNodes = mapNode2LocalID.size();
1777 result->nodesXYZ.length( nbNodes );
1778 TNodeLocalID node2ID = mapNode2LocalID.begin();
1779 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1780 node2ID->second = i;
1781 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1782 result->nodesXYZ[i].x = node->X();
1783 result->nodesXYZ[i].y = node->Y();
1784 result->nodesXYZ[i].z = node->Z();
1786 // fill connectivity
1787 result->elementConnectivities.length( nbConnNodes );
1788 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1789 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1790 result->elementConnectivities[i] = (*connIt)->second;
1792 // fill element types
1793 result->elementTypes.length( nbElements );
1794 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1796 const SMDS_MeshElement* elem = *elemIt;
1797 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1798 result->elementTypes[i].isPoly = elem->IsPoly();
1799 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1805 catch ( SALOME_Exception& S_ex ) {
1806 INFOS( "catch exception "<< S_ex.what() );
1809 return result._retn();
1812 //================================================================================
1814 * \brief Create a group of elements preventing computation of a sub-shape
1816 //================================================================================
1818 SMESH::ListOfGroups*
1819 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1820 CORBA::Short theSubShapeID,
1821 const char* theGroupName )
1823 Unexpect aCatch(SALOME_SalomeException);
1825 SMESH::ListOfGroups_var groups;
1827 if ( CORBA::is_nil( theMesh ) )
1828 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1831 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1833 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1834 TPythonDump(this) << groups << " = " << this
1835 << ".MakeGroupsOfBadInputElements( "
1836 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1839 catch ( SALOME_Exception& S_ex ) {
1840 INFOS( "catch exception "<< S_ex.what() );
1842 return groups._retn();
1845 //================================================================================
1847 * \brief Returns errors of hypotheses definition
1848 * \param theMesh - the mesh
1849 * \param theSubObject - the main or sub- shape
1850 * \retval SMESH::algo_error_array* - sequence of errors
1852 //================================================================================
1854 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1855 GEOM::GEOM_Object_ptr theSubObject )
1857 Unexpect aCatch(SALOME_SalomeException);
1858 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1860 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1861 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1863 if ( CORBA::is_nil( theMesh ) )
1864 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1866 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1868 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1869 ASSERT( meshServant );
1870 if ( meshServant ) {
1871 TopoDS_Shape myLocShape;
1872 if(theMesh->HasShapeToMesh())
1873 myLocShape = GeomObjectToShape( theSubObject );
1875 myLocShape = SMESH_Mesh::PseudoShape();
1877 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1878 list< ::SMESH_Gen::TAlgoStateError > error_list;
1879 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1880 // call ::SMESH_Gen::GetAlgoState()
1881 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1882 error_array->length( error_list.size() );
1884 for ( error = error_list.begin(); error != error_list.end(); ++error )
1886 // fill AlgoStateError structure
1887 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1888 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1889 errStruct.algoDim = error->_algoDim;
1890 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1891 errStruct.algoName = "";
1892 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1893 if ( !algoSO->_is_nil() ) {
1894 CORBA::String_var algoName = algoSO->GetName();
1895 errStruct.algoName = algoName.in();
1900 catch ( SALOME_Exception& S_ex ) {
1901 INFOS( "catch exception "<< S_ex.what() );
1903 return error_array._retn();
1906 //=============================================================================
1908 * SMESH_Gen_i::GetSubShapesId
1910 * Get sub-shapes unique ID's list
1912 //=============================================================================
1915 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1916 const SMESH::object_array& theListOfSubShapeObject )
1918 Unexpect aCatch(SALOME_SalomeException);
1919 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1921 SMESH::long_array_var shapesId = new SMESH::long_array;
1924 if ( CORBA::is_nil( theMainShapeObject ) )
1925 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1929 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1930 TopTools_IndexedMapOfShape myIndexToShape;
1931 TopExp::MapShapes(myMainShape,myIndexToShape);
1933 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1935 GEOM::GEOM_Object_var aShapeObject
1936 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1937 if ( CORBA::is_nil( aShapeObject ) )
1938 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1939 SALOME::BAD_PARAM );
1941 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1942 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1944 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1945 setId.insert(myIndexToShape.FindIndex(F));
1946 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1948 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1950 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1951 setId.insert(myIndexToShape.FindIndex(E));
1952 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1954 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1956 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1957 setId.insert(myIndexToShape.FindIndex(V));
1958 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1961 shapesId->length(setId.size());
1962 set<int>::iterator iind;
1964 for (iind = setId.begin(); iind != setId.end(); iind++)
1966 if(MYDEBUG) SCRUTE((*iind));
1967 shapesId[i] = (*iind);
1968 if(MYDEBUG) SCRUTE(shapesId[i]);
1972 catch (SALOME_Exception& S_ex)
1974 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1977 return shapesId._retn();
1980 //=============================================================================
1982 * SMESH_Gen_i::Compute
1984 * Compute mesh on a shape
1986 //=============================================================================
1988 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1989 GEOM::GEOM_Object_ptr theShapeObject )
1992 Unexpect aCatch(SALOME_SalomeException);
1993 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1995 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1996 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1997 SALOME::BAD_PARAM );
1999 if ( CORBA::is_nil( theMesh ) )
2000 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2001 SALOME::BAD_PARAM );
2003 // Update Python script
2004 TPythonDump(this) << "isDone = " << this << ".Compute( "
2005 << theMesh << ", " << theShapeObject << ")";
2009 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2010 ASSERT( meshServant );
2011 if ( meshServant ) {
2012 if ( isGeomModifIcon( theMesh ))
2013 meshServant->Clear();
2015 meshServant->Load();
2016 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2017 meshServant->CheckGeomModif();
2018 // get local TopoDS_Shape
2019 TopoDS_Shape myLocShape;
2020 if(theMesh->HasShapeToMesh())
2021 myLocShape = GeomObjectToShape( theShapeObject );
2023 myLocShape = SMESH_Mesh::PseudoShape();
2024 // call implementation compute
2025 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2026 myGen.PrepareCompute( myLocMesh, myLocShape );
2027 int how = ::SMESH_Gen::COMPACT_MESH;
2028 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2029 how |= ::SMESH_Gen::SHAPE_ONLY;
2030 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2031 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2032 myLocMesh.GetMeshDS()->Modified();
2033 UpdateIcons( theMesh );
2035 HighLightInvalid( theMesh, /*isInvalid=*/false );
2039 catch ( std::bad_alloc& ) {
2040 INFOS( "Compute(): lack of memory" );
2042 catch ( SALOME_Exception& S_ex ) {
2043 INFOS( "Compute(): catch exception "<< S_ex.what() );
2046 INFOS( "Compute(): unknown exception " );
2051 //=============================================================================
2053 * SMESH_Gen_i::CancelCompute
2055 * Cancel Compute mesh on a shape
2057 //=============================================================================
2059 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2060 GEOM::GEOM_Object_ptr theShapeObject )
2062 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2064 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2065 TopoDS_Shape myLocShape;
2066 if(theMesh->HasShapeToMesh())
2067 myLocShape = GeomObjectToShape( theShapeObject );
2069 myLocShape = SMESH_Mesh::PseudoShape();
2070 myGen.CancelCompute( myLocMesh, myLocShape);
2074 //=============================================================================
2076 * SMESH_Gen_i::Precompute
2078 * Compute mesh as preview till indicated dimension on shape
2080 //=============================================================================
2082 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2083 GEOM::GEOM_Object_ptr theShapeObject,
2084 SMESH::Dimension theDimension,
2085 SMESH::long_array& theShapesId)
2087 Unexpect aCatch(SALOME_SalomeException);
2088 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2090 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2091 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2092 SALOME::BAD_PARAM );
2094 if ( CORBA::is_nil( theMesh ) )
2095 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2096 SALOME::BAD_PARAM );
2098 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2101 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2102 meshServant->Load();
2103 ASSERT( meshServant );
2104 if ( meshServant ) {
2105 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2106 meshServant->CheckGeomModif();
2107 // get local TopoDS_Shape
2108 TopoDS_Shape myLocShape;
2109 if(theMesh->HasShapeToMesh())
2110 myLocShape = GeomObjectToShape( theShapeObject );
2112 return result._retn();
2114 // call implementation compute
2115 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2117 ::MeshDimension aDim = (MeshDimension)theDimension;
2118 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2120 int nbShapeId = shapeIds.size();
2121 theShapesId.length( nbShapeId );
2122 // iterates on shapes and collect mesh entities into mesh preview
2123 TSetOfInt::const_iterator idIt = shapeIds.begin();
2124 TSetOfInt::const_iterator idEnd = shapeIds.end();
2125 std::map< int, int > mapOfShIdNb;
2126 std::set< SMESH_TLink > setOfEdge;
2127 std::list< SMDSAbs_ElementType > listOfElemType;
2128 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2129 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2130 TNode2LocalIDMap mapNode2LocalID;
2131 list< TNodeLocalID > connectivity;
2132 int i, nbConnNodes = 0;
2133 std::set< const SMESH_subMesh* > setOfVSubMesh;
2134 // iterates on shapes
2135 for ( ; idIt != idEnd; idIt++ )
2137 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2139 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2140 if ( !sm || !sm->IsMeshComputed() )
2143 const TopoDS_Shape& aSh = sm->GetSubShape();
2144 const int shDim = myGen.GetShapeDim( aSh );
2145 if ( shDim < 1 || shDim > theDimension )
2148 mapOfShIdNb[ *idIt ] = 0;
2149 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2151 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2152 if ( !smDS ) continue;
2154 if ( theDimension == SMESH::DIM_2D )
2156 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2157 while ( faceIt->more() )
2159 const SMDS_MeshElement* face = faceIt->next();
2160 int aNbNode = face->NbNodes();
2162 aNbNode /= 2; // do not take into account additional middle nodes
2164 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2165 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2167 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2168 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2170 listOfElemType.push_back( SMDSAbs_Edge );
2171 connectivity.push_back
2172 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2173 connectivity.push_back
2174 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2180 else if ( theDimension == SMESH::DIM_1D )
2182 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2183 while ( nodeIt->more() )
2185 listOfElemType.push_back( SMDSAbs_Node );
2186 connectivity.push_back
2187 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2189 // add corner nodes by first vertex from edge
2190 SMESH_subMeshIteratorPtr edgeSmIt =
2191 sm->getDependsOnIterator(/*includeSelf*/false,
2192 /*complexShapeFirst*/false);
2193 while ( edgeSmIt->more() )
2195 SMESH_subMesh* vertexSM = edgeSmIt->next();
2196 // check that vertex is not already treated
2197 if ( !setOfVSubMesh.insert( vertexSM ).second )
2199 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2202 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2203 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2204 while ( nodeIt->more() )
2206 listOfElemType.push_back( SMDSAbs_Node );
2207 connectivity.push_back
2208 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2214 // fill node coords and assign local ids to the nodes
2215 int nbNodes = mapNode2LocalID.size();
2216 result->nodesXYZ.length( nbNodes );
2217 TNodeLocalID node2ID = mapNode2LocalID.begin();
2218 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2219 node2ID->second = i;
2220 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2221 result->nodesXYZ[i].x = node->X();
2222 result->nodesXYZ[i].y = node->Y();
2223 result->nodesXYZ[i].z = node->Z();
2225 // fill connectivity
2226 result->elementConnectivities.length( nbConnNodes );
2227 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2228 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2229 result->elementConnectivities[i] = (*connIt)->second;
2232 // fill element types
2233 result->elementTypes.length( listOfElemType.size() );
2234 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2235 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2236 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2238 SMDSAbs_ElementType elemType = *typeIt;
2239 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2240 result->elementTypes[i].isPoly = false;
2241 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2244 // correct number of shapes
2245 theShapesId.length( mapOfShIdNb.size() );
2249 catch ( std::bad_alloc& ) {
2250 INFOS( "Precompute(): lack of memory" );
2252 catch ( SALOME_Exception& S_ex ) {
2253 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2256 INFOS( "Precompute(): unknown exception " );
2258 return result._retn();
2262 //=============================================================================
2264 * SMESH_Gen_i::Evaluate
2266 * Evaluate mesh on a shape
2268 //=============================================================================
2270 SMESH::smIdType_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2271 GEOM::GEOM_Object_ptr theShapeObject)
2273 Unexpect aCatch(SALOME_SalomeException);
2274 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2276 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2277 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2279 if ( CORBA::is_nil( theMesh ) )
2280 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2282 SMESH::smIdType_array_var nbels = new SMESH::smIdType_array;
2283 nbels->length(SMESH::Entity_Last);
2284 int i = SMESH::Entity_Node;
2285 for (; i < SMESH::Entity_Last; i++)
2288 // Update Python script
2289 TPythonDump(this) << "theNbElems = " << this << ".Evaluate( "
2290 << theMesh << ", " << theShapeObject << ")";
2294 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2295 ASSERT( meshServant );
2296 if ( meshServant ) {
2297 meshServant->Load();
2298 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2299 meshServant->CheckGeomModif();
2300 // get local TopoDS_Shape
2301 TopoDS_Shape myLocShape;
2302 if(theMesh->HasShapeToMesh())
2303 myLocShape = GeomObjectToShape( theShapeObject );
2305 myLocShape = SMESH_Mesh::PseudoShape();
2306 // call implementation compute
2307 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2308 MapShapeNbElems aResMap;
2309 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2310 MapShapeNbElemsItr anIt = aResMap.begin();
2311 for(; anIt!=aResMap.end(); anIt++) {
2312 const vector<smIdType>& aVec = (*anIt).second;
2313 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2314 smIdType nbElem = aVec[i];
2315 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2317 SMESH_subMesh* sm = anIt->first;
2318 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2319 const SMESH_Algo* algo = sm->GetAlgo();
2320 if ( (algo && !error.get()) || error->IsOK() )
2321 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2325 nbels[i] += aVec[i];
2329 return nbels._retn();
2332 catch ( std::bad_alloc& ) {
2333 INFOS( "Evaluate(): lack of memory" );
2335 catch ( SALOME_Exception& S_ex ) {
2336 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2339 INFOS( "Evaluate(): unknown exception " );
2342 return nbels._retn();
2345 //================================================================================
2347 * \brief Return geometrical object the given element is built on
2348 * \param theMesh - the mesh the element is in
2349 * \param theElementID - the element ID
2350 * \param theGeomName - the name of the result geom object if it is not yet published
2351 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2353 //================================================================================
2355 GEOM::GEOM_Object_ptr
2356 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2357 SMESH::smIdType theElementID,
2358 const char* theGeomName)
2360 Unexpect aCatch(SALOME_SalomeException);
2362 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2363 if ( !geom->_is_nil() ) {
2364 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2365 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2367 // try to find the corresponding SObject
2368 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2369 if ( SObj->_is_nil() ) // submesh can be not found even if published
2371 // try to find published submesh
2372 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2373 if ( !geom->IsMainShape() && list->length() == 1 ) {
2374 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2375 SALOMEDS::ChildIterator_wrap it;
2376 if ( !mainSO->_is_nil() ) {
2377 it = getStudyServant()->NewChildIterator( mainSO );
2379 if ( !it->_is_nil() ) {
2380 for ( it->InitEx(true); it->More(); it->Next() ) {
2381 SALOMEDS::SObject_wrap so = it->Value();
2382 CORBA::Object_var obj = SObjectToObject( so );
2383 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2384 if ( !subGeom->_is_nil() ) {
2385 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2386 if ( subList->length() == 1 && list[0] == subList[0] ) {
2396 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2397 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2399 // return only published geometry
2400 if ( !SObj->_is_nil() ) {
2401 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2402 CORBA::Object_var obj = SObjectToObject( SObj );
2403 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2407 return GEOM::GEOM_Object::_nil();
2410 //================================================================================
2412 * \brief Return geometrical object the given element is built on.
2413 * \param theMesh - the mesh the element is in
2414 * \param theElementID - the element ID
2415 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2417 //================================================================================
2419 GEOM::GEOM_Object_ptr
2420 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2421 SMESH::smIdType theElementID)
2423 Unexpect aCatch(SALOME_SalomeException);
2424 if ( CORBA::is_nil( theMesh ) )
2425 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2427 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2428 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2430 // get a core mesh DS
2431 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2432 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2434 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2435 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2436 // find the element in mesh
2437 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2438 // find a shape id by the element
2439 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2440 // get a geom object by the shape id
2441 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2442 if ( geom->_is_nil() ) {
2443 // try to find a published sub-shape
2444 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2445 SALOMEDS::ChildIterator_wrap it;
2446 if ( !mainSO->_is_nil() ) {
2447 it = getStudyServant()->NewChildIterator( mainSO );
2449 if ( !it->_is_nil() ) {
2450 for ( it->InitEx(true); it->More(); it->Next() ) {
2451 SALOMEDS::SObject_wrap so = it->Value();
2452 CORBA::Object_var obj = SObjectToObject( so );
2453 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2454 if ( !subGeom->_is_nil() ) {
2455 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2456 if ( subList->length() == 1 && shapeID == subList[0] ) {
2464 if ( geom->_is_nil() ) {
2466 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2467 if ( !op->_is_nil() )
2468 geom = op->GetSubShape( mainShape, shapeID );
2473 if ( !geom->_is_nil() ) {
2474 GeomObjectToShape( geom ); // let geom client remember the found shape
2475 return geom._retn();
2480 return GEOM::GEOM_Object::_nil();
2483 //================================================================================
2485 * SMESH_Gen_i::Concatenate
2487 * Concatenate the given meshes into one mesh
2489 //================================================================================
2491 SMESH::SMESH_Mesh_ptr
2492 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2493 CORBA::Boolean theUniteIdenticalGroups,
2494 CORBA::Boolean theMergeNodesAndElements,
2495 CORBA::Double theMergeTolerance,
2496 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2498 return ConcatenateCommon(theMeshesArray,
2499 theUniteIdenticalGroups,
2500 theMergeNodesAndElements,
2506 //================================================================================
2508 * SMESH_Gen_i::ConcatenateWithGroups
2510 * Concatenate the given meshes into one mesh
2511 * Create the groups of all elements from initial meshes
2513 //================================================================================
2515 SMESH::SMESH_Mesh_ptr
2516 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2517 CORBA::Boolean theUniteIdenticalGroups,
2518 CORBA::Boolean theMergeNodesAndElements,
2519 CORBA::Double theMergeTolerance,
2520 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2522 return ConcatenateCommon(theMeshesArray,
2523 theUniteIdenticalGroups,
2524 theMergeNodesAndElements,
2530 //================================================================================
2532 * SMESH_Gen_i::ConcatenateCommon
2534 * Concatenate the given meshes into one mesh
2536 //================================================================================
2538 SMESH::SMESH_Mesh_ptr
2539 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2540 CORBA::Boolean theUniteIdenticalGroups,
2541 CORBA::Boolean theMergeNodesAndElements,
2542 CORBA::Double theMergeTolerance,
2543 CORBA::Boolean theCommonGroups,
2544 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2546 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump(this) );
2547 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2549 // create mesh if theMeshToAppendTo not provided
2550 SMESH::SMESH_Mesh_var newMesh;
2551 if ( CORBA::is_nil( theMeshToAppendTo ))
2552 newMesh = CreateEmptyMesh();
2554 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2555 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2556 if ( !newImpl ) return newMesh._retn();
2559 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2560 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2562 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2563 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2564 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2565 TGroupsMap groupsMap;
2566 TListOfNewGroups listOfNewGroups;
2568 if ( !CORBA::is_nil( theMeshToAppendTo ))
2570 // fill groupsMap with existing groups
2571 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2572 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2574 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2575 if ( !group->_is_nil() )
2577 CORBA::String_var name = group->GetName();
2578 SMESH::ElementType type = group->GetType();
2579 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2584 ::SMESH_MeshEditor newEditor( &locMesh );
2585 ::SMESH_MeshEditor::ElemFeatures elemType;
2587 // loop on sub-meshes
2588 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2590 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2591 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2592 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2593 if ( !initImpl ) continue;
2594 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2598 // assure that IDs increment by one during iteration
2599 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2600 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2601 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2602 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2604 initMeshDS->Modified();
2605 initMeshDS->CompactMesh();
2608 // remember nb of elements before filling in
2609 SMESH::smIdType_array_var prevState = newMesh->GetNbElementsByType();
2613 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2614 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2615 while ( elemIt->more() )
2617 SMESH_NodeXYZ node = elemIt->next();
2618 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2623 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2624 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2625 bool hasElems = (( srcElemTypes->length() > 1 ) ||
2626 ( srcElemTypes->length() == 1 && srcElemTypes[0] != SMESH::NODE ));
2629 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2630 while ( elemIt->more() )
2632 const SMDS_MeshElement* elem = elemIt->next();
2633 elemType.myNodes.resize( elem->NbNodes() );
2635 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2636 for ( int k = 0; itNodes->more(); k++)
2638 const SMDS_MeshNode* node = itNodes->next();
2639 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2642 // creates a corresponding element on existent nodes in new mesh
2643 newElems[ elem->GetID() ] =
2644 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2646 newEditor.ClearLastCreated(); // forget the history
2650 // create groups of just added elements
2651 SMESH::SMESH_Group_var newGroup;
2652 SMESH::ElementType groupType;
2653 if ( theCommonGroups )
2656 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2658 // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2659 static_assert( sizeof(typeNames) / sizeof(const char*) ==SMESH::NB_ELEMENT_TYPES,
2660 "Update names of ElementType's!!!" );
2662 SMESH::smIdType_array_var curState = newMesh->GetNbElementsByType();
2664 for( groupType = SMESH::NODE;
2665 groupType < SMESH::NB_ELEMENT_TYPES;
2666 groupType = (SMESH::ElementType)( groupType + 1 ))
2668 if ( curState[ groupType ] <= prevState[ groupType ])
2669 continue; // no elements of groupType added from the i-th mesh
2671 // make a group name
2672 std::string groupName = "Gr";
2673 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2675 CORBA::String_var name = meshSO->GetName();
2679 groupName += typeNames[ groupType ];
2681 // make and fill a group
2682 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2683 std::vector< const SMDS_MeshElement* > & elemVec =
2684 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2685 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2687 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2689 for ( size_t j = 0; j < elemVec.size(); ++j )
2691 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2692 grpDS->Add( elemVec[j] );
2696 listOfNewGroups.clear();
2697 listOfNewGroups.push_back( newGroup );
2698 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2703 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2707 SMESH::SMESH_GroupBase_ptr group;
2708 CORBA::String_var groupName;
2709 SMESH::smIdType_array_var newIDs = new SMESH::smIdType_array();
2711 // loop on groups of a source mesh
2712 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2713 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2715 group = listOfGroups[iG];
2716 groupType = group->GetType();
2717 groupName = group->GetName();
2718 std::string name = groupName.in();
2720 // convert a list of IDs
2721 newIDs->length( group->Size() );
2722 std::vector< const SMDS_MeshElement* > & elemVec =
2723 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2724 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2726 while ( itGrElems->more() )
2728 const SMDS_MeshElement* elem = itGrElems->next();
2729 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2731 newIDs[ nbElems++ ] = newElem->GetID();
2733 newIDs->length( nbElems );
2735 // check that a current group name and type don't have identical ones in final mesh
2736 listOfNewGroups.clear();
2737 TNameAndType nameAndType( name, groupType );
2738 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2739 if ( anIter == groupsMap.end() )
2741 // add a new group in the mesh
2742 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2743 newGroup->Add( newIDs );
2745 listOfNewGroups.push_back( newGroup );
2746 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2748 else if ( theUniteIdenticalGroups )
2750 // unite identical groups
2751 TListOfNewGroups& aNewGroups = anIter->second;
2752 aNewGroups.front()->Add( newIDs );
2756 // rename identical groups
2757 newGroup = newImpl->CreateGroup( groupType, groupName );
2758 newGroup->Add( newIDs );
2760 TListOfNewGroups& newGroups = anIter->second;
2761 std::string newGroupName;
2762 if ( newGroups.size() == 1 )
2764 newGroupName = name + "_1";
2765 newGroups.front()->SetName( newGroupName.c_str() );
2767 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2768 newGroup->SetName( newGroupName.c_str() );
2769 newGroups.push_back( newGroup );
2772 } // if an IDSource is a mesh
2775 if ( theMergeNodesAndElements ) // merge nodes
2777 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2778 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2779 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2780 /*SeparateCornersAndMedium=*/ false );
2781 newEditor.MergeNodes( groupsOfNodes );
2783 newEditor.MergeEqualElements();
2786 // Update Python script
2787 pythonDump << newMesh << " = " << this
2788 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2789 << theMeshesArray << ", "
2790 << theUniteIdenticalGroups << ", "
2791 << theMergeNodesAndElements << ", "
2792 << TVar( theMergeTolerance ) << ", "
2793 << theMeshToAppendTo << " )";
2795 pPythonDump.reset(); // enable python dump from GetGroups()
2797 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2798 if ( !newMesh->_is_nil() )
2800 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2803 // IPAL21468 Change icon of compound because it need not be computed.
2804 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2805 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2807 newMeshDS->Modified();
2809 return newMesh._retn();
2813 //================================================================================
2815 * \brief Create a mesh by copying a part of another mesh
2816 * \param mesh - TetraHedron mesh
2817 * \param meshName Name of the created mesh
2818 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2820 //================================================================================
2822 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateDualMesh(SMESH::SMESH_IDSource_ptr mesh,
2823 const char* meshName,
2824 CORBA::Boolean adapt_to_shape)
2826 Unexpect aCatch(SALOME_SalomeException);
2828 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2829 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2831 // 1. Get source mesh
2833 if ( CORBA::is_nil( mesh ))
2834 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2836 SMESH::SMESH_Mesh_var srcMesh = mesh->GetMesh();
2837 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2839 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2841 CORBA::String_var mesh_var=GetORB()->object_to_string(mesh);
2842 std::string mesh_ior = mesh_var.in();
2844 //temporary folder for the generation of the med file
2845 fs::path tmp_folder = fs::temp_directory_path() / fs::unique_path(fs::path("dual_mesh-%%%%"));
2846 fs::create_directories(tmp_folder);
2847 fs::path dual_mesh_file = tmp_folder / fs::path("tmp_dual_mesh.med");
2848 std::string mesh_name(meshName);
2849 MESSAGE("Working in folder" + tmp_folder.string());
2851 // Running Python script
2852 assert(Py_IsInitialized());
2853 PyGILState_STATE gstate;
2854 gstate = PyGILState_Ensure();
2863 std::string cmd="import salome.smesh.smesh_tools as smt\n";
2864 cmd +="smt.smesh_create_dual_mesh(\"" + mesh_ior + "\", \"" +
2865 dual_mesh_file.string() + "\", mesh_name=\"" + mesh_name + "\", adapt_to_shape=" + ats + ")";
2868 PyObject *py_main = PyImport_AddModule("__main__");
2869 PyObject *py_dict = PyModule_GetDict(py_main);
2871 PyRun_String(cmd.c_str(), Py_file_input, py_dict, py_dict);
2873 if (PyErr_Occurred()) {
2874 // Restrieving python error
2875 MESSAGE("Catching error")
2876 PyObject *errtype, *errvalue, *traceback;
2877 PyErr_Fetch(&errtype, &errvalue, &traceback);
2878 if(errvalue != NULL) {
2879 MESSAGE("Error has a value")
2880 PyObject *s = PyObject_Str(errvalue);
2882 std::string msg = PyUnicode_AsUTF8AndSize(s, &size);
2883 msg = "Issue with the execution of create_dual_mesh:\n"+msg;
2884 MESSAGE("throwing exception")
2885 // We need to deactivate the GIL before throwing the exception
2886 PyGILState_Release(gstate);
2887 THROW_SALOME_CORBA_EXCEPTION(msg.c_str(), SALOME::INTERNAL_ERROR );
2890 Py_XDECREF(errvalue);
2891 Py_XDECREF(errtype);
2892 Py_XDECREF(traceback);
2895 PyGILState_Release(gstate);
2897 MESSAGE("Mesh created in " + dual_mesh_file.string());
2899 // Import created MED
2900 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2901 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2903 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2904 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2905 if ( !meshSO->_is_nil() )
2907 SetName( meshSO, meshName, meshName );
2908 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2910 int ret = newMesh_i->ImportMEDFile(dual_mesh_file.string().c_str(), meshName);
2912 THROW_SALOME_CORBA_EXCEPTION( "Issue when importing mesh", SALOME::INTERNAL_ERROR );
2915 SMESH_Mesh& newMesh2 = newMesh_i->GetImpl();
2918 MESSAGE("Loading file: " << dual_mesh_file.string() << " with mesh " << meshName);
2919 int ret = newMesh2.MEDToMesh(dual_mesh_file.c_str(), meshName);
2922 newMesh_i->GetImpl().GetMeshDS()->Modified();
2924 *pyDump << newMesh << " = " << this
2925 << ".CreateDualMesh("
2927 << "'" << mesh_name << "', "
2930 pyDumpDeleter.reset(); // allow dump in GetGroups()
2932 if ( srcMesh_i->GetImpl().GetGroupIds().size() > 0 ) // dump created groups
2933 MESSAGE("Dump of groups");
2934 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2936 return newMesh._retn();
2939 //================================================================================
2941 * \brief Create a mesh by copying a part of another mesh
2942 * \param meshPart - a part of mesh to copy
2943 * \param toCopyGroups - to create in the new mesh groups
2944 * the copied elements belongs to
2945 * \param toKeepIDs - to preserve IDs of the copied elements or not
2946 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2948 //================================================================================
2950 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2951 const char* meshName,
2952 CORBA::Boolean toCopyGroups,
2953 CORBA::Boolean toKeepIDs)
2955 Unexpect aCatch(SALOME_SalomeException);
2957 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2958 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2960 // 1. Get source mesh
2962 if ( CORBA::is_nil( meshPart ))
2963 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2965 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2966 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2968 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2970 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2972 // 2. Make a new mesh
2974 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2975 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2977 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2978 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2979 if ( !meshSO->_is_nil() )
2981 SetName( meshSO, meshName, "Mesh" );
2982 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2984 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2985 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2986 ::SMESH_MeshEditor::ElemFeatures elemType;
2988 // 3. Get elements to copy
2990 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2991 TIDSortedElemSet srcElems;
2992 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2993 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2996 srcElemIt = srcMeshDS->elementsIterator();
2997 srcNodeIt = srcMeshDS->nodesIterator();
3001 SMESH::smIdType_array_var ids = meshPart->GetIDs();
3002 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
3004 for ( CORBA::ULong i=0; i < ids->length(); i++ )
3005 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
3006 srcElems.insert( elem );
3010 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
3011 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
3012 srcElems.insert( elem );
3014 if ( srcElems.empty() )
3015 return newMesh._retn();
3017 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
3018 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
3023 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
3024 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
3025 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
3027 const SMDS_MeshNode *nSrc, *nTgt;
3028 vector< const SMDS_MeshNode* > nodes;
3029 while ( srcElemIt->more() )
3031 const SMDS_MeshElement * elem = srcElemIt->next();
3033 nodes.resize( elem->NbNodes());
3034 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
3036 for ( iN = 0; nIt->more(); ++iN )
3038 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3039 nTgt = newMeshDS->FindNode( nSrc->GetID());
3041 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3046 for ( iN = 0; nIt->more(); ++iN )
3048 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
3049 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
3051 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3052 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
3056 if ( elem->GetType() != SMDSAbs_Node )
3058 elemType.Init( elem, /*basicOnly=*/false );
3059 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
3061 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
3062 if ( toCopyGroups && !toKeepIDs )
3063 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
3065 } // while ( srcElemIt->more() )
3067 // 4(b). Copy free nodes
3069 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3071 while ( srcNodeIt->more() )
3073 nSrc = srcNodeIt->next();
3074 if ( nSrc->NbInverseElements() == 0 )
3077 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3079 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3086 int nbNewGroups = 0;
3089 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3090 while ( gIt->more() )
3092 SMESH_Group* group = gIt->next();
3093 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3095 // Check group type. We copy nodal groups containing nodes of copied element
3096 SMDSAbs_ElementType groupType = groupDS->GetType();
3097 if ( groupType != SMDSAbs_Node &&
3098 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3099 continue; // group type differs from types of meshPart
3101 // Find copied elements in the group
3102 vector< const SMDS_MeshElement* > groupElems;
3103 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3106 const SMDS_MeshElement* foundElem;
3107 if ( groupType == SMDSAbs_Node )
3109 while ( eIt->more() )
3110 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3111 groupElems.push_back( foundElem );
3115 while ( eIt->more() )
3116 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3117 groupElems.push_back( foundElem );
3122 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3123 if ( e2eMap.empty() ) continue;
3124 smIdType minID = e2eMap.begin()->first->GetID();
3125 smIdType maxID = e2eMap.rbegin()->first->GetID();
3126 TE2EMap::iterator e2e;
3127 while ( eIt->more() && groupElems.size() < e2eMap.size())
3129 const SMDS_MeshElement* e = eIt->next();
3130 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3131 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3132 groupElems.push_back( e2e->second );
3136 if ( !groupElems.empty() )
3138 SMESH::SMESH_Group_var newGroupObj =
3139 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3140 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3142 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3143 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3144 for ( unsigned i = 0; i < groupElems.size(); ++i )
3145 smdsGroup.Add( groupElems[i] );
3153 newMeshDS->Modified();
3155 *pyDump << newMesh << " = " << this
3156 << ".CopyMesh( " << meshPart << ", "
3157 << "'" << meshName << "', "
3158 << toCopyGroups << ", "
3159 << toKeepIDs << ")";
3161 pyDumpDeleter.reset(); // allow dump in GetGroups()
3163 if ( nbNewGroups > 0 ) // dump created groups
3164 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3166 return newMesh._retn();
3170 namespace // utils for CopyMeshWithGeom()
3172 typedef std::map< std::string, std::string > TStr2StrMap;
3173 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3174 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3175 typedef std::map< std::string, int > TName2IndexMap;
3177 //================================================================================
3179 * \brief Return a new sub-shape corresponding to an old one
3181 //================================================================================
3185 SMESH_Mesh_i* mySrcMesh_i;
3186 SMESH_Mesh_i* myNewMesh_i;
3187 SMESH_Gen_i* myGen_i;
3191 TStr2StrMap myOld2NewEntryMap; // map of study entries
3193 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3194 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3195 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3198 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3200 // not directly relating to shape search
3201 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3203 //================================================================================
3205 * \brief Constructor
3207 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3208 SMESH_Mesh_i* newMesh_i,
3209 SMESH_Gen_i* smeshGen_i )
3210 : mySrcMesh_i( srcMesh_i ),
3211 myNewMesh_i( newMesh_i ),
3212 myGen_i ( smeshGen_i ),
3213 myToPublish( smeshGen_i->IsEnablePublish() ),
3214 myGIPMapDone( false )
3216 // retrieve from the study shape mapping made thanks to
3217 // "Set presentation parameters and sub-shapes from arguments" option
3219 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3220 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3221 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3222 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3223 if ( newSO->_is_nil() )
3225 myToPublish = false;
3228 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3230 CORBA::String_var oldEntry = oldSO->GetID();
3231 CORBA::String_var newEntry = newSO->GetID();
3232 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3233 std::string( newEntry.in() )));
3234 std::string newMainEntry = newEntry.in();
3236 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3237 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3238 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3239 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3240 /*groupsOnly=*/false );
3241 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3243 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3244 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3245 bool refFound = false;
3246 for ( ; anIter->More(); anIter->Next() )
3248 SALOMEDS::SObject_wrap so = anIter->Value();
3249 if ( so->ReferencedObject( oldSO.inout() ))
3251 oldEntry = oldSO->GetID();
3252 newEntry = newSO->GetID();
3253 if (( refFound = ( newMainEntry != oldEntry.in() )))
3254 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3255 std::string( newEntry.in() )));
3260 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3261 if ( father->_is_equivalent( mainShapeNew ))
3263 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3264 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3265 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3266 CORBA::String_var name = newSO->GetName();
3268 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3274 //================================================================================
3276 * \brief Find a new sub-shape corresponding to an old one
3278 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3281 return GEOM::GEOM_Object::_duplicate( oldShape );
3283 GEOM::GEOM_Object_var newShape;
3285 if ( CORBA::is_nil( oldShape ))
3286 return newShape._retn();
3288 if ( !isChildOfOld( oldShape ))
3289 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3291 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3292 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3294 // try to find by entry or name
3297 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3298 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3299 if ( o2nID != myOld2NewEntryMap.end() )
3301 newShape = getShapeByEntry( o2nID->second );
3303 if ( newShape->_is_nil() )
3305 CORBA::String_var name = oldShape->GetName();
3306 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3307 if ( n2ind != myName2SubshapeIndex.end() )
3309 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3310 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3311 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3312 if ( oldIndices->length() == 0 ||
3313 newIndices->length() == 0 ||
3314 getShapeType( myNewMesh_i, newIndices[0] ) !=
3315 getShapeType( mySrcMesh_i, oldIndices[0] ))
3316 newShape = GEOM::GEOM_Object::_nil();
3321 if ( newShape->_is_nil() )
3323 // try to construct a new sub-shape using myGIPMap
3325 std::vector< int > newIndices;
3326 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3327 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3329 findNewIDs( oldIndices[i], newIndices );
3331 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3334 newShape = getInPlace( oldShape );
3336 if ( !newIndices.empty() && newShape->_is_nil() )
3338 // search for a sub-shape with same ids
3339 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3340 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3341 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3342 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3344 if ( newShape->_is_nil() )
3347 // create a new shape
3348 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3350 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3352 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3353 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3355 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3356 newIndicesList->length( newIndices.size() );
3357 for ( size_t i = 0; i < newIndices.size(); ++i )
3358 newIndicesList[ i ] = newIndices[ i ];
3359 grOp->UnionIDs( newShape, newIndicesList );
3363 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3364 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3373 if ( !newShape->_is_nil() && myToPublish )
3375 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3376 if ( !newEntry.in() || !newEntry.in()[0] )
3378 CORBA::String_var name = oldShape->GetName();
3379 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3380 newEntry = newShape->GetStudyEntry();
3381 oldEntry = oldShape->GetStudyEntry();
3382 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3383 std::string( newEntry.in() )));
3387 return newShape._retn();
3390 //================================================================================
3392 * \brief Return a study entry of a new shape by study entry of the old one
3394 std::string FindNew( const std::string & oldEntry )
3399 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3400 if ( o2nID != myOld2NewEntryMap.end() )
3401 return o2nID->second;
3403 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3404 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3407 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3408 if ( newShape->_is_nil() )
3409 return std::string();
3411 CORBA::String_var newEntry = newShape->GetStudyEntry();
3412 return newEntry.in();
3415 //================================================================================
3417 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3418 * Return zero if not found or there are more than one new ID
3420 int FindNew( int oldID )
3429 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3431 if ( myGIPMap[ oldID ].length() == 1 )
3433 newID = myGIPMap[ oldID ][ 0 ];
3435 else if ( myGIPMap[ oldID ].length() > 1 &&
3436 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3438 // select a meshed VERTEX
3439 SMESH_subMesh* newSM;
3440 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3441 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3442 ( !newSM->IsEmpty() ))
3443 newID = myGIPMap[ oldID ][ i ];
3449 //================================================================================
3451 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3452 * Return zero if the old shape is not kept as is in the new shape.
3454 int FindNewNotChanged( SMESH_subMesh* oldSM )
3457 return oldSM->GetId();
3459 int newID = FindNew( oldSM->GetId() );
3463 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3467 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3468 // one new sub-shape of the same type.
3470 if ( oldSM->DependsOn().size() !=
3471 newSM->DependsOn().size() )
3474 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3475 while ( srcSMIt->more() )
3477 oldSM = srcSMIt->next();
3478 int newSubID = FindNew( oldSM->GetId() );
3479 if ( getShapeType( myNewMesh_i, newSubID ) !=
3480 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3486 //================================================================================
3488 * \brief Return shape by study entry
3490 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3492 GEOM::GEOM_Object_var shape;
3493 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3494 if ( !so->_is_nil() )
3496 CORBA::Object_var obj = so->GetObject();
3497 shape = GEOM::GEOM_Object::_narrow( obj );
3499 return shape._retn();
3502 //================================================================================
3504 * \brief Fill myGIPMap by calling GetInPlaceMap()
3508 if ( !myGIPMapDone )
3510 myGIPMapDone = true;
3512 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3513 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3514 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3515 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3518 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3522 myGIPMap = new GEOM::ListOfListOfLong();
3527 //================================================================================
3529 * \brief Get new sub-shape by calling GetInPlace()
3531 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3533 GEOM::GEOM_Object_var newShape;
3535 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3536 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3537 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3540 newShape = op->GetInPlace( mainShapeNew, oldShape );
3545 return newShape._retn();
3548 //================================================================================
3550 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3551 * number of found IDs
3553 int findNewIDs( int oldID, std::vector< int >& newIDs )
3555 size_t prevNbIDs = newIDs.size();
3557 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3559 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3560 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3562 return newIDs.size() - prevNbIDs;
3565 //================================================================================
3567 * \brief Check if an object relates to the old shape
3569 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3571 if ( CORBA::is_nil( oldShape ))
3573 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3574 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3575 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3576 mainShapeOld1->_is_equivalent( oldShape ));
3579 //================================================================================
3581 * \brief Return shape type by shape ID
3583 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3585 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3586 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3587 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3590 //================================================================================
3592 * \brief Store a source sub-shape for which a counterpart not found and
3593 * a smesh object invalid due to that
3595 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3596 SALOMEDS::SObject_wrap smeshSO )
3598 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3599 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3601 CORBA::String_var smeshEntry = smeshSO->GetID();
3602 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3606 //================================================================================
3608 * \brief Store a source sub-shape for which a counterpart not found and
3609 * a smesh object invalid due to that
3611 void AddInvalid( std::string geomEntry,
3612 SALOMEDS::SObject_wrap smeshSO )
3614 if ( !geomEntry.empty() )
3616 CORBA::String_var smeshEntry = smeshSO->GetID();
3617 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3621 //================================================================================
3623 * \brief Store a source sub-shape for which a counterpart not found and
3624 * a smesh object invalid due to that
3626 void AddInvalid( int oldGeomID,
3627 SALOMEDS::SObject_wrap smeshSO )
3629 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3630 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3633 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3634 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3636 SMESH_Comment geomName( typeName[ shapeType ]);
3637 geomName << " #" << oldGeomID;
3639 CORBA::String_var smeshEntry = smeshSO->GetID();
3640 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3643 //================================================================================
3645 * \brief Return entries of a source sub-shape for which a counterpart not found and
3646 * of smesh objects invalid due to that
3648 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3649 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3652 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3653 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3655 nbSO += 1 + entry2entrySet->second.size();
3657 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3658 theInvalidEntries->length ( nbSO );
3659 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3661 entry2entrySet = myInvalidMap.begin();
3662 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3664 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3666 std::set< std::string > & entrySet = entry2entrySet->second;
3667 std::set< std::string >::iterator entry = entrySet.begin();
3668 for ( ; entry != entrySet.end(); ++entry )
3670 theInvalidEntries[ iEntry++ ] = entry->c_str();
3672 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3673 if ( !so->_is_nil() )
3674 theInvalidMeshSObjects[ iSO++ ] = so;
3679 }; // struct ShapeMapper
3681 //================================================================================
3683 * \brief Append an item to a CORBA sequence
3685 template < class CORBA_seq, class ITEM >
3686 void append( CORBA_seq& seq, ITEM item )
3688 if ( !CORBA::is_nil( item ))
3690 seq->length( 1 + seq->length() );
3691 seq[ seq->length() - 1 ] = item;
3694 } // namespace // utils for CopyMeshWithGeom()
3696 //================================================================================
3698 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3699 * \param [in] sourceMesh - a mesh to copy
3700 * \param [in] newGeometry - a new geometry
3701 * \param [in] toCopyGroups - to create groups in the new mesh
3702 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3703 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3704 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3705 * \param [out] newMesh - return a new mesh
3706 * \param [out] newGroups - return new groups
3707 * \param [out] newSubmeshes - return new sub-meshes
3708 * \param [out] newHypotheses - return new algorithms and hypotheses
3709 * \param [out] invalidEntries - return study entries of objects whose
3710 * counterparts are not found in the newGeometry, followed by entries
3711 * of mesh sub-objects that are invalid because they depend on a not found
3712 * preceding sub-shape
3713 * \return CORBA::Boolean - is a success
3715 //================================================================================
3717 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3718 GEOM::GEOM_Object_ptr theNewGeometry,
3719 const char* theMeshName,
3720 CORBA::Boolean theToCopyGroups,
3721 CORBA::Boolean theToReuseHypotheses,
3722 CORBA::Boolean theToCopyElements,
3723 SMESH::SMESH_Mesh_out theNewMesh,
3724 SMESH::ListOfGroups_out theNewGroups,
3725 SMESH::submesh_array_out theNewSubmeshes,
3726 SMESH::ListOfHypothesis_out theNewHypotheses,
3727 SMESH::string_array_out theInvalidEntries)
3729 if ( CORBA::is_nil( theSourceMesh ) ||
3730 CORBA::is_nil( theNewGeometry ))
3731 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3733 if ( !theSourceMesh->HasShapeToMesh() )
3734 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3739 TPythonDump pyDump(this); // prevent dump from CreateMesh()
3741 theNewMesh = CreateMesh( theNewGeometry );
3742 theNewGroups = new SMESH::ListOfGroups();
3743 theNewSubmeshes = new SMESH::submesh_array();
3744 theNewHypotheses = new SMESH::ListOfHypothesis();
3745 theInvalidEntries = new SMESH::string_array();
3747 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3749 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3750 GEOM::GEOM_Object_var geom, newGeom;
3751 SALOMEDS::SObject_wrap so;
3753 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3754 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3757 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3759 // treat hypotheses of mesh and sub-meshes
3760 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3761 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3763 bool isSubMesh = ( iSM < smList->length() );
3766 // create a new sub-mesh
3767 SMESH::SMESH_subMesh_var newSM;
3768 geom = smList[iSM]->GetSubShape();
3769 so = ObjectToSObject( smList[iSM] );
3770 CORBA::String_var name;
3771 if ( !so->_is_nil() )
3772 name = so->GetName();
3773 newGeom = shapeMapper.FindNew( geom );
3774 if ( newGeom->_is_nil() )
3776 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3777 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3782 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3784 append( theNewSubmeshes, newSM );
3786 if ( newGeom->_is_nil() )
3787 continue; // don't assign hypotheses
3791 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3793 so = ObjectToSObject( theNewMesh );
3794 SetName( so, theMeshName, "Mesh" );
3797 // assign hypotheses
3798 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3799 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3801 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3802 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3804 // get geometry hyp depends on
3805 std::vector< std::string > entryArray;
3806 std::vector< int > subIDArray;
3807 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3809 if ( !theToReuseHypotheses || dependsOnGeom )
3811 // create a new hypothesis
3812 CORBA::String_var type = hyp->GetName();
3813 CORBA::String_var lib = hyp->GetLibName();
3814 CORBA::String_var data = hyp_i->SaveTo();
3817 hyp = CreateHypothesis( type, lib );
3818 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3819 hyp_i->LoadFrom( data.in() );
3820 append( theNewHypotheses, hyp );
3824 // update geometry hyp depends on
3825 if ( dependsOnGeom )
3827 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3829 if ( !entryArray[ iGeo ].empty() )
3831 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3832 if ( newEntry.empty() )
3835 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3836 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3838 entryArray[ iGeo ] = newEntry;
3841 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3843 if ( subIDArray[ iGeo ] > 0 )
3845 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3849 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3850 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3852 subIDArray[ iGeo ] = newID;
3855 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3859 CORBA::String_var errorText;
3860 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3861 if ( errorText.in()[0] )
3864 } // loop on hypotheses
3865 } // loop on sub-meshes and mesh
3868 // copy mesh elements, keeping IDs
3869 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3870 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3872 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3873 ::SMESH_MeshEditor::ElemFeatures elemData;
3875 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3876 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3877 /*vertexLast=*/false);
3878 while ( srcSMIt->more() )
3880 SMESH_subMesh* srcSM = srcSMIt->next();
3881 if ( srcSM->IsEmpty() )
3882 continue; // not yet computed
3883 int newID = shapeMapper.FindNewNotChanged( srcSM );
3887 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3888 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3889 while ( nIt->more() )
3891 SMESH_NodeXYZ node( nIt->next() );
3892 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3894 const SMDS_PositionPtr pos = node->GetPosition();
3895 const double* uv = pos->GetParameters();
3896 switch ( pos->GetTypeOfPosition() )
3898 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3899 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3900 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3901 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3905 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3906 while( eIt->more() )
3908 const SMDS_MeshElement* e = eIt->next();
3909 elemData.Init( e, /*basicOnly=*/false );
3910 elemData.SetID( e->GetID() );
3911 elemData.myNodes.resize( e->NbNodes() );
3912 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3914 for ( iN = 0; nnIt->more(); ++iN )
3916 const SMDS_MeshNode* srcNode = nnIt->next();
3917 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3918 if ( !elemData.myNodes[ iN ])
3921 if ( iN == elemData.myNodes.size() )
3922 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3923 newMeshDS->SetMeshElementOnShape( newElem, newID );
3925 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3926 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3929 newMeshDS->Modified();
3935 TStr2StrMap old2newGroupMap;
3937 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3939 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3940 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3941 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3943 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3944 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3945 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3947 CORBA::String_var name = groups[ i ]->GetName();
3948 SMESH::ElementType elemType = groups[ i ]->GetType();
3950 SMESH::SMESH_GroupBase_var newGroup;
3952 if ( !stdlGroup->_is_nil() )
3954 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3956 SMESH::smIdType_array_var elemIDs = stdlGroup->GetIDs();
3957 const bool isElem = ( elemType != SMESH::NODE );
3958 CORBA::ULong iE = 0;
3959 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3960 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3962 if ( iE < elemIDs->length() )
3964 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3965 stdlGroup->Add( elemIDs );
3966 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3970 else if ( !geomGroup->_is_nil() )
3972 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3973 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3974 if ( newGeom->_is_nil() )
3976 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3977 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3982 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3985 else if ( !fltrGroup->_is_nil() )
3987 // replace geometry in a filter
3988 SMESH::Filter_var filter = fltrGroup->GetFilter();
3989 SMESH::Filter::Criteria_var criteria;
3990 filter->GetCriteria( criteria.out() );
3992 bool isMissingGroup = false;
3993 std::vector< std::string > badEntries;
3995 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3997 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3998 switch ( criteria[ iCr ].Type )
4000 case SMESH::FT_BelongToMeshGroup:
4002 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
4003 btgg->SetGroupID( thresholdID );
4004 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
4005 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
4006 if ( refGroupSO->_is_nil() )
4008 CORBA::String_var refID = refGroupSO->GetID();
4009 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
4010 if ( o2nID == old2newGroupMap.end() )
4012 isMissingGroup = true; // corresponding new group not yet created
4015 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
4017 if ( o2nID->second.empty() ) // new referred group is invalid
4018 badEntries.push_back( refID.in() );
4021 case SMESH::FT_BelongToGeom:
4022 case SMESH::FT_BelongToPlane:
4023 case SMESH::FT_BelongToCylinder:
4024 case SMESH::FT_BelongToGenSurface:
4025 case SMESH::FT_LyingOnGeom:
4027 std::string newID = shapeMapper.FindNew( thresholdID );
4028 criteria[ iCr ].ThresholdID = newID.c_str();
4029 if ( newID.empty() )
4030 badEntries.push_back( thresholdID );
4033 case SMESH::FT_ConnectedElements:
4035 if ( thresholdID && thresholdID[0] )
4037 std::string newID = shapeMapper.FindNew( thresholdID );
4038 criteria[ iCr ].ThresholdID = newID.c_str();
4039 if ( newID.empty() )
4040 badEntries.push_back( thresholdID );
4046 } // loop on criteria
4048 if ( isMissingGroup && i < nbGroups )
4050 // to treat the group again
4051 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
4055 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
4056 newFilter->SetCriteria( criteria );
4058 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
4059 newFilter->UnRegister();
4061 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4062 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
4063 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
4065 if ( isMissingGroup ) // all groups treated but a referred groups still not found
4067 invalidSObjects.push_back( ObjectToSObject( newGroup ));
4070 if ( !badEntries.empty() )
4073 } // treat a group on filter
4075 append( theNewGroups, newGroup );
4077 // fill old2newGroupMap
4078 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4079 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4080 if ( !srcSO->_is_nil() )
4082 CORBA::String_var srcID, newID("");
4083 srcID = srcSO->GetID();
4084 if ( !newSO->_is_nil() )
4085 newID = newSO->GetID();
4086 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4087 std::string( newID.in() )));
4090 if ( newGroup->_is_nil() )
4095 newMeshDS->CompactMesh();
4098 if ( !theMeshName || !theMeshName[0] )
4100 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4101 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4102 CORBA::String_var oldName = soOld->GetName();
4103 SetName( soNew, oldName.in(), "Mesh" );
4105 // mark invalid objects
4106 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4108 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4109 highLightInvalid( invalidSObjects[i].in(), true );
4112 << theNewMesh << ", "
4113 << theNewGroups << ", "
4114 << *theNewSubmeshes.ptr() << ", "
4115 << *theNewHypotheses.ptr() << ", "
4116 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4117 << theSourceMesh << ", "
4118 << theNewGeometry << ", "
4119 << "'" << theMeshName << "', "
4120 << theToCopyGroups << ", "
4121 << theToReuseHypotheses << ", "
4122 << theToCopyElements << " )";
4124 SMESH_CATCH( SMESH::throwCorbaException );
4129 //================================================================================
4131 * \brief Get version of MED format being used.
4133 //================================================================================
4135 char* SMESH_Gen_i::GetMEDFileVersion()
4137 MED::TInt majeur, mineur, release;
4138 majeur = mineur = release = 0;
4139 MED::GetVersionRelease(majeur, mineur, release);
4140 std::ostringstream version;
4141 version << majeur << "." << mineur << "." << release;
4142 return CORBA::string_dup( version.str().c_str() );
4145 //================================================================================
4147 * SMESH_Gen_i::GetMEDVersion
4149 * Get MED version of the file by its name
4151 //================================================================================
4153 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4155 std::string version = MED::GetMEDVersion( theFileName );
4156 return CORBA::string_dup( version.c_str() );
4159 //================================================================================
4161 * SMESH_Gen_i::CheckCompatibility
4163 * Check compatibility of file with MED format being used, read only.
4165 //================================================================================
4167 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4169 return MED::CheckCompatibility( theFileName );
4172 //================================================================================
4174 * SMESH_Gen_i::CheckWriteCompatibility
4176 * Check compatibility of file with MED format being used, for append on write.
4178 //================================================================================
4180 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4182 return MED::CheckCompatibility( theFileName, true );
4185 //================================================================================
4187 * SMESH_Gen_i::GetMeshNames
4189 * Get names of meshes defined in file with the specified name
4191 //================================================================================
4192 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4195 SMESH::string_array_var aResult = new SMESH::string_array();
4196 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4198 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4200 aResult->length( aNbMeshes );
4201 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4202 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4203 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4206 return aResult._retn();
4209 //=============================================================================
4213 * Save SMESH module's data
4215 //=============================================================================
4217 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4222 Kernel_Utils::Localizer loc;
4224 if (!myStudyContext)
4227 // Store study contents as a set of python commands
4230 SALOMEDS::Study_var aStudy = getStudyServant();
4232 // Declare a byte stream
4233 SALOMEDS::TMPFile_var aStreamFile;
4235 // Obtain a temporary dir
4236 TCollection_AsciiString tmpDir =
4237 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4239 // Create a sequence of files processed
4240 SALOMEDS_Tool::ListOfFiles aFileSeq;
4241 aFileSeq.reserve( NUM_TMP_FILES );
4243 TCollection_AsciiString aStudyName( "" );
4245 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4247 // Set names of temporary files
4248 TCollection_AsciiString filename =
4249 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4250 TCollection_AsciiString meshfile =
4251 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4252 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4253 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4254 filename = tmpDir + filename;
4255 meshfile = tmpDir + meshfile;
4258 HDFdataset* aDataset;
4259 HDFgroup* aTopGroup;
4261 HDFgroup* aSubGroup;
4262 HDFgroup* aSubSubGroup;
4263 hdf_size aSize[ 1 ];
4266 //Remove the files if they exist: BugID: 11225
4267 #ifndef WIN32 /* unix functionality */
4268 TCollection_AsciiString cmd("rm -f \"");
4270 TCollection_AsciiString cmd("del /F \"");
4280 system(cmd.ToCString());
4282 // MED writer to be used by storage process
4283 DriverMED_W_SMESHDS_Mesh writer;
4284 writer.SetFile( meshfile.ToCString() );
4285 //writer.SetSaveNumbers( false ); // bos #24400 -- it leads to change of element IDs
4288 // SetStoreName() to groups before storing hypotheses to let them refer to
4289 // groups using "store name", which is "Group <group_persistent_id>"
4291 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4292 for ( ; itBig->More(); itBig->Next() ) {
4293 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4294 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4295 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4296 if ( !CORBA::is_nil( anObject ) ) {
4297 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4298 if ( !myMesh->_is_nil() ) {
4299 myMesh->Load(); // load from study file if not yet done
4300 TPythonDump pd(this); // not to dump GetGroups()
4301 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4302 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4304 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4307 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4308 int anId = myStudyContext->findId( string( objStr.in() ) );
4310 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4311 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4312 aGrpBaseDS->SetStoreName( grpName );
4322 // ---> create HDF file
4323 aFile = new HDFfile( (char*) filename.ToCString() );
4324 aFile->CreateOnDisk();
4326 // --> iterator for top-level objects
4327 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4328 for ( ; itBig->More(); itBig->Next() ) {
4329 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4331 // --> hypotheses root branch (only one for the study)
4332 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4333 // create hypotheses root HDF group
4334 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4335 aTopGroup->CreateOnDisk();
4337 // iterator for all hypotheses
4338 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4339 for ( ; it->More(); it->Next() ) {
4340 SALOMEDS::SObject_wrap mySObject = it->Value();
4341 CORBA::Object_var anObject = SObjectToObject( mySObject );
4342 if ( !CORBA::is_nil( anObject ) ) {
4343 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4344 if ( !myHyp->_is_nil() ) {
4345 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4347 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4348 std::string hypname = hn.in();
4349 std::string libname = ln.in();
4351 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4352 // WIN32 and ".so" for X-system) must be deleted
4353 int libname_len = libname.length();
4355 if( libname_len > 4 )
4356 libname.resize( libname_len - 4 );
4358 // PAL17753 (Regression: missing hypothesis in restored study)
4359 // "lib" also should be removed from the beginning
4360 if( libname_len > 6 )
4361 libname = libname.substr( 3, libname_len - 3 - 3 );
4363 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4364 CORBA::String_var hypdata = myImpl->SaveTo();
4365 int id = myStudyContext->findId( string( objStr.in() ));
4367 // for each hypothesis create HDF group basing on its id
4368 char hypGrpName[30];
4369 sprintf( hypGrpName, "Hypothesis %d", id );
4370 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4371 aGroup->CreateOnDisk();
4372 // --> type name of hypothesis
4373 aSize[ 0 ] = hypname.length() + 1;
4374 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4375 aDataset->CreateOnDisk();
4376 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4377 aDataset->CloseOnDisk();
4378 // --> server plugin library name of hypothesis
4379 aSize[ 0 ] = libname.length() + 1;
4380 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4381 aDataset->CreateOnDisk();
4382 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4383 aDataset->CloseOnDisk();
4384 // --> persistent data of hypothesis
4385 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4386 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4387 aDataset->CreateOnDisk();
4388 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4389 aDataset->CloseOnDisk();
4390 // close hypothesis HDF group
4391 aGroup->CloseOnDisk();
4396 // close hypotheses root HDF group
4397 aTopGroup->CloseOnDisk();
4399 // --> algorithms root branch (only one for the study)
4400 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4401 // create algorithms root HDF group
4402 aTopGroup = new HDFgroup( "Algorithms", aFile );
4403 aTopGroup->CreateOnDisk();
4405 // iterator for all algorithms
4406 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4407 for ( ; it->More(); it->Next() ) {
4408 SALOMEDS::SObject_wrap mySObject = it->Value();
4409 CORBA::Object_var anObject = SObjectToObject( mySObject );
4410 if ( !CORBA::is_nil( anObject ) ) {
4411 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4412 if ( !myHyp->_is_nil() ) {
4413 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4415 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4416 std::string hypname = hn.in();
4417 std::string libname = ln.in();
4419 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4420 // WIN32 and ".so" for X-system) must be deleted
4421 int libname_len = libname.length();
4423 if( libname_len > 4 )
4424 libname.resize( libname_len - 4 );
4426 // PAL17753 (Regression: missing hypothesis in restored study)
4427 // "lib" also should be removed from the beginning
4428 if( libname_len > 6 )
4429 libname = libname.substr( 3, libname_len - 3 - 3 );
4431 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4432 CORBA::String_var hypdata = myImpl->SaveTo();
4433 int id = myStudyContext->findId( string( objStr.in() ) );
4435 // for each algorithm create HDF group basing on its id
4436 char hypGrpName[30];
4437 sprintf( hypGrpName, "Algorithm %d", id );
4438 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4439 aGroup->CreateOnDisk();
4440 // --> type name of algorithm
4441 aSize[0] = hypname.length() + 1;
4442 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4443 aDataset->CreateOnDisk();
4444 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4445 aDataset->CloseOnDisk();
4446 // --> server plugin library name of hypothesis
4447 aSize[0] = libname.length() + 1;
4448 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4449 aDataset->CreateOnDisk();
4450 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4451 aDataset->CloseOnDisk();
4452 // --> persistent data of algorithm
4453 aSize[0] = strlen( hypdata.in() ) + 1;
4454 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4455 aDataset->CreateOnDisk();
4456 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4457 aDataset->CloseOnDisk();
4458 // close algorithm HDF group
4459 aGroup->CloseOnDisk();
4464 // close algorithms root HDF group
4465 aTopGroup->CloseOnDisk();
4467 // --> mesh objects roots branches
4468 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4469 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4470 if ( !CORBA::is_nil( anObject ) ) {
4471 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4472 if ( !myMesh->_is_nil() ) {
4473 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4475 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4476 int id = myStudyContext->findId( string( objStr.in() ) );
4477 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4478 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4479 bool hasShape = myLocMesh.HasShapeToMesh();
4481 // for each mesh open the HDF group basing on its id
4482 char meshGrpName[ 30 ];
4483 sprintf( meshGrpName, "Mesh %d", id );
4484 aTopGroup = new HDFgroup( meshGrpName, aFile );
4485 aTopGroup->CreateOnDisk();
4487 // --> put dataset to hdf file which is a flag that mesh has data
4488 string strHasData = "0";
4489 // check if the mesh is not empty
4490 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4491 // write mesh data to med file
4492 writer.SetMesh( mySMESHDSMesh );
4493 writer.SetMeshId( id );
4496 aSize[ 0 ] = strHasData.length() + 1;
4497 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4498 aDataset->CreateOnDisk();
4499 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4500 aDataset->CloseOnDisk();
4503 // for each mesh open the HDF group basing on its auto color parameter
4504 char meshAutoColorName[ 30 ];
4505 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4507 anAutoColor[0] = myImpl->GetAutoColor();
4509 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4510 aDataset->CreateOnDisk();
4511 aDataset->WriteOnDisk( anAutoColor );
4512 aDataset->CloseOnDisk();
4514 // issue 0020693. Store _isModified flag
4515 int isModified = myLocMesh.GetIsModified();
4517 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4518 aDataset->CreateOnDisk();
4519 aDataset->WriteOnDisk( &isModified );
4520 aDataset->CloseOnDisk();
4522 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4523 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4525 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4526 aDataset->CreateOnDisk();
4527 aDataset->WriteOnDisk( &meshPersistentId );
4528 aDataset->CloseOnDisk();
4530 // Store SMESH_Mesh_i::_mainShapeTick
4531 int shapeTick = myImpl->MainShapeTick();
4533 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4534 aDataset->CreateOnDisk();
4535 aDataset->WriteOnDisk( &shapeTick );
4536 aDataset->CloseOnDisk();
4538 // write reference on a shape if exists
4539 SALOMEDS::SObject_wrap myRef;
4540 bool shapeRefFound = false;
4541 bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4543 SALOMEDS::SObject_wrap myShape;
4544 bool ok = myRef->ReferencedObject( myShape.inout() );
4546 CORBA::Object_var shapeObj = myShape->GetObject();
4547 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4548 CORBA::String_var myRefOnObject = myShape->GetID();
4549 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4550 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4551 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4552 aDataset->CreateOnDisk();
4553 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4554 aDataset->CloseOnDisk();
4560 std::string info = myImpl->FileInfoToString();
4561 if ( !info.empty() )
4563 aSize[ 0 ] = info.size();
4564 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4565 aDataset->CreateOnDisk();
4566 aDataset->WriteOnDisk( (char*) info.data() );
4567 aDataset->CloseOnDisk();
4570 // write applied hypotheses if exist
4571 SALOMEDS::SObject_wrap myHypBranch;
4572 found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4573 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4574 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4576 if ( found && (shapeRefFound || !hasShape) ) {
4577 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4578 aGroup->CreateOnDisk();
4580 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4582 for ( ; it->More(); it->Next() ) {
4583 SALOMEDS::SObject_wrap mySObject = it->Value();
4584 SALOMEDS::SObject_wrap myRefOnHyp;
4585 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4587 // san - it is impossible to recover applied hypotheses
4588 // using their entries within Load() method,
4589 // for there are no AttributeIORs in the study when Load() is working.
4590 // Hence, it is better to store persistent IDs of hypotheses as references to them
4592 //string myRefOnObject = myRefOnHyp->GetID();
4593 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4594 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4595 int id = myStudyContext->findId( string( objStr.in() ) );
4596 //if ( myRefOnObject.length() > 0 ) {
4597 //aSize[ 0 ] = myRefOnObject.length() + 1;
4598 char hypName[ 30 ], hypId[ 30 ];
4599 sprintf( hypName, "Hyp %d", ++hypNb );
4600 sprintf( hypId, "%d", id );
4601 aSize[ 0 ] = strlen( hypId ) + 1;
4602 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4603 aDataset->CreateOnDisk();
4604 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4605 aDataset->WriteOnDisk( hypId );
4606 aDataset->CloseOnDisk();
4610 aGroup->CloseOnDisk();
4613 // write applied algorithms if exist
4614 SALOMEDS::SObject_wrap myAlgoBranch;
4615 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4616 myAlgoBranch.inout() );
4617 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4618 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4620 if ( found && (shapeRefFound || !hasShape)) {
4621 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4622 aGroup->CreateOnDisk();
4624 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4626 for ( ; it->More(); it->Next() ) {
4627 SALOMEDS::SObject_wrap mySObject = it->Value();
4628 SALOMEDS::SObject_wrap myRefOnAlgo;
4629 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4631 // san - it is impossible to recover applied algorithms
4632 // using their entries within Load() method,
4633 // for there are no AttributeIORs in the study when Load() is working.
4634 // Hence, it is better to store persistent IDs of algorithms as references to them
4636 //string myRefOnObject = myRefOnAlgo->GetID();
4637 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4638 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4639 int id = myStudyContext->findId( string( objStr.in() ) );
4640 //if ( myRefOnObject.length() > 0 ) {
4641 //aSize[ 0 ] = myRefOnObject.length() + 1;
4642 char algoName[ 30 ], algoId[ 30 ];
4643 sprintf( algoName, "Algo %d", ++algoNb );
4644 sprintf( algoId, "%d", id );
4645 aSize[ 0 ] = strlen( algoId ) + 1;
4646 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4647 aDataset->CreateOnDisk();
4648 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4649 aDataset->WriteOnDisk( algoId );
4650 aDataset->CloseOnDisk();
4654 aGroup->CloseOnDisk();
4657 // --> submesh objects sub-branches
4659 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4660 SALOMEDS::SObject_wrap mySubmeshBranch;
4661 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4663 if ( found ) // check if there is shape reference in submeshes
4665 bool hasShapeRef = false;
4666 SALOMEDS::ChildIterator_wrap itSM =
4667 aStudy->NewChildIterator( mySubmeshBranch );
4668 for ( ; itSM->More(); itSM->Next() ) {
4669 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4670 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4671 mySubRef->ReferencedObject( myShape.inout() );
4672 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4675 { // remove one submesh
4676 if ( shapeRefFound )
4677 { // unassign hypothesis
4678 SMESH::SMESH_subMesh_var mySubMesh =
4679 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4680 if ( !mySubMesh->_is_nil() ) {
4681 int shapeID = mySubMesh->GetId();
4682 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4683 const list<const SMESHDS_Hypothesis*>& hypList =
4684 mySMESHDSMesh->GetHypothesis( S );
4685 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4686 while ( hyp != hypList.end() ) {
4687 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4688 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4692 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4694 } // loop on submeshes of a type
4695 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4696 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4699 } // end check if there is shape reference in submeshes
4701 char name_meshgroup[ 30 ];
4702 if ( i == GetSubMeshOnVertexTag() )
4703 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4704 else if ( i == GetSubMeshOnEdgeTag() )
4705 strcpy( name_meshgroup, "SubMeshes On Edge" );
4706 else if ( i == GetSubMeshOnWireTag() )
4707 strcpy( name_meshgroup, "SubMeshes On Wire" );
4708 else if ( i == GetSubMeshOnFaceTag() )
4709 strcpy( name_meshgroup, "SubMeshes On Face" );
4710 else if ( i == GetSubMeshOnShellTag() )
4711 strcpy( name_meshgroup, "SubMeshes On Shell" );
4712 else if ( i == GetSubMeshOnSolidTag() )
4713 strcpy( name_meshgroup, "SubMeshes On Solid" );
4714 else if ( i == GetSubMeshOnCompoundTag() )
4715 strcpy( name_meshgroup, "SubMeshes On Compound" );
4717 // for each type of submeshes create container HDF group
4718 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4719 aGroup->CreateOnDisk();
4721 // iterator for all submeshes of given type
4722 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4723 for ( ; itSM->More(); itSM->Next() ) {
4724 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4725 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4726 if ( !CORBA::is_nil( anSubObject ))
4728 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4729 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4730 int subid = myStudyContext->findId( string( objStr.in() ) );
4732 // for each mesh open the HDF group basing on its id
4733 char submeshGrpName[ 30 ];
4734 sprintf( submeshGrpName, "SubMesh %d", subid );
4735 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4736 aSubGroup->CreateOnDisk();
4738 // write reference on a shape, already checked if it exists
4739 SALOMEDS::SObject_wrap mySubRef, myShape;
4740 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4741 mySubRef->ReferencedObject( myShape.inout() );
4742 string myRefOnObject = myShape->GetID();
4743 if ( myRefOnObject.length() > 0 ) {
4744 aSize[ 0 ] = myRefOnObject.length() + 1;
4745 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4746 aDataset->CreateOnDisk();
4747 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4748 aDataset->CloseOnDisk();
4751 // write applied hypotheses if exist
4752 SALOMEDS::SObject_wrap mySubHypBranch;
4753 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4754 mySubHypBranch.inout() );
4756 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4757 aSubSubGroup->CreateOnDisk();
4759 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4761 for ( ; it->More(); it->Next() ) {
4762 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4763 SALOMEDS::SObject_wrap myRefOnHyp;
4764 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4766 //string myRefOnObject = myRefOnHyp->GetID();
4767 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4768 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4769 int id = myStudyContext->findId( string( objStr.in() ) );
4770 //if ( myRefOnObject.length() > 0 ) {
4771 //aSize[ 0 ] = myRefOnObject.length() + 1;
4772 char hypName[ 30 ], hypId[ 30 ];
4773 sprintf( hypName, "Hyp %d", ++hypNb );
4774 sprintf( hypId, "%d", id );
4775 aSize[ 0 ] = strlen( hypId ) + 1;
4776 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4777 aDataset->CreateOnDisk();
4778 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4779 aDataset->WriteOnDisk( hypId );
4780 aDataset->CloseOnDisk();
4784 aSubSubGroup->CloseOnDisk();
4787 // write applied algorithms if exist
4788 SALOMEDS::SObject_wrap mySubAlgoBranch;
4789 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4790 mySubAlgoBranch.inout() );
4792 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4793 aSubSubGroup->CreateOnDisk();
4795 SALOMEDS::ChildIterator_wrap it =
4796 aStudy->NewChildIterator( mySubAlgoBranch );
4798 for ( ; it->More(); it->Next() ) {
4799 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4800 SALOMEDS::SObject_wrap myRefOnAlgo;
4801 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4803 //string myRefOnObject = myRefOnAlgo->GetID();
4804 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4805 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4806 int id = myStudyContext->findId( string( objStr.in() ) );
4807 //if ( myRefOnObject.length() > 0 ) {
4808 //aSize[ 0 ] = myRefOnObject.length() + 1;
4809 char algoName[ 30 ], algoId[ 30 ];
4810 sprintf( algoName, "Algo %d", ++algoNb );
4811 sprintf( algoId, "%d", id );
4812 aSize[ 0 ] = strlen( algoId ) + 1;
4813 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4814 aDataset->CreateOnDisk();
4815 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4816 aDataset->WriteOnDisk( algoId );
4817 aDataset->CloseOnDisk();
4821 aSubSubGroup->CloseOnDisk();
4823 // close submesh HDF group
4824 aSubGroup->CloseOnDisk();
4827 // close container of submeshes by type HDF group
4828 aGroup->CloseOnDisk();
4832 // store submesh order if any
4833 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4834 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4835 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4836 char order_list[ 30 ];
4837 strcpy( order_list, "Mesh Order" );
4838 // count number of submesh ids
4840 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4841 for ( ; idIt != theOrderIds.end(); idIt++ )
4842 nbIDs += (*idIt).size();
4843 // number of values = number of IDs +
4844 // number of lists (for separators) - 1
4845 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4846 idIt = theOrderIds.begin();
4847 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4848 const TListOfInt& idList = *idIt;
4849 if (idIt != theOrderIds.begin()) // not first list
4850 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4851 // dump submesh ids from current list
4852 TListOfInt::const_iterator id_smId = idList.begin();
4853 for( ; id_smId != idList.end(); id_smId++ )
4854 smIDs[ i++ ] = *id_smId;
4857 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4859 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4860 aDataset->CreateOnDisk();
4861 aDataset->WriteOnDisk( smIDs );
4862 aDataset->CloseOnDisk();
4866 if ( !theOrderIds.empty() && isNewOrederVersion )
4868 // convert ids to entries
4869 std::list< std::list< std::string > > orderEntryLists;
4870 for ( const TListOfInt& idList : theOrderIds )
4872 orderEntryLists.emplace_back();
4873 std::list< std::string > & entryList = orderEntryLists.back();
4874 for ( const int& id : idList )
4876 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4877 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4878 SALOMEDS::SObject_var so = ObjectToSObject( go );
4879 if ( !so->_is_nil() )
4881 CORBA::String_var entry = so->GetID();
4882 entryList.emplace_back( entry.in() );
4886 // convert orderEntryLists to string
4887 std::ostringstream ostream;
4888 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4889 std::string orderEntryString = ostream.str();
4892 aSize[ 0 ] = orderEntryString.size() + 1;
4893 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4894 aDataset->CreateOnDisk();
4895 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4896 aDataset->CloseOnDisk();
4899 // groups root sub-branch
4900 SALOMEDS::SObject_wrap myGroupsBranch;
4901 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4902 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4904 char name_group[ 30 ];
4905 if ( i == GetNodeGroupsTag() )
4906 strcpy( name_group, "Groups of Nodes" );
4907 else if ( i == GetEdgeGroupsTag() )
4908 strcpy( name_group, "Groups of Edges" );
4909 else if ( i == GetFaceGroupsTag() )
4910 strcpy( name_group, "Groups of Faces" );
4911 else if ( i == GetVolumeGroupsTag() )
4912 strcpy( name_group, "Groups of Volumes" );
4913 else if ( i == Get0DElementsGroupsTag() )
4914 strcpy( name_group, "Groups of 0D Elements" );
4915 else if ( i == GetBallElementsGroupsTag() )
4916 strcpy( name_group, "Groups of Balls" );
4918 aGroup = new HDFgroup( name_group, aTopGroup );
4919 aGroup->CreateOnDisk();
4921 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4922 for ( ; it->More(); it->Next() ) {
4923 SALOMEDS::SObject_wrap mySObject = it->Value();
4924 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4925 if ( !CORBA::is_nil( aSubObject ) ) {
4926 SMESH_GroupBase_i* myGroupImpl =
4927 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4930 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4934 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4935 int anId = myStudyContext->findId( string( objStr.in() ) );
4937 // For each group, create a dataset named "Group <group_persistent_id>"
4938 // and store the group's user name into it
4939 const char* grpName = aGrpBaseDS->GetStoreName();
4940 CORBA::String_var aUserName = myGroupImpl->GetName();
4941 aSize[ 0 ] = strlen( aUserName ) + 1;
4943 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4944 aDataset->CreateOnDisk();
4945 aDataset->WriteOnDisk( aUserName );
4946 aDataset->CloseOnDisk();
4949 // For each group, create a dataset named "Group <group_persistent_id> Color"
4950 // and store the group's color into it
4951 char grpColorName[ 30 ];
4952 sprintf( grpColorName, "ColorGroup %d", anId );
4953 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4955 anRGB[ 0 ] = aColor.R;
4956 anRGB[ 1 ] = aColor.G;
4957 anRGB[ 2 ] = aColor.B;
4959 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4960 aDataset->CreateOnDisk();
4961 aDataset->WriteOnDisk( anRGB );
4962 aDataset->CloseOnDisk();
4964 // Pass SMESHDS_Group to MED writer
4965 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4967 writer.AddGroup( aGrpDS );
4969 // write reference on a shape if exists
4970 SMESHDS_GroupOnGeom* aGeomGrp =
4971 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4973 SALOMEDS::SObject_wrap mySubRef, myShape;
4974 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4975 mySubRef->ReferencedObject( myShape.inout() ) &&
4976 !CORBA::is_nil( myShape->GetObject() ))
4978 CORBA::String_var myRefOnObject = myShape->GetID();
4979 if ( myRefOnObject.in()[0] ) {
4980 char aRefName[ 30 ];
4981 sprintf( aRefName, "Ref on shape %d", anId);
4982 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4983 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4984 aDataset->CreateOnDisk();
4985 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4986 aDataset->CloseOnDisk();
4989 else // shape ref is invalid:
4991 // save a group on geometry as ordinary group
4992 writer.AddGroup( aGeomGrp );
4995 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4996 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4998 std::string str = aFilterGrp_i->FilterToString();
4999 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
5000 aSize[ 0 ] = str.length() + 1;
5001 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
5002 aDataset->CreateOnDisk();
5003 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
5004 aDataset->CloseOnDisk();
5008 aGroup->CloseOnDisk();
5012 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
5014 // Flush current mesh information into MED file
5017 // save info on nb of elements
5018 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
5020 // maybe a shape was deleted in the study
5021 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
5022 TopoDS_Shape nullShape;
5023 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
5026 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
5031 aGroup = new HDFgroup( "Submeshes", aTopGroup );
5032 aGroup->CreateOnDisk();
5034 // each element belongs to one or none submesh,
5035 // so for each node/element, we store a submesh ID
5037 // Store submesh IDs
5038 for ( int isNode = 0; isNode < 2; ++isNode )
5040 SMDS_ElemIteratorPtr eIt =
5041 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
5042 smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
5045 std::vector<int> smIDs; smIDs.reserve( nbElems );
5046 while ( eIt->more() )
5047 if ( const SMDS_MeshElement* e = eIt->next())
5048 smIDs.push_back( e->getshapeId() );
5050 aSize[ 0 ] = nbElems;
5051 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
5052 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5053 aDataset->CreateOnDisk();
5054 aDataset->WriteOnDisk( & smIDs[0] );
5055 aDataset->CloseOnDisk();
5058 aGroup->CloseOnDisk();
5060 // Store node positions on sub-shapes (SMDS_Position):
5061 // ----------------------------------------------------
5063 aGroup = new HDFgroup( "Node Positions", aTopGroup );
5064 aGroup->CreateOnDisk();
5066 // in aGroup, create 5 datasets to contain:
5067 // "Nodes on Edges" - ID of node on edge
5068 // "Edge positions" - U parameter on node on edge
5069 // "Nodes on Faces" - ID of node on face
5070 // "Face U positions" - U parameter of node on face
5071 // "Face V positions" - V parameter of node on face
5073 // Find out nb of nodes on edges and faces
5074 // Collect corresponding sub-meshes
5075 int nbEdgeNodes = 0, nbFaceNodes = 0;
5076 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5077 // loop on SMESHDS_SubMesh'es
5078 while ( smIt->more() )
5080 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5081 if ( aSubMesh->IsComplexSubmesh() )
5082 continue; // submesh containing other submeshs
5083 smIdType nbNodes = aSubMesh->NbNodes();
5084 if ( nbNodes == 0 ) continue;
5086 int aShapeID = aSubMesh->GetID();
5087 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5089 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5090 // write only SMDS_FacePosition and SMDS_EdgePosition
5091 switch ( aShapeType ) {
5093 nbFaceNodes += nbNodes;
5094 aFaceSM.push_back( aSubMesh );
5097 nbEdgeNodes += nbNodes;
5098 aEdgeSM.push_back( aSubMesh );
5104 // Treat positions on edges or faces
5105 for ( int onFace = 0; onFace < 2; onFace++ )
5107 // Create arrays to store in datasets
5108 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5109 if (!nbNodes) continue;
5110 int* aNodeIDs = new int [ nbNodes ];
5111 double* aUPos = new double [ nbNodes ];
5112 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5115 // loop on sub-meshes
5116 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5117 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5118 for ( ; itSM != pListSM->end(); itSM++ )
5120 SMESHDS_SubMesh* aSubMesh = (*itSM);
5122 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5123 // loop on nodes in aSubMesh
5124 while ( itNode->more() )
5127 const SMDS_MeshNode* node = itNode->next();
5128 aNodeIDs [ iNode ] = node->GetID();
5131 const SMDS_PositionPtr pos = node->GetPosition();
5132 if ( onFace ) { // on FACE
5133 SMDS_FacePositionPtr fPos = pos;
5135 aUPos[ iNode ] = fPos->GetUParameter();
5136 aVPos[ iNode ] = fPos->GetVParameter();
5143 SMDS_EdgePositionPtr ePos = pos;
5145 aUPos[ iNode ] = ePos->GetUParameter();
5151 } // loop on nodes in aSubMesh
5152 } // loop on sub-meshes
5157 aSize[ 0 ] = nbNodes;
5159 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5160 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5161 aDataset->CreateOnDisk();
5162 aDataset->WriteOnDisk( aNodeIDs );
5163 aDataset->CloseOnDisk();
5166 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5167 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5168 aDataset->CreateOnDisk();
5169 aDataset->WriteOnDisk( aUPos );
5170 aDataset->CloseOnDisk();
5173 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5174 aDataset->CreateOnDisk();
5175 aDataset->WriteOnDisk( aVPos );
5176 aDataset->CloseOnDisk();
5181 if ( aVPos ) delete [] aVPos;
5183 } // treat positions on edges or faces
5185 // close "Node Positions" group
5186 aGroup->CloseOnDisk();
5188 } // if ( there are submeshes in SMESHDS_Mesh )
5191 // close mesh HDF group
5192 aTopGroup->CloseOnDisk();
5200 aFile->CloseOnDisk();
5203 // Convert temporary files to stream
5204 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5206 // Remove temporary files and directory
5208 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5210 return aStreamFile._retn();
5213 //=============================================================================
5215 * SMESH_Gen_i::SaveASCII
5217 * Save SMESH module's data in ASCII format
5219 //=============================================================================
5221 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5223 bool isMultiFile ) {
5224 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5225 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5226 return aStreamFile._retn();
5228 //after usual saving needs to encipher binary to text string
5229 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5230 int size = aStreamFile.in().length();
5231 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5232 for ( int i = 0; i < size; i++ )
5233 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5235 buffer[size * 3] = '\0';
5237 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5239 return anAsciiStreamFile._retn();
5242 //=============================================================================
5246 * Load SMESH module's data
5248 //=============================================================================
5250 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5251 const SALOMEDS::TMPFile& theStream,
5255 UpdateStudy(); // load geom data
5256 Kernel_Utils::Localizer loc;
5258 SALOMEDS::Study_var aStudy = getStudyServant();
5260 // Get temporary files location
5261 TCollection_AsciiString tmpDir =
5262 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5264 // Convert the stream into sequence of files to process
5265 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5268 TCollection_AsciiString aStudyName( "" );
5269 if ( isMultiFile ) {
5270 CORBA::WString_var url = aStudy->URL();
5271 SMESHUtils::ArrayDeleter<const char> urlMulibyte( Kernel_Utils::encode( url.in()) );
5272 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( urlMulibyte.get() ).c_str();
5274 // Set names of temporary files
5275 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5276 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5280 HDFdataset* aDataset;
5281 HDFgroup* aTopGroup;
5283 HDFgroup* aSubGroup;
5284 HDFgroup* aSubSubGroup;
5287 // ---> open HDF file
5288 aFile = new HDFfile( (char*) filename.ToCString() );
5290 aFile->OpenOnDisk( HDF_RDONLY );
5292 catch ( HDFexception ) {
5293 INFOS( "Load(): " << filename << " not found!" );
5297 TPythonDump pd(this); // prevent dump during loading
5299 // For PAL13473 ("Repetitive mesh") implementation.
5300 // New dependencies between SMESH objects are established:
5301 // now hypotheses can refer to meshes, shapes and other hypotheses.
5302 // To keep data consistent, the following order of data restoration
5304 // 1. Create hypotheses
5305 // 2. Create all meshes
5306 // 3. Load hypotheses' data
5309 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5310 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5311 list< SMESH::Filter_var > filters;
5313 // get total number of top-level groups
5314 int aNbGroups = aFile->nInternalObjects();
5315 if ( aNbGroups > 0 ) {
5316 // --> in first turn we should read&create hypotheses
5317 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5318 // open hypotheses root HDF group
5319 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5320 aTopGroup->OpenOnDisk();
5322 // get number of hypotheses
5323 int aNbObjects = aTopGroup->nInternalObjects();
5324 for ( int j = 0; j < aNbObjects; j++ ) {
5325 // try to identify hypothesis
5326 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5327 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5329 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5330 // open hypothesis group
5331 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5332 aGroup->OpenOnDisk();
5334 // --> get hypothesis id
5335 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5340 // get number of datasets
5341 int aNbSubObjects = aGroup->nInternalObjects();
5342 for ( int k = 0; k < aNbSubObjects; k++ ) {
5344 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5345 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5346 // --> get hypothesis name
5347 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5348 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5349 aDataset->OpenOnDisk();
5350 size = aDataset->GetSize();
5351 char* hypname_str = new char[ size ];
5352 aDataset->ReadFromDisk( hypname_str );
5353 hypname = string( hypname_str );
5354 delete [] hypname_str;
5355 aDataset->CloseOnDisk();
5357 // --> get hypothesis plugin library name
5358 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5359 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5360 aDataset->OpenOnDisk();
5361 size = aDataset->GetSize();
5362 char* libname_str = new char[ size ];
5363 aDataset->ReadFromDisk( libname_str );
5364 if(MYDEBUG) SCRUTE( libname_str );
5365 libname = string( libname_str );
5366 delete [] libname_str;
5367 aDataset->CloseOnDisk();
5369 // --> get hypothesis data
5370 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5371 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5372 aDataset->OpenOnDisk();
5373 size = aDataset->GetSize();
5374 char* hypdata_str = new char[ size ];
5375 aDataset->ReadFromDisk( hypdata_str );
5376 hypdata = string( hypdata_str );
5377 delete [] hypdata_str;
5378 aDataset->CloseOnDisk();
5381 // close hypothesis HDF group
5382 aGroup->CloseOnDisk();
5384 // --> restore hypothesis from data
5385 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5386 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5387 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5388 SMESH::SMESH_Hypothesis_var myHyp;
5390 try { // protect persistence mechanism against exceptions
5391 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5394 INFOS( "Exception during hypothesis creation" );
5397 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5399 // myImpl->LoadFrom( hypdata.c_str() );
5400 hypDataList.push_back( make_pair( myImpl, hypdata ));
5401 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5402 int newId = myStudyContext->findId( iorString.in() );
5403 myStudyContext->mapOldToNew( id, newId );
5406 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5410 // close hypotheses root HDF group
5411 aTopGroup->CloseOnDisk();
5415 // --> then we should read&create algorithms
5416 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5417 // open algorithms root HDF group
5418 aTopGroup = new HDFgroup( "Algorithms", aFile );
5419 aTopGroup->OpenOnDisk();
5421 // get number of algorithms
5422 int aNbObjects = aTopGroup->nInternalObjects();
5423 for ( int j = 0; j < aNbObjects; j++ ) {
5424 // try to identify algorithm
5425 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5426 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5428 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5429 // open algorithm group
5430 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5431 aGroup->OpenOnDisk();
5433 // --> get algorithm id
5434 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5439 // get number of datasets
5440 int aNbSubObjects = aGroup->nInternalObjects();
5441 for ( int k = 0; k < aNbSubObjects; k++ ) {
5443 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5444 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5445 // --> get algorithm name
5446 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5447 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5448 aDataset->OpenOnDisk();
5449 size = aDataset->GetSize();
5450 char* hypname_str = new char[ size ];
5451 aDataset->ReadFromDisk( hypname_str );
5452 hypname = string( hypname_str );
5453 delete [] hypname_str;
5454 aDataset->CloseOnDisk();
5456 // --> get algorithm plugin library name
5457 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5458 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5459 aDataset->OpenOnDisk();
5460 size = aDataset->GetSize();
5461 char* libname_str = new char[ size ];
5462 aDataset->ReadFromDisk( libname_str );
5463 if(MYDEBUG) SCRUTE( libname_str );
5464 libname = string( libname_str );
5465 delete [] libname_str;
5466 aDataset->CloseOnDisk();
5468 // --> get algorithm data
5469 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5470 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5471 aDataset->OpenOnDisk();
5472 size = aDataset->GetSize();
5473 char* hypdata_str = new char[ size ];
5474 aDataset->ReadFromDisk( hypdata_str );
5475 if(MYDEBUG) SCRUTE( hypdata_str );
5476 hypdata = string( hypdata_str );
5477 delete [] hypdata_str;
5478 aDataset->CloseOnDisk();
5481 // close algorithm HDF group
5482 aGroup->CloseOnDisk();
5484 // --> restore algorithm from data
5485 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5486 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5487 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5488 SMESH::SMESH_Hypothesis_var myHyp;
5490 try { // protect persistence mechanism against exceptions
5491 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5493 catch( SALOME::SALOME_Exception& ex )
5495 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5498 INFOS( "Exception during hypothesis creation" );
5501 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5503 //myImpl->LoadFrom( hypdata.c_str() );
5504 hypDataList.push_back( make_pair( myImpl, hypdata ));
5505 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5506 int newId = myStudyContext->findId( iorString.in() );
5507 myStudyContext->mapOldToNew( id, newId );
5510 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5514 // close algorithms root HDF group
5515 aTopGroup->CloseOnDisk();
5519 // --> the rest groups should be meshes
5520 for ( int i = 0; i < aNbGroups; i++ ) {
5521 // identify next group
5522 char meshName[ HDF_NAME_MAX_LEN+1 ];
5523 aFile->InternalObjectIndentify( i, meshName );
5525 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5527 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5531 // open mesh HDF group
5532 aTopGroup = new HDFgroup( meshName, aFile );
5533 aTopGroup->OpenOnDisk();
5535 // get number of child HDF objects
5536 int aNbObjects = aTopGroup->nInternalObjects();
5537 if ( aNbObjects > 0 ) {
5539 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5540 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5541 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5542 if ( !myNewMeshImpl )
5544 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5546 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5547 int newId = myStudyContext->findId( iorString.in() );
5548 myStudyContext->mapOldToNew( id, newId );
5551 // try to read and set auto color flag
5552 char aMeshAutoColorName[ 30 ];
5553 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5554 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5556 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5557 aDataset->OpenOnDisk();
5558 size = aDataset->GetSize();
5559 int* anAutoColor = new int[ size ];
5560 aDataset->ReadFromDisk( anAutoColor );
5561 aDataset->CloseOnDisk();
5562 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5563 delete [] anAutoColor;
5566 // try to read and set reference to shape
5567 GEOM::GEOM_Object_var aShapeObject;
5568 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5569 // load mesh "Ref on shape" - it's an entry to SObject
5570 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5571 aDataset->OpenOnDisk();
5572 size = aDataset->GetSize();
5573 char* refFromFile = new char[ size ];
5574 aDataset->ReadFromDisk( refFromFile );
5575 aDataset->CloseOnDisk();
5576 if ( strlen( refFromFile ) > 0 ) {
5577 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5578 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5579 if ( !CORBA::is_nil( shapeObject ) ) {
5580 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5581 if ( !aShapeObject->_is_nil() )
5582 myNewMeshImpl->SetShape( aShapeObject );
5585 delete [] refFromFile;
5588 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5589 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5591 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5592 aDataset->OpenOnDisk();
5593 size = aDataset->GetSize();
5594 int* meshPersistentId = new int[ size ];
5595 aDataset->ReadFromDisk( meshPersistentId );
5596 aDataset->CloseOnDisk();
5597 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5598 delete [] meshPersistentId;
5601 // Restore SMESH_Mesh_i::_mainShapeTick
5602 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5604 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5605 aDataset->OpenOnDisk();
5606 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5607 aDataset->ReadFromDisk( shapeTick );
5608 aDataset->CloseOnDisk();
5611 // Restore file info
5612 if ( aTopGroup->ExistInternalObject( "file info" ))
5614 aDataset = new HDFdataset( "file info", aTopGroup );
5615 aDataset->OpenOnDisk();
5616 size = aDataset->GetSize();
5617 std::string info( size, ' ');
5618 aDataset->ReadFromDisk( (char*) info.data() );
5619 aDataset->CloseOnDisk();
5620 myNewMeshImpl->FileInfoFromString( info );
5626 // As all objects that can be referred by hypothesis are created,
5627 // we can restore hypothesis data
5629 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5630 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5632 SMESH_Hypothesis_i* hyp = hyp_data->first;
5633 string & data = hyp_data->second;
5634 hyp->LoadFrom( data.c_str() );
5637 // Restore the rest mesh data
5639 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5640 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5642 aTopGroup = meshi_group->second;
5643 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5645 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5646 bool hasData = false;
5649 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5650 int newId = myStudyContext->findId( iorString.in() );
5651 int meshOldId = myStudyContext->getOldId( newId );
5653 // try to find mesh data dataset
5654 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5655 // load mesh "has data" flag
5656 aDataset = new HDFdataset( "Has data", aTopGroup );
5657 aDataset->OpenOnDisk();
5658 size = aDataset->GetSize();
5659 char* strHasData = new char[ size ];
5660 aDataset->ReadFromDisk( strHasData );
5661 aDataset->CloseOnDisk();
5662 if ( strcmp( strHasData, "1") == 0 ) {
5665 delete [] strHasData;
5668 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5669 // nodes and elements are not yet put into sub-meshes)
5670 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5671 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5672 aGroup->OpenOnDisk();
5673 // get number of applied algorithms
5674 int aNbSubObjects = aGroup->nInternalObjects();
5675 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5676 for ( int j = 0; j < aNbSubObjects; j++ ) {
5677 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5678 aGroup->InternalObjectIndentify( j, name_dataset );
5679 // check if it is an algorithm
5680 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5681 aDataset = new HDFdataset( name_dataset, aGroup );
5682 aDataset->OpenOnDisk();
5683 size = aDataset->GetSize();
5684 char* refFromFile = new char[ size ];
5685 aDataset->ReadFromDisk( refFromFile );
5686 aDataset->CloseOnDisk();
5687 // san - it is impossible to recover applied algorithms using their entries within Load() method
5688 int id = atoi( refFromFile );
5689 delete [] refFromFile;
5690 string anIOR = myStudyContext->getIORbyOldId( id );
5691 if ( !anIOR.empty() ) {
5692 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5693 if ( !CORBA::is_nil( hypObject ) ) {
5694 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5695 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5696 || !myNewMeshImpl->HasShapeToMesh()) )
5697 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5702 aGroup->CloseOnDisk();
5705 // try to get applied hypotheses
5706 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5707 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5708 aGroup->OpenOnDisk();
5709 // get number of applied hypotheses
5710 int aNbSubObjects = aGroup->nInternalObjects();
5711 for ( int j = 0; j < aNbSubObjects; j++ ) {
5712 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5713 aGroup->InternalObjectIndentify( j, name_dataset );
5714 // check if it is a hypothesis
5715 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5716 aDataset = new HDFdataset( name_dataset, aGroup );
5717 aDataset->OpenOnDisk();
5718 size = aDataset->GetSize();
5719 char* refFromFile = new char[ size ];
5720 aDataset->ReadFromDisk( refFromFile );
5721 aDataset->CloseOnDisk();
5722 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5723 int id = atoi( refFromFile );
5724 delete [] refFromFile;
5725 string anIOR = myStudyContext->getIORbyOldId( id );
5726 if ( !anIOR.empty() ) {
5727 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5728 if ( !CORBA::is_nil( hypObject ) ) {
5729 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5730 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5731 || !myNewMeshImpl->HasShapeToMesh()) )
5732 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5737 aGroup->CloseOnDisk();
5740 // --> try to find SUB-MESHES containers for each type of submesh
5741 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5742 const char* name_meshgroup = 0;
5743 if ( j == GetSubMeshOnVertexTag() )
5744 name_meshgroup = "SubMeshes On Vertex";
5745 else if ( j == GetSubMeshOnEdgeTag() )
5746 name_meshgroup = "SubMeshes On Edge";
5747 else if ( j == GetSubMeshOnWireTag() )
5748 name_meshgroup = "SubMeshes On Wire";
5749 else if ( j == GetSubMeshOnFaceTag() )
5750 name_meshgroup = "SubMeshes On Face";
5751 else if ( j == GetSubMeshOnShellTag() )
5752 name_meshgroup = "SubMeshes On Shell";
5753 else if ( j == GetSubMeshOnSolidTag() )
5754 name_meshgroup = "SubMeshes On Solid";
5755 else if ( j == GetSubMeshOnCompoundTag() )
5756 name_meshgroup = "SubMeshes On Compound";
5758 // try to get submeshes container HDF group
5759 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5760 // open submeshes containers HDF group
5761 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5762 aGroup->OpenOnDisk();
5764 // get number of submeshes
5765 int aNbSubMeshes = aGroup->nInternalObjects();
5766 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5768 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5769 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5770 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5771 // --> get submesh id
5772 int subid = atoi( name_submeshgroup + 7 );
5775 // open submesh HDF group
5776 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5777 aSubGroup->OpenOnDisk();
5779 // try to read and set reference to subshape
5780 GEOM::GEOM_Object_var aSubShapeObject;
5781 SMESH::SMESH_subMesh_var aSubMesh;
5783 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5784 // load submesh "Ref on shape" - it's an entry to SObject
5785 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5786 aDataset->OpenOnDisk();
5787 size = aDataset->GetSize();
5788 char* refFromFile = new char[ size ];
5789 aDataset->ReadFromDisk( refFromFile );
5790 aDataset->CloseOnDisk();
5791 if ( strlen( refFromFile ) > 0 ) {
5792 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5793 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5794 if ( !CORBA::is_nil( subShapeObject ) ) {
5795 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5796 if ( !aSubShapeObject->_is_nil() )
5797 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5798 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5799 if ( aSubMesh->_is_nil() )
5801 string iorSubString = GetORB()->object_to_string( aSubMesh );
5802 int newSubId = myStudyContext->findId( iorSubString );
5803 myStudyContext->mapOldToNew( subid, newSubId );
5806 delete [] refFromFile;
5809 if ( aSubMesh->_is_nil() )
5812 // try to get applied algorithms
5813 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5814 // open "applied algorithms" HDF group
5815 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5816 aSubSubGroup->OpenOnDisk();
5817 // get number of applied algorithms
5818 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5819 for ( int l = 0; l < aNbSubObjects; l++ ) {
5820 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5821 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5822 // check if it is an algorithm
5823 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5824 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5825 aDataset->OpenOnDisk();
5826 size = aDataset->GetSize();
5827 char* refFromFile = new char[ size ];
5828 aDataset->ReadFromDisk( refFromFile );
5829 aDataset->CloseOnDisk();
5831 int id = atoi( refFromFile );
5832 string anIOR = myStudyContext->getIORbyOldId( id );
5833 if ( !anIOR.empty() ) {
5834 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5835 if ( !CORBA::is_nil( hypObject ) ) {
5836 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5837 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5838 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5841 delete [] refFromFile;
5844 // close "applied algorithms" HDF group
5845 aSubSubGroup->CloseOnDisk();
5848 // try to get applied hypotheses
5849 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5850 // open "applied hypotheses" HDF group
5851 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5852 aSubSubGroup->OpenOnDisk();
5853 // get number of applied hypotheses
5854 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5855 for ( int l = 0; l < aNbSubObjects; l++ ) {
5856 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5857 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5858 // check if it is a hypothesis
5859 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5860 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5861 aDataset->OpenOnDisk();
5862 size = aDataset->GetSize();
5863 char* refFromFile = new char[ size ];
5864 aDataset->ReadFromDisk( refFromFile );
5865 aDataset->CloseOnDisk();
5867 int id = atoi( refFromFile );
5868 string anIOR = myStudyContext->getIORbyOldId( id );
5869 if ( !anIOR.empty() ) {
5870 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5871 if ( !CORBA::is_nil( hypObject ) ) {
5872 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5873 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5874 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5877 delete [] refFromFile;
5880 // close "APPLIED HYPOTHESES" hdf group
5881 aSubSubGroup->CloseOnDisk();
5884 // close SUB-MESH hdf group
5885 aSubGroup->CloseOnDisk();
5888 // close SUB-MESHES containers hdf group
5889 aGroup->CloseOnDisk();
5893 // try to get GROUPS
5894 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5895 char name_group[ 30 ];
5896 if ( ii == GetNodeGroupsTag() )
5897 strcpy( name_group, "Groups of Nodes" );
5898 else if ( ii == GetEdgeGroupsTag() )
5899 strcpy( name_group, "Groups of Edges" );
5900 else if ( ii == GetFaceGroupsTag() )
5901 strcpy( name_group, "Groups of Faces" );
5902 else if ( ii == GetVolumeGroupsTag() )
5903 strcpy( name_group, "Groups of Volumes" );
5904 else if ( ii == Get0DElementsGroupsTag() )
5905 strcpy( name_group, "Groups of 0D Elements" );
5906 else if ( ii == GetBallElementsGroupsTag() )
5907 strcpy( name_group, "Groups of Balls" );
5909 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5910 aGroup = new HDFgroup( name_group, aTopGroup );
5911 aGroup->OpenOnDisk();
5912 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5913 // within aGroup->ExistInternalObject( name )
5914 std::vector< std::string > subNames;
5915 TColStd_MapOfAsciiString mapOfNames;
5916 aGroup->GetAllObjects( subNames );
5917 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5918 mapOfNames.Add( subNames[ iN ].c_str() );
5920 for ( size_t j = 0; j < subNames.size(); j++ ) {
5921 const std::string& name_dataset = subNames[ j ];
5922 // check if it is a group
5923 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5926 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5929 int groupID = -1; // group local ID (also persistent)
5931 groupID = atoi( endptr + 1 );
5932 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5933 aDataset->OpenOnDisk();
5935 // Retrieve actual group name
5936 size = aDataset->GetSize();
5937 char* nameFromFile = new char[ size ];
5938 aDataset->ReadFromDisk( nameFromFile );
5939 aDataset->CloseOnDisk();
5941 // Try to find a shape reference
5942 TopoDS_Shape aShape;
5943 char aRefName[ 30 ];
5944 sprintf( aRefName, "Ref on shape %d", subid);
5945 if ( mapOfNames.Contains( aRefName ))
5947 // load mesh "Ref on shape" - it's an entry to SObject
5948 aDataset = new HDFdataset( aRefName, aGroup );
5949 aDataset->OpenOnDisk();
5950 size = aDataset->GetSize();
5951 char* refFromFile = new char[ size ];
5952 aDataset->ReadFromDisk( refFromFile );
5953 aDataset->CloseOnDisk();
5954 if ( strlen( refFromFile ) > 0 ) {
5955 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5956 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5957 if ( !CORBA::is_nil( shapeObject ) ) {
5958 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5959 if ( !aShapeObject->_is_nil() )
5960 aShape = GeomObjectToShape( aShapeObject );
5963 delete [] refFromFile;
5965 // Try to read a filter of SMESH_GroupOnFilter
5966 SMESH::Filter_var filter;
5967 SMESH_PredicatePtr predicate;
5968 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5969 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5971 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5972 aDataset->OpenOnDisk();
5973 size = aDataset->GetSize();
5974 char* persistStr = new char[ size ];
5975 aDataset->ReadFromDisk( persistStr );
5976 aDataset->CloseOnDisk();
5977 if ( strlen( persistStr ) > 0 ) {
5978 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5979 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5980 filters.push_back( filter );
5982 delete [] persistStr;
5985 // Create group servant
5986 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5987 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5988 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5989 delete [] nameFromFile;
5990 // Obtain a SMESHDS_Group object
5991 if ( aNewGroup->_is_nil() )
5994 CORBA::String_var iorSubStringVar = GetORB()->object_to_string( aNewGroup );
5995 string iorSubString(iorSubStringVar.in());
5996 int newSubId = myStudyContext->findId( iorSubString );
5997 myStudyContext->mapOldToNew( subid, newSubId );
5999 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
6003 if ( SMESH_GroupOnFilter_i* aFilterGroup =
6004 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
6006 aFilterGroup->SetFilter( filter );
6007 filter->UnRegister();
6009 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
6010 if ( !aGroupBaseDS )
6013 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
6016 // Read color of the group
6017 char aGroupColorName[ 30 ];
6018 sprintf( aGroupColorName, "ColorGroup %d", subid);
6019 if ( mapOfNames.Contains( aGroupColorName ))
6021 aDataset = new HDFdataset( aGroupColorName, aGroup );
6022 aDataset->OpenOnDisk();
6023 size = aDataset->GetSize();
6024 double* anRGB = new double[ size ];
6025 aDataset->ReadFromDisk( anRGB );
6026 aDataset->CloseOnDisk();
6027 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
6028 aGroupBaseDS->SetColor( aColor );
6033 aGroup->CloseOnDisk();
6037 // instead of reading mesh data, we read only brief information of all
6038 // objects: mesh, groups, sub-meshes (issue 0021208)
6041 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
6042 meshfile.ToCString(), filename.ToCString(),
6046 // read Sub-Mesh ORDER if any
6047 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
6048 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
6049 aDataset->OpenOnDisk();
6050 size = aDataset->GetSize();
6051 int* smIDs = new int[ size ];
6052 aDataset->ReadFromDisk( smIDs );
6053 aDataset->CloseOnDisk();
6054 TListOfListOfInt anOrderIds;
6055 anOrderIds.push_back( TListOfInt() );
6056 for ( int i = 0; i < size; i++ )
6057 if ( smIDs[ i ] < 0 ) // is separator
6058 anOrderIds.push_back( TListOfInt() );
6060 anOrderIds.back().push_back(smIDs[ i ]);
6062 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6065 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
6067 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
6068 aDataset->OpenOnDisk();
6069 size = aDataset->GetSize();
6070 std::string dataString; dataString.resize( size );
6071 aDataset->ReadFromDisk((char*) dataString.data() );
6072 aDataset->CloseOnDisk();
6074 std::list< std::list< std::string > > orderEntryLists;
6075 SMESHUtils::BoostTxtArchive( dataString ) >> orderEntryLists;
6077 TListOfListOfInt anOrderIds;
6078 for ( const std::list< std::string >& entryList : orderEntryLists )
6080 anOrderIds.emplace_back();
6081 for ( const std::string & entry : entryList )
6083 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6084 TopoDS_Shape shape = GeomObjectToShape( go );
6085 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6086 anOrderIds.back().emplace_back( sm->GetId() );
6089 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6093 // update hyps needing full mesh data restored (issue 20918)
6094 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6096 SMESH_Hypothesis_i* hyp = hyp_data->first;
6097 hyp->UpdateAsMeshesRestored();
6100 // notify algos on completed restoration to set sub-mesh event listeners
6101 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6103 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6104 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6106 TopoDS_Shape myLocShape;
6107 if(myLocMesh.HasShapeToMesh())
6108 myLocShape = myLocMesh.GetShapeToMesh();
6110 myLocShape = SMESH_Mesh::PseudoShape();
6112 myLocMesh.GetSubMesh(myLocShape)->
6113 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6116 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6117 list< SMESH::Filter_var >::iterator f = filters.begin();
6118 for ( ; f != filters.end(); ++f )
6119 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6120 fi->FindBaseObjects();
6125 aTopGroup->CloseOnDisk();
6128 aFile->CloseOnDisk();
6131 // Remove temporary files created from the stream
6134 SMESH_File meshFile( meshfile.ToCString() );
6135 if ( !meshFile ) // no meshfile exists
6137 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6141 Engines::Container_var container = GetContainerRef();
6142 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6144 container_i->registerTemporaryFile( filename.ToCString() );
6145 container_i->registerTemporaryFile( meshfile.ToCString() );
6146 container_i->registerTemporaryFile( tmpDir.ToCString() );
6151 // creation of tree nodes for all data objects in the study
6152 // to support tree representation customization and drag-n-drop:
6153 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6154 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6155 useCaseBuilder->SetRootCurrent();
6156 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6157 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6158 for (it->InitEx(true); it->More(); it->Next()) {
6159 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6166 //=============================================================================
6168 * SMESH_Gen_i::LoadASCII
6170 * Load SMESH module's data in ASCII format
6172 //=============================================================================
6174 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6175 const SALOMEDS::TMPFile& theStream,
6177 bool isMultiFile ) {
6178 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6179 return Load( theComponent, theStream, theURL, isMultiFile );
6181 //before call main ::Load method it's need for decipher text format to
6182 //binary ( "|xx" => x' )
6183 int size = theStream.length();
6184 if ( int((size / 3 )*3) != size ) //error size of buffer
6187 int real_size = int(size / 3);
6189 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6192 unsigned int c = -1;
6193 for ( int i = 0; i < real_size; i++ )
6195 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6196 sscanf( tmp, "%x", &c );
6197 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6200 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6202 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6205 //=============================================================================
6207 * SMESH_Gen_i::Close
6209 * Clears study-connected data when it is closed
6211 //=============================================================================
6213 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6215 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6217 // Clear study contexts data
6218 myStudyContext->Clear();
6220 // remove the tmp files meshes are loaded from
6221 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6223 // Clean trace of API methods calls
6229 //=============================================================================
6231 * SMESH_Gen_i::ComponentDataType
6233 * Get component data type
6235 //=============================================================================
6237 char* SMESH_Gen_i::ComponentDataType()
6239 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6240 return CORBA::string_dup( "SMESH" );
6244 //=============================================================================
6246 * SMESH_Gen_i::IORToLocalPersistentID
6248 * Transform data from transient form to persistent
6250 //=============================================================================
6252 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6253 const char* IORString,
6254 CORBA::Boolean /*isMultiFile*/,
6255 CORBA::Boolean /*isASCII*/ )
6257 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6259 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6260 int anId = myStudyContext->findId( IORString );
6262 if(MYDEBUG) MESSAGE( "VSR " << anId )
6264 sprintf( strId, "%d", anId );
6265 return CORBA::string_dup( strId );
6268 return CORBA::string_dup( "" );
6271 //=============================================================================
6273 * SMESH_Gen_i::LocalPersistentIDToIOR
6275 * Transform data from persistent form to transient
6277 //=============================================================================
6279 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6280 const char* aLocalPersistentID,
6281 CORBA::Boolean /*isMultiFile*/,
6282 CORBA::Boolean /*isASCII*/ )
6284 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6286 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6287 int anId = atoi( aLocalPersistentID );
6288 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6290 return CORBA::string_dup( "" );
6293 //=======================================================================
6294 //function : RegisterObject
6296 //=======================================================================
6298 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6300 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6301 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6302 return myStudyContext->addObject( string( iorString.in() ) );
6307 //================================================================================
6309 * \brief Return id of registered object
6310 * \param theObject - the Object
6311 * \retval int - Object id
6313 //================================================================================
6315 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6317 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6318 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6319 string iorStringCpp(iorString.in());
6320 return myStudyContext->findId( iorStringCpp );
6325 //=============================================================================
6327 * SMESH_Gen_i::SetName
6329 * Set a new object name
6331 //=============================================================================
6333 void SMESH_Gen_i::SetName(const char* theIOR,
6334 const char* theName)
6336 if ( theIOR && strcmp( theIOR, "" ) ) {
6337 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6338 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6339 if ( !aSO->_is_nil() ) {
6340 SetName( aSO, theName );
6345 // Version information
6346 char* SMESH_Gen_i::getVersion()
6348 #if SMESH_DEVELOPMENT
6349 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6351 return CORBA::string_dup(SMESH_VERSION_STR);
6355 //=================================================================================
6356 // function : Move()
6357 // purpose : Moves objects to the specified position.
6358 // Is used in the drag-n-drop functionality.
6359 //=================================================================================
6361 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6362 SALOMEDS::SObject_ptr where,
6365 if ( CORBA::is_nil( where ) ) return;
6367 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6368 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6369 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6370 std::string dataType = father->ComponentDataType();
6371 if ( dataType != "SMESH" ) return; // not a SMESH component
6373 SALOMEDS::SObject_var objAfter;
6374 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6375 // insert at given row -> find insertion position
6376 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6378 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6379 if ( i == row && useCaseIt->More() ) {
6380 objAfter = useCaseIt->Value();
6384 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6385 SALOMEDS::SObject_var sobj = what[i];
6386 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6387 // insert the object to the use case tree
6388 if ( !CORBA::is_nil( objAfter ) )
6389 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6391 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6395 //================================================================================
6397 * \brief Collect indices of elements, which are located inside the sphere
6399 //================================================================================
6401 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6402 SMESH::ElementType theElemType,
6408 SMESH::long_array_var aResult = new SMESH::long_array();
6409 if ( meshPart->_is_nil() )
6410 return aResult._retn();
6412 // 1. Create geometrical object
6413 gp_Pnt aP( theX, theY, theZ );
6414 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6416 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6418 if ( lst.size() > 0 ) {
6419 aResult->length( lst.size() );
6420 for ( size_t i = 0; i < lst.size(); i++ ) {
6421 aResult[i] = lst[i];
6424 return aResult._retn();
6427 //================================================================================
6429 * \brief Collect indices of elements, which are located inside the box
6431 //================================================================================
6433 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6434 SMESH::ElementType theElemType,
6435 CORBA::Double theX1,
6436 CORBA::Double theY1,
6437 CORBA::Double theZ1,
6438 CORBA::Double theX2,
6439 CORBA::Double theY2,
6440 CORBA::Double theZ2)
6442 SMESH::long_array_var aResult = new SMESH::long_array();
6443 if( meshPart->_is_nil() )
6444 return aResult._retn();
6446 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6447 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6449 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6451 if( lst.size() > 0 ) {
6452 aResult->length( lst.size() );
6453 for ( size_t i = 0; i < lst.size(); i++ ) {
6454 aResult[i] = lst[i];
6457 return aResult._retn();
6460 //================================================================================
6462 * \brief Collect indices of elements, which are located inside the cylinder
6464 //================================================================================
6466 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6467 SMESH::ElementType theElemType,
6471 CORBA::Double theDX,
6472 CORBA::Double theDY,
6473 CORBA::Double theDZ,
6475 CORBA::Double theR )
6477 SMESH::long_array_var aResult = new SMESH::long_array();
6478 if( meshPart->_is_nil() )
6479 return aResult._retn();
6481 gp_Pnt aP( theX, theY, theZ );
6482 gp_Vec aV( theDX, theDY, theDZ );
6483 gp_Ax2 anAxes (aP, aV);
6485 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6487 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6489 if( lst.size() > 0 ) {
6490 aResult->length( lst.size() );
6491 for ( size_t i = 0; i < lst.size(); i++ ) {
6492 aResult[i] = lst[i];
6495 return aResult._retn();
6498 //================================================================================
6500 * \brief Collect indices of elements, which are located inside the geom object
6502 //================================================================================
6504 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6505 SMESH::ElementType theElemType,
6506 GEOM::GEOM_Object_ptr theGeom,
6507 CORBA::Double theTolerance )
6509 SMESH::long_array_var aResult = new SMESH::long_array();
6510 if( meshPart->_is_nil() || theGeom->_is_nil() )
6511 return aResult._retn();
6513 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6515 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6517 if( lst.size() > 0 ) {
6518 aResult->length( lst.size() );
6519 for ( size_t i = 0; i < lst.size(); i++ ) {
6520 aResult[i] = lst[i];
6523 return aResult._retn();
6526 //================================================================================
6528 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6530 //================================================================================
6532 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6533 SMESH::ElementType theElemType,
6534 const TopoDS_Shape& theShape,
6535 double* theTolerance) {
6537 std::vector<long> res;
6538 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6540 if ( mesh->_is_nil() )
6543 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6547 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6552 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6553 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6554 anElementsOnShape->SetAllNodes( true );
6555 anElementsOnShape->SetMesh( meshDS );
6556 anElementsOnShape->SetShape( theShape, aType );
6559 anElementsOnShape->SetTolerance(*theTolerance);
6561 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6562 if ( !msource->_is_nil() ) { // Mesh case
6563 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6565 while ( elemIt->more() ) {
6566 const SMDS_MeshElement* anElem = elemIt->next();
6567 long anId = anElem->GetID();
6568 if ( anElementsOnShape->IsSatisfy( anId ) )
6569 res.push_back( anId );
6573 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6574 if ( !gsource->_is_nil() ) {
6575 if(theElemType == SMESH::NODE) {
6576 SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6577 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6578 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6579 long anId = node->GetID();
6580 if ( anElementsOnShape->IsSatisfy( anId ) )
6581 res.push_back( anId );
6584 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6585 SMESH::smIdType_array_var elems = gsource->GetListOfID();
6586 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6587 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6588 long anId = elem->GetID();
6589 if ( anElementsOnShape->IsSatisfy( anId ) )
6590 res.push_back( anId );
6595 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6596 if ( !smsource->_is_nil() ) {
6597 SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6598 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6599 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6601 long anId = elem->GetID();
6602 if ( anElementsOnShape->IsSatisfy( anId ) )
6603 res.push_back( anId );
6610 //================================================================================
6612 * \brief Returns true if algorithm can be used to mesh a given geometry
6613 * \param [in] theAlgoType - the algorithm type
6614 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6615 * \param [in] theGeomObject - the geometry to mesh
6616 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6617 * else, returns \c True if at least one shape is meshable
6618 * \return CORBA::Boolean - can or can't
6620 //================================================================================
6622 #undef SMY_OWN_CATCH
6623 #define SMY_OWN_CATCH // prevent re-throwing SALOME::SALOME_Exception in IsApplicable()
6625 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6626 const char* theLibName,
6627 GEOM::GEOM_Object_ptr theGeomObject,
6628 CORBA::Boolean toCheckAll)
6632 std::string aPlatformLibName;
6633 GenericHypothesisCreator_i* aCreator =
6634 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6637 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6638 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6639 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6646 SMESH_CATCH( SMESH::doNothing );
6649 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;