1 // Copyright (C) 2007-2021 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>
57 #include <libgen.h> // for basename function
61 #define LibHandle HMODULE
62 #define LoadLib( name ) LoadLibrary( name )
63 #define GetProc GetProcAddress
64 #define UnLoadLib( handle ) FreeLibrary( handle );
66 #define LibHandle void*
68 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
69 #else // DYNLOAD_LOCAL
70 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
71 #endif // DYNLOAD_LOCAL
73 #define UnLoadLib( handle ) dlclose( handle );
76 #include "SMESH_Gen_i.hxx"
77 #include "SMESH_version.h"
79 #include "DriverMED_W_SMESHDS_Mesh.h"
80 #include "DriverMED_R_SMESHDS_Mesh.h"
82 #include "DriverCGNS_Read.hxx"
84 #include "MED_Factory.hxx"
85 #include "SMDS_EdgePosition.hxx"
86 #include "SMDS_FacePosition.hxx"
87 #include "SMDS_SetIterator.hxx"
88 #include "SMDS_SpacePosition.hxx"
89 #include "SMDS_VertexPosition.hxx"
90 #include "SMESHDS_Document.hxx"
91 #include "SMESHDS_Group.hxx"
92 #include "SMESHDS_GroupOnGeom.hxx"
93 #include "SMESH_Algo_i.hxx"
94 #include "SMESH_File.hxx"
95 #include "SMESH_Group.hxx"
96 #include "SMESH_Group_i.hxx"
97 #include "SMESH_Hypothesis.hxx"
98 #include "SMESH_Hypothesis_i.hxx"
99 #include "SMESH_Mesh.hxx"
100 #include "SMESH_MeshEditor.hxx"
101 #include "SMESH_Mesh_i.hxx"
102 #include "SMESH_PreMeshInfo.hxx"
103 #include "SMESH_PythonDump.hxx"
104 #include "SMESH_ControlsDef.hxx"
105 #include <SMESH_BoostTxtArchive.hxx>
107 // to pass CORBA exception through SMESH_TRY
108 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
109 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
111 #include CORBA_SERVER_HEADER(SMESH_Group)
112 #include CORBA_SERVER_HEADER(SMESH_Filter)
113 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
116 #include <GEOMImpl_Types.hxx>
117 #include <GEOM_Client.hxx>
119 #include <Basics_Utils.hxx>
120 #include <Basics_DirUtils.hxx>
122 #include <OpUtil.hxx>
123 #include <SALOMEDS_Tool.hxx>
124 #include <SALOME_Container_i.hxx>
125 #include <SALOME_LifeCycleCORBA.hxx>
126 #include <SALOME_NamingService.hxx>
127 #include <Utils_CorbaException.hxx>
128 #include <Utils_ExceptHandlers.hxx>
129 #include <Utils_SINGLETON.hxx>
130 #include <utilities.h>
132 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
133 #include CORBA_CLIENT_HEADER(SALOME_Session)
135 // helpers about SALOME::GenericObj
136 #include <SALOMEDS_wrap.hxx>
137 #include <SALOMEDS_Attributes_wrap.hxx>
138 #include <GEOM_wrap.hxx>
147 #include <boost/archive/text_oarchive.hpp>
148 #include <boost/archive/text_iarchive.hpp>
149 #include <boost/serialization/list.hpp>
150 #include <boost/serialization/string.hpp>
153 using SMESH::TPythonDump;
156 #define NUM_TMP_FILES 2
159 static int MYDEBUG = 0;
161 static int MYDEBUG = 0;
164 // Static variables definition
165 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
166 CORBA::ORB_var SMESH_Gen_i::myOrb;
167 PortableServer::POA_var SMESH_Gen_i::myPoa;
168 SALOME_NamingService_Abstract* SMESH_Gen_i::myNS = nullptr;
169 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = nullptr;
170 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = nullptr;
173 const int nbElemPerDiagonal = 10;
175 //=============================================================================
177 * GetServant [ static ]
179 * Get servant of the CORBA object
181 //=============================================================================
183 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
185 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
188 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
191 catch (PortableServer::POA::ObjectNotActive &ex)
193 INFOS("GetServant: ObjectNotActive");
196 catch (PortableServer::POA::WrongAdapter &ex)
198 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
201 catch (PortableServer::POA::WrongPolicy &ex)
203 INFOS("GetServant: WrongPolicy");
208 INFOS( "GetServant - Unknown exception was caught!!!" );
213 //=============================================================================
215 * SObjectToObject [ static ]
217 * Get CORBA object corresponding to the SALOMEDS::SObject
219 //=============================================================================
221 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
223 SALOMEDS::GenericAttribute_wrap anAttr;
224 CORBA::Object_var anObj;
225 if ( !theSObject->_is_nil() ) {
227 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
228 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
229 CORBA::String_var aValue = anIOR->Value();
230 if( strcmp( aValue, "" ) != 0 )
231 anObj = GetORB()->string_to_object( aValue );
235 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
241 // Set Naming Service object
242 void SMESH_Gen_i::SetNS(SALOME_NamingService_Abstract *ns)
249 //=============================================================================
253 * Get SALOME_NamingService object
255 //=============================================================================
257 SALOME_NamingService_Abstract* SMESH_Gen_i::GetNS()
260 myNS = SINGLETON_<SALOME_NamingService>::Instance();
261 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
262 myNS->init_orb( GetORB() );
267 //=============================================================================
271 * Get SALOME_LifeCycleCORBA object
273 //=============================================================================
275 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
277 if ( myLCC == NULL ) {
278 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
283 //=============================================================================
285 * GetGeomEngine [ static ]
287 * Get GEOM::GEOM_Gen reference
289 //=============================================================================
291 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
293 GEOM::GEOM_Gen_ptr gen = GEOM::GEOM_Gen::_nil();
294 if ( !CORBA::is_nil( go ))
299 //=============================================================================
301 * SMESH_Gen_i::SMESH_Gen_i
303 * Default constructor: not for use
305 //=============================================================================
307 SMESH_Gen_i::SMESH_Gen_i()
311 //=============================================================================
313 * SMESH_Gen_i::SMESH_Gen_i
315 * Standard constructor, used with Container
317 //=============================================================================
319 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
320 PortableServer::POA_ptr poa,
321 PortableServer::ObjectId* contId,
322 const char* instanceName,
323 const char* interfaceName,
325 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName, false, checkNS )
328 myOrb = CORBA::ORB::_duplicate(orb);
329 myPoa = PortableServer::POA::_duplicate(poa);
332 _id = myPoa->activate_object( _thisObj );
334 myStudyContext = new StudyContext;
336 myIsEmbeddedMode = false;
337 myIsEnablePublish = true;
338 myShapeReader = NULL; // shape reader
340 myIsHistoricalPythonDump = true;
341 myToForgetMeshDataOnHypModif = false;
343 // set it in standalone mode only
344 //OSD::SetSignal( true );
346 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
347 // find out mode (embedded or standalone) here else
348 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
349 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
352 if ( SALOME_NamingService_Abstract* ns = GetNS() )
354 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
355 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
356 if ( !session->_is_nil() )
358 CORBA::String_var str_host = session->getHostname();
359 CORBA::Long s_pid = session->getPID();
360 string my_host = Kernel_Utils::GetHostname();
362 long my_pid = (long)_getpid();
364 long my_pid = (long) getpid();
366 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
372 //=============================================================================
374 * SMESH_Gen_i::~SMESH_Gen_i
378 //=============================================================================
380 SMESH_Gen_i::~SMESH_Gen_i()
382 // delete hypothesis creators
383 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
384 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
386 // same creator can be mapped under different names
387 GenericHypothesisCreator_i* creator = (*itHyp).second;
391 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
392 if ( creator == (*itHyp2).second )
393 (*itHyp2).second = 0;
395 myHypCreatorMap.clear();
397 // Clear study contexts data
398 delete myStudyContext;
400 // delete shape reader
402 delete myShapeReader;
405 //=============================================================================
407 * SMESH_Gen_i::getHypothesisCreator
409 * Get hypothesis creator
411 //=============================================================================
413 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
414 const char* theLibName,
415 std::string& thePlatformLibName)
417 std::string aPlatformLibName;
418 /* It's Need to translate lib name for WIN32 or X platform */
419 if ( theLibName && theLibName[0] != '\0' )
421 int libNameLen = strlen(theLibName);
422 //check for old format "libXXXXXXX.so"
423 if (libNameLen > 7 &&
424 !strncmp( theLibName, "lib", 3 ) &&
425 !strcmp( theLibName+libNameLen-3, ".so" ))
429 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
430 #elif defined(__APPLE__)
431 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
433 aPlatformLibName = theLibName;
438 //try to use new format
440 aPlatformLibName = theLibName;
441 aPlatformLibName += ".dll";
442 #elif defined(__APPLE__)
443 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
445 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
449 thePlatformLibName = aPlatformLibName;
451 Unexpect aCatch(SALOME_SalomeException);
452 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
454 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
455 GenericHypothesisCreator_i* aCreator;
458 // check, if creator for this hypothesis type already exists
459 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
461 // load plugin library
462 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
465 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
466 SMESHUtils::ArrayDeleter<const wchar_t> deleter( path );
468 const char* path = aPlatformLibName.c_str();
471 const char* path = aPlatformLibName.c_str();
473 LibHandle libHandle = LoadLib( path );
477 // report any error, if occurred
479 const char* anError = dlerror();
480 throw(SALOME_Exception( anError ));
482 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
483 << aPlatformLibName));
487 // get method, returning hypothesis creator
488 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
489 GetHypothesisCreator procHandle =
490 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
493 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
494 << aPlatformLibName ));
495 UnLoadLib(libHandle);
498 // get hypothesis creator
499 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
500 aCreator = procHandle(theHypName);
503 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
504 << aPlatformLibName));
506 // map hypothesis creator to a hypothesis name
507 myHypCreatorMap[string(theHypName)] = aCreator;
512 return myHypCreatorMap[string(theHypName)];
515 catch (SALOME_Exception& S_ex)
517 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
522 //=============================================================================
524 * SMESH_Gen_i::createHypothesis
526 * Create hypothesis of given type
528 //=============================================================================
530 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
531 const char* theLibName)
533 SMESH_Hypothesis_i* myHypothesis_i = 0;
534 SMESH::SMESH_Hypothesis_var hypothesis_i;
535 std::string aPlatformLibName;
536 GenericHypothesisCreator_i* aCreator =
537 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
539 // create a new hypothesis object, store its ref. in studyContext
540 myHypothesis_i = aCreator->Create(myPoa, &myGen);
543 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
544 CORBA::String_var hypName = myHypothesis_i->GetName();
545 myHypCreatorMap[ hypName.in() ] = aCreator;
547 // activate the CORBA servant of hypothesis
548 hypothesis_i = myHypothesis_i->_this();
549 int nextId = RegisterObject( hypothesis_i );
550 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
551 else { (void)nextId; } // avoid "unused variable" warning in release mode
553 return hypothesis_i._retn();
556 //=============================================================================
558 * SMESH_Gen_i::createMesh
560 * Create empty mesh on shape
562 //=============================================================================
564 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
566 Unexpect aCatch(SALOME_SalomeException);
567 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
569 // Get or create the GEOM_Client instance
571 // create a new mesh object servant, store it in a map in study context
572 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
573 // create a new mesh object
574 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
575 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
577 // activate the CORBA servant of Mesh
578 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
579 int nextId = RegisterObject( mesh );
580 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
581 else { (void)nextId; } // avoid "unused variable" warning in release mode
584 catch (SALOME_Exception& S_ex) {
585 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
587 return SMESH::SMESH_Mesh::_nil();
590 //=============================================================================
592 * SMESH_Gen_i::GetShapeReader
596 //=============================================================================
598 GEOM_Client* SMESH_Gen_i::GetShapeReader()
600 // create shape reader if necessary
601 if ( !myShapeReader )
602 myShapeReader = new GEOM_Client(GetContainerRef());
603 ASSERT( myShapeReader );
604 return myShapeReader;
607 //=============================================================================
609 * SMESH_Gen_i::SetGeomEngine
611 * Set GEOM::GEOM_Gen reference
613 //=============================================================================
615 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
617 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
620 //=============================================================================
622 * SMESH_Gen_i::SetEmbeddedMode
626 //=============================================================================
628 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
630 myIsEmbeddedMode = theMode;
632 if ( !myIsEmbeddedMode ) {
633 //PAL10867: disable signals catching with "noexcepthandler" option
634 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
635 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
640 char* envDisableFPE = getenv("DISABLE_FPE");
641 if (envDisableFPE && atoi(envDisableFPE))
646 OSD::SetSignal( raiseFPE );
648 // else OSD::SetSignal() is called in GUI
652 //=============================================================================
654 * SMESH_Gen_i::IsEmbeddedMode
658 //=============================================================================
660 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
662 return myIsEmbeddedMode;
665 //=============================================================================
667 * SMESH_Gen_i::SetEnablePublish
669 * Set enable publishing in the study
671 //=============================================================================
673 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
675 myIsEnablePublish = theIsEnablePublish;
678 //=============================================================================
680 * SMESH_Gen_i::IsEnablePublish
682 * Check enable publishing
684 //=============================================================================
686 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
688 return myIsEnablePublish;
691 //=============================================================================
693 * SMESH_Gen_i::UpdateStudy
695 * Update study (needed at switching GEOM->SMESH)
697 //=============================================================================
699 void SMESH_Gen_i::UpdateStudy()
701 if ( !myStudyContext )
702 myStudyContext = new StudyContext;
704 SALOMEDS::Study_var aStudy = getStudyServant();
705 if ( !CORBA::is_nil( aStudy ) )
707 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
709 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
710 if( !GEOM_var->_is_nil() )
711 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
713 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
714 if( !GEOM_var->_is_nil() )
715 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
717 // NPAL16168, issue 0020210
718 // Let meshes update their data depending on GEOM groups that could change
719 CORBA::String_var compDataType = ComponentDataType();
720 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
721 if ( !me->_is_nil() ) {
722 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
723 for ( ; anIter->More(); anIter->Next() ) {
724 SALOMEDS::SObject_wrap so = anIter->Value();
725 CORBA::Object_var ior = SObjectToObject( so );
726 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
727 mesh->CheckGeomModif();
733 //================================================================================
735 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
737 //================================================================================
739 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
741 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
742 SALOMEDS::GenericAttribute_wrap attr;
743 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
745 SALOMEDS::AttributePixMap_wrap pm = attr;
746 CORBA::String_var ico = pm->GetPixMap();
747 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
752 //=================================================================================
753 // function : hasObjectInfo()
754 // purpose : shows if module provides information for its objects
755 //=================================================================================
757 bool SMESH_Gen_i::hasObjectInfo()
762 //=================================================================================
763 // function : getObjectInfo()
764 // purpose : returns an information for a given object by its entry
765 //=================================================================================
767 char* SMESH_Gen_i::getObjectInfo( const char* entry )
769 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
770 // for the rest, "module 'SMESH', ID=0:1:2:*"
774 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
775 CORBA::Object_var obj = SObjectToObject( so );
776 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
777 if ( isGeomModifIcon( mesh ))
779 txt << "The geometry was changed and the mesh needs to be recomputed";
784 CORBA::String_var compType = ComponentDataType();
785 txt << "module '" << compType << "', ID=" << entry;
787 return CORBA::string_dup( txt );
790 //=============================================================================
792 * SMESH_Gen_i::GetStudyContext
796 //=============================================================================
798 StudyContext* SMESH_Gen_i::GetStudyContext()
800 return myStudyContext;
803 //=============================================================================
805 * SMESH_Gen_i::CreateHypothesis
807 * Create hypothesis/algorithm of given type and publish it in the study
809 //=============================================================================
811 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
812 const char* theLibName )
814 Unexpect aCatch(SALOME_SalomeException);
815 // Create hypothesis/algorithm
816 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
818 // Publish hypothesis/algorithm in the study
819 if ( CanPublishInStudy( hyp ) ) {
820 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
821 if ( !aSO->_is_nil() ) {
822 // Update Python script
823 TPythonDump(this) << aSO << " = " << this << ".CreateHypothesis('"
824 << theHypName << "', '" << theLibName << "')";
831 //================================================================================
833 * \brief Return a hypothesis initialized by given average length.
834 * \param theHypType - hypothesis type name
835 * \param theLibName - plugin library name
836 * \param theAverageLength - average length
837 * \param theQuadDominated - is quad-dominated flag
838 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
840 //================================================================================
842 SMESH::SMESH_Hypothesis_ptr
843 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
844 const char* theLibName,
845 CORBA::Double theAverageLength,
846 CORBA::Boolean theQuadDominated)
848 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
849 theAverageLength, theQuadDominated };
851 SMESH::SMESH_Hypothesis_var hyp =
852 GetHypothesisParameterValues( theHypType, theLibName,
853 SMESH::SMESH_Mesh::_nil(),
854 GEOM::GEOM_Object::_nil(),
856 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
858 TPythonDump(this) << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
859 << theHypType << "', '"
860 << theLibName << "', "
861 << theAverageLength << ", "
862 << theQuadDominated << " )";
867 //================================================================================
869 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
870 * existing on the given geometry or to size of the geometry.
871 * \param theHypType - hypothesis type name
872 * \param theLibName - plugin library name
873 * \param theMesh - The mesh of interest
874 * \param theGeom - The shape to get parameter values from
875 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
876 * in a study and used to compute the mesh, or a temporary one created just to pass
879 //================================================================================
881 SMESH::SMESH_Hypothesis_ptr
882 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
883 const char* theLibName,
884 SMESH::SMESH_Mesh_ptr theMesh,
885 GEOM::GEOM_Object_ptr theGeom,
886 const SMESH::HypInitParams& theParams)
888 Unexpect aCatch(SALOME_SalomeException);
890 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
891 if ( byMesh && CORBA::is_nil( theMesh ) )
892 return SMESH::SMESH_Hypothesis::_nil();
893 if ( byMesh && CORBA::is_nil( theGeom ) )
894 return SMESH::SMESH_Hypothesis::_nil();
896 // -----------------------------------------------
897 // find hypothesis used to mesh theGeom
898 // -----------------------------------------------
900 // get mesh and shape
901 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
902 TopoDS_Shape shape = GeomObjectToShape( theGeom );
903 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
904 return SMESH::SMESH_Hypothesis::_nil();
905 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
907 // create a temporary hypothesis to know its dimension
908 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
909 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
911 return SMESH::SMESH_Hypothesis::_nil();
912 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
915 // look for a hypothesis of theHypType used to mesh the shape
916 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
919 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
920 int nbLocalHyps = aHypList->length();
921 for ( int i = 0; i < nbLocalHyps; i++ ) {
922 CORBA::String_var hypName = aHypList[i]->GetName();
923 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
924 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
926 // check super shapes
927 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
928 while ( nbLocalHyps == 0 && itShape.More() ) {
929 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
930 if ( ! CORBA::is_nil( geomObj )) {
931 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
932 nbLocalHyps = aHypList->length();
933 for ( int i = 0; i < nbLocalHyps; i++ )
934 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
935 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
941 // let the temporary hypothesis find out somehow parameter values by mesh
942 if ( hyp->SetParametersByMesh( mesh, shape ))
943 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
947 ::SMESH_Hypothesis::TDefaults dflts;
948 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
949 dflts._nbSegments = myGen.GetDefaultNbSegments();
950 dflts._elemLength = theParams.averageLength;
951 dflts._quadDominated = theParams.quadDominated;
952 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
955 dflts._diagonal = mesh->GetShapeDiagonalSize();
957 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
958 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
959 dflts._shape = &shape;
962 // let the hypothesis initialize it's values
963 if ( hyp->SetParametersByDefaults( dflts, mesh ))
964 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
967 return SMESH::SMESH_Hypothesis::_nil();
970 //=============================================================================
972 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
973 * \param [in] theHyp - the hypothesis of interest
974 * \param [out] theMesh - the sole mesh using \a theHyp
975 * \param [out] theShape - the sole geometry \a theHyp is assigned to
976 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
978 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
979 * considered as SAME sub-mesh => result is \c true.
980 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
981 * a shape to which an hyp being edited is assigned.
983 //=============================================================================
985 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
986 SMESH::SMESH_Mesh_out theMesh,
987 GEOM::GEOM_Object_out theShape)
989 if ( CORBA::is_nil( theHyp ))
992 // get Mesh component SO
993 CORBA::String_var compDataType = ComponentDataType();
994 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
995 if ( CORBA::is_nil( comp ))
998 // look for child SO of meshes
999 SMESH::SMESH_Mesh_var foundMesh;
1000 TopoDS_Shape foundShape;
1002 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1003 for ( ; meshIter->More() && isSole; meshIter->Next() )
1005 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1006 CORBA::Object_var obj = SObjectToObject( curSO );
1007 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1011 // look for a sole shape where theHyp is assigned
1012 bool isHypFound = false;
1013 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1014 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1015 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1017 const THypList& hyps = s2hypsIt.Value();
1018 THypList::const_iterator h = hyps.begin();
1019 for ( ; h != hyps.end(); ++h )
1020 if ( (*h)->GetID() == theHyp->GetId() )
1022 if ( h != hyps.end()) // theHyp found
1025 if ( ! foundShape.IsNull() &&
1026 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1028 foundShape.Nullify();
1032 foundShape = s2hypsIt.Key();
1034 } // loop on assigned hyps
1036 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1038 if ( !foundMesh->_is_nil() ) // not a sole mesh
1040 if ( !foundMesh->HasShapeToMesh() ||
1041 !mesh_i ->HasShapeToMesh() )
1043 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1047 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1048 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1049 isSole = s1->IsSame( s2 );
1052 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1058 ! foundMesh->_is_nil() &&
1059 ! foundShape.IsNull() )
1061 theMesh = foundMesh._retn();
1062 theShape = ShapeToGeomObject( foundShape );
1063 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1068 //=============================================================================
1070 * Set number of segments per diagonal of boundary box of geometry by which
1071 * default segment length of appropriate 1D hypotheses is defined
1073 //=============================================================================
1075 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1077 if ( theNbSegments > 0 )
1078 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1080 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1083 //=============================================================================
1085 * \brief Set default number of segments per edge
1087 //=============================================================================
1089 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1091 if ( theNbSegments > 0 )
1092 myGen.SetDefaultNbSegments( int(theNbSegments) );
1094 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1097 //=============================================================================
1099 * Set an option value
1101 //=============================================================================
1103 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1105 if ( name && value && strlen( value ) > 0 )
1108 if ( strcmp(name, "historical_python_dump") == 0 )
1110 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1111 msgToGUI = "preferences/SMESH/historical_python_dump/";
1112 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1114 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1116 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1117 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1118 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1120 else if ( strcmp(name, "default_grp_color") == 0 )
1124 // color must be presented as a string of following form:
1125 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1126 str = str.substr(1);
1127 for ( size_t i = 0; i < str.length()/2; i++ )
1128 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1129 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1131 else if ( value ) { // rgb color ("255,170,0", for example)
1132 string tempValue( value );
1133 char* colorValue = strtok( &tempValue[0], "," );
1134 while ( colorValue != NULL ) {
1135 int c_value = atoi( colorValue );
1136 if ( c_value >= 0 && c_value <= 255 )
1137 color.push_back( c_value );
1138 colorValue = strtok( NULL, "," );
1141 if ( color.size() == 3 ) { // color must have three valid component
1142 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1143 myDefaultGroupColor = value;
1144 msgToGUI = "preferences/SMESH/default_grp_color/";
1149 // update preferences in case if SetOption() is invoked from python console
1150 if ( !msgToGUI.empty() )
1152 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1153 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1154 if ( !CORBA::is_nil( session ) )
1155 session->emitMessageOneWay(msgToGUI.c_str());
1160 //=============================================================================
1162 * Return an option value
1164 //=============================================================================
1166 char* SMESH_Gen_i::GetOption(const char* name)
1170 if ( strcmp(name, "historical_python_dump") == 0 )
1172 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1174 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1176 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1178 if ( strcmp(name, "default_grp_color") == 0 )
1180 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1183 return CORBA::string_dup( "" );
1186 //=============================================================================
1188 * SMESH_Gen_i::CreateMesh
1190 * Create empty mesh on a shape and publish it in the study
1192 //=============================================================================
1194 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1196 Unexpect aCatch(SALOME_SalomeException);
1197 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1199 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1201 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1202 ASSERT( meshServant );
1203 meshServant->SetShape( theShapeObject );
1205 // publish mesh in the study
1206 if ( CanPublishInStudy( mesh ) ) {
1207 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1208 aStudyBuilder->NewCommand(); // There is a transaction
1209 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1210 aStudyBuilder->CommitCommand();
1211 if ( !aSO->_is_nil() ) {
1212 // Update Python script
1213 TPythonDump(this) << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1217 return mesh._retn();
1220 //=============================================================================
1222 * SMESH_Gen_i::CreateEmptyMesh
1226 //=============================================================================
1228 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1230 Unexpect aCatch(SALOME_SalomeException);
1231 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1233 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1235 // publish mesh in the study
1236 if ( CanPublishInStudy( mesh ) ) {
1237 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1238 aStudyBuilder->NewCommand(); // There is a transaction
1239 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1240 aStudyBuilder->CommitCommand();
1241 if ( !aSO->_is_nil() ) {
1242 // Update Python script
1243 TPythonDump(this) << aSO << " = " << this << ".CreateEmptyMesh()";
1247 return mesh._retn();
1252 //================================================================================
1254 * \brief Throw an exception in case if the file can't be read
1256 //================================================================================
1258 void checkFileReadable( const char* theFileName )
1260 SMESH_File f ( theFileName );
1263 if ( !f.error().empty() )
1264 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1266 THROW_SALOME_CORBA_EXCEPTION
1267 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1268 SALOME::BAD_PARAM );
1273 //=============================================================================
1275 * SMESH_Gen_i::CreateMeshFromUNV
1277 * Create mesh and import data from UNV file
1279 //=============================================================================
1281 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1283 Unexpect aCatch(SALOME_SalomeException);
1285 checkFileReadable( theFileName );
1287 SMESH::SMESH_Mesh_var aMesh = createMesh();
1289 // publish mesh in the study
1290 if ( CanPublishInStudy( aMesh ) ) {
1291 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1292 aStudyBuilder->NewCommand(); // There is a transaction
1293 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1294 aStudyBuilder->CommitCommand();
1295 if ( !aSO->_is_nil() ) {
1296 // Update Python script
1297 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1301 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1303 aServant->ImportUNVFile( theFileName );
1305 // Dump creation of groups
1306 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1308 aServant->GetImpl().GetMeshDS()->Modified();
1309 return aMesh._retn();
1312 //=============================================================================
1314 * SMESH_Gen_i::CreateMeshFromMED
1316 * Create mesh and import data from MED file
1318 //=============================================================================
1320 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1321 SMESH::DriverMED_ReadStatus& theStatus,
1322 const char* theCommandNameForPython,
1323 const char* theFileNameForPython)
1326 char bname[ _MAX_FNAME ];
1327 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1328 string aFileName = bname;
1330 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1332 // Retrieve mesh names from the file
1333 DriverMED_R_SMESHDS_Mesh myReader;
1334 myReader.SetFile( theFileName );
1335 myReader.SetMeshId( -1 );
1336 Driver_Mesh::Status aStatus;
1337 list<string> aNames = myReader.GetMeshNames(aStatus);
1338 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1339 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1341 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1344 TPythonDump aPythonDump(this);
1345 aPythonDump << "([";
1347 if (theStatus == SMESH::DRS_OK) {
1348 SALOMEDS::StudyBuilder_var aStudyBuilder;
1349 aStudyBuilder = getStudyServant()->NewBuilder();
1350 aStudyBuilder->NewCommand(); // There is a transaction
1352 aResult->length( aNames.size() );
1355 // Iterate through all meshes and create mesh objects
1356 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1359 if (i > 0) aPythonDump << ", ";
1362 SMESH::SMESH_Mesh_var mesh = createMesh();
1364 // publish mesh in the study
1365 SALOMEDS::SObject_wrap aSO;
1366 if ( CanPublishInStudy( mesh ) )
1367 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1368 // - as names of meshes are stored in MED file, we use them for data publishing
1369 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1370 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1373 if ( !aSO->_is_nil() ) {
1376 aPythonDump << "mesh_" << i;
1379 // Read mesh data (groups are published automatically by ImportMEDFile())
1380 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1381 ASSERT( meshServant );
1382 SMESH::DriverMED_ReadStatus status1 =
1383 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1384 if (status1 > theStatus)
1385 theStatus = status1;
1387 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1388 meshServant->GetImpl().GetMeshDS()->Modified();
1390 if ( !aStudyBuilder->_is_nil() )
1391 aStudyBuilder->CommitCommand();
1394 // Update Python script
1395 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1397 // Dump creation of groups
1398 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1399 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1401 return aResult._retn();
1404 //================================================================================
1406 * \brief Create meshes by reading a MED file
1408 //================================================================================
1410 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1411 SMESH::DriverMED_ReadStatus& theStatus)
1413 Unexpect aCatch(SALOME_SalomeException);
1414 checkFileReadable( theFileName );
1416 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus,
1417 "CreateMeshesFromMED", theFileName);
1421 //=============================================================================
1423 * SMESH_Gen_i::CreateMeshFromSAUV
1425 * Create mesh and import data from SAUV file
1427 //=============================================================================
1429 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1430 SMESH::DriverMED_ReadStatus& theStatus)
1432 Unexpect aCatch(SALOME_SalomeException);
1433 checkFileReadable( theFileName );
1435 std::string sauvfilename(theFileName);
1436 std::string medfilename(theFileName);
1437 medfilename += ".med";
1440 cmd = "%PYTHONBIN% ";
1445 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1447 system(cmd.c_str());
1448 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(),
1450 "CreateMeshesFromSAUV",
1451 sauvfilename.c_str());
1453 cmd = "%PYTHONBIN% ";
1458 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1460 system(cmd.c_str());
1464 //=============================================================================
1466 * SMESH_Gen_i::CreateMeshFromSTL
1468 * Create mesh and import data from STL file
1470 //=============================================================================
1472 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1474 Unexpect aCatch(SALOME_SalomeException);
1475 checkFileReadable( theFileName );
1477 SMESH::SMESH_Mesh_var aMesh = createMesh();
1480 char bname[ _MAX_FNAME ];
1481 _splitpath( theFileName, NULL, NULL, bname, NULL );
1482 string aFileName = bname;
1484 string aFileName = basename( const_cast<char *>(theFileName) );
1486 // publish mesh in the study
1487 if ( CanPublishInStudy( aMesh ) ) {
1488 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1489 aStudyBuilder->NewCommand(); // There is a transaction
1490 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1491 aStudyBuilder->CommitCommand();
1492 if ( !aSO->_is_nil() ) {
1493 // Update Python script
1494 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1498 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1500 aServant->ImportSTLFile( theFileName );
1501 aServant->GetImpl().GetMeshDS()->Modified();
1502 return aMesh._retn();
1505 //================================================================================
1507 * \brief Create meshes and import data from the CGSN file
1509 //================================================================================
1511 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1512 SMESH::DriverMED_ReadStatus& theStatus)
1514 Unexpect aCatch(SALOME_SalomeException);
1515 checkFileReadable( theFileName );
1517 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1520 // Retrieve nb meshes from the file
1521 DriverCGNS_Read myReader;
1522 myReader.SetFile( theFileName );
1523 Driver_Mesh::Status aStatus;
1524 int nbMeshes = myReader.GetNbMeshes(aStatus);
1525 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1527 aResult->length( nbMeshes );
1529 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1532 TPythonDump aPythonDump(this);
1533 aPythonDump << "([";
1535 if (theStatus == SMESH::DRS_OK)
1537 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1538 aStudyBuilder->NewCommand(); // There is a transaction
1542 // Iterate through all meshes and create mesh objects
1543 for ( ; i < nbMeshes; ++i )
1546 if (i > 0) aPythonDump << ", ";
1549 SMESH::SMESH_Mesh_var mesh = createMesh();
1550 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1552 // Read mesh data (groups are published automatically by ImportMEDFile())
1553 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1554 ASSERT( meshServant );
1556 SMESH::DriverMED_ReadStatus status1 =
1557 meshServant->ImportCGNSFile( theFileName, i, meshName );
1558 if (status1 > theStatus)
1559 theStatus = status1;
1561 meshServant->GetImpl().GetMeshDS()->Modified();
1562 // publish mesh in the study
1563 SALOMEDS::SObject_wrap aSO;
1564 if ( CanPublishInStudy( mesh ) )
1565 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1568 if ( !aSO->_is_nil() ) {
1572 aPythonDump << "mesh_" << i;
1575 aStudyBuilder->CommitCommand();
1578 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1580 // Dump creation of groups
1581 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1582 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1584 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1587 return aResult._retn();
1590 //================================================================================
1592 * \brief Create a mesh and import data from a GMF file
1594 //================================================================================
1596 SMESH::SMESH_Mesh_ptr
1597 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1598 CORBA::Boolean theMakeRequiredGroups,
1599 SMESH::ComputeError_out theError)
1601 Unexpect aCatch(SALOME_SalomeException);
1602 checkFileReadable( theFileName );
1604 SMESH::SMESH_Mesh_var aMesh = createMesh();
1606 char bname[ _MAX_FNAME ];
1607 _splitpath( theFileName, NULL, NULL, bname, NULL );
1608 string aFileName = bname;
1610 string aFileName = basename( const_cast<char *>(theFileName) );
1612 // publish mesh in the study
1613 if ( CanPublishInStudy( aMesh ) ) {
1614 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1615 aStudyBuilder->NewCommand(); // There is a transaction
1616 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1617 aStudyBuilder->CommitCommand();
1618 if ( !aSO->_is_nil() ) {
1619 // Update Python script
1620 TPythonDump(this) << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1621 << theFileName << "', "
1622 << theMakeRequiredGroups << " )";
1625 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1627 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1628 aServant->GetImpl().GetMeshDS()->Modified();
1629 return aMesh._retn();
1633 //=============================================================================
1635 * SMESH_Gen_i::IsReadyToCompute
1637 * Return true if mesh contains enough data to be computed
1639 //=============================================================================
1641 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1642 GEOM::GEOM_Object_ptr theShapeObject )
1644 Unexpect aCatch(SALOME_SalomeException);
1645 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1647 if ( CORBA::is_nil( theShapeObject ) )
1648 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1649 SALOME::BAD_PARAM );
1650 if ( CORBA::is_nil( theMesh ) )
1651 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1652 SALOME::BAD_PARAM );
1655 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1656 ASSERT( meshServant );
1657 if ( meshServant ) {
1658 // get local TopoDS_Shape
1659 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1660 // call implementation
1661 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1662 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1665 catch ( SALOME_Exception& S_ex ) {
1666 INFOS( "catch exception "<< S_ex.what() );
1671 //================================================================================
1673 * \brief Find SObject for an algo
1675 //================================================================================
1677 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1680 SALOMEDS::Study_var aStudy = getStudyServant();
1681 if ( !aStudy->_is_nil() ) {
1682 // find algo in the study
1683 CORBA::String_var compDataType = ComponentDataType();
1684 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1685 if ( !father->_is_nil() ) {
1686 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1687 for ( ; itBig->More(); itBig->Next() ) {
1688 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1689 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1690 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1691 for ( ; algoIt->More(); algoIt->Next() ) {
1692 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1693 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1694 if ( !CORBA::is_nil( algoIOR )) {
1695 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1696 if ( impl && impl->GetImpl() == algo )
1697 return algoSO._retn();
1699 } // loop on algo SO's
1702 } // SMESH component iterator
1706 return SALOMEDS::SObject::_nil();
1709 //================================================================================
1711 * \brief Return errors of mesh computation
1713 //================================================================================
1715 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1716 GEOM::GEOM_Object_ptr theSubObject )
1718 Unexpect aCatch(SALOME_SalomeException);
1719 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1721 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1722 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1724 if ( CORBA::is_nil( theMesh ) )
1725 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1727 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1729 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1732 if(theMesh->HasShapeToMesh())
1733 shape = GeomObjectToShape( theSubObject );
1735 shape = SMESH_Mesh::PseudoShape();
1737 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1739 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1742 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1743 const bool includeSelf = true, complexShapeFirst = true;
1744 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1746 while ( smIt->more() )
1749 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1751 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1752 if ( error && !error->IsOK() )
1754 if ( !( error->myAlgo ) &&
1755 !( error->myAlgo = sm->GetAlgo() ))
1757 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1758 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1759 errStruct.comment = error->myComment.c_str();
1760 errStruct.subShapeID = sm->GetId();
1761 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1762 if ( !algoSO->_is_nil() ) {
1763 CORBA::String_var algoName = algoSO->GetName();
1764 errStruct.algoName = algoName;
1767 errStruct.algoName = error->myAlgo->GetName();
1769 errStruct.hasBadMesh = error->HasBadElems();
1772 error_array->length( nbErr );
1775 catch ( SALOME_Exception& S_ex ) {
1776 INFOS( "catch exception "<< S_ex.what() );
1779 return error_array._retn();
1782 //================================================================================
1784 * \brief Return mesh elements preventing computation of a subshape
1786 //================================================================================
1788 SMESH::MeshPreviewStruct*
1789 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1790 CORBA::Short theSubShapeID )
1792 Unexpect aCatch(SALOME_SalomeException);
1793 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1795 if ( CORBA::is_nil( theMesh ) )
1796 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1798 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1801 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1803 // mesh implementation
1804 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1805 // submesh by subshape id
1806 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1809 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1810 if ( error && error->HasBadElems() )
1812 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1813 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1815 // get nodes of elements and count elements
1816 TNode2LocalIDMap mapNode2LocalID;
1817 list< TNodeLocalID > connectivity;
1818 int i, nbElements = 0, nbConnNodes = 0;
1820 const list<const SMDS_MeshElement*>& badElems =
1821 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1822 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1823 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1824 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1826 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1827 while ( nIt->more() )
1828 connectivity.push_back
1829 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1831 // fill node coords and assign local ids to the nodes
1832 int nbNodes = mapNode2LocalID.size();
1833 result->nodesXYZ.length( nbNodes );
1834 TNodeLocalID node2ID = mapNode2LocalID.begin();
1835 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1836 node2ID->second = i;
1837 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1838 result->nodesXYZ[i].x = node->X();
1839 result->nodesXYZ[i].y = node->Y();
1840 result->nodesXYZ[i].z = node->Z();
1842 // fill connectivity
1843 result->elementConnectivities.length( nbConnNodes );
1844 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1845 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1846 result->elementConnectivities[i] = (*connIt)->second;
1848 // fill element types
1849 result->elementTypes.length( nbElements );
1850 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1852 const SMDS_MeshElement* elem = *elemIt;
1853 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1854 result->elementTypes[i].isPoly = elem->IsPoly();
1855 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1861 catch ( SALOME_Exception& S_ex ) {
1862 INFOS( "catch exception "<< S_ex.what() );
1865 return result._retn();
1868 //================================================================================
1870 * \brief Create a group of elements preventing computation of a sub-shape
1872 //================================================================================
1874 SMESH::ListOfGroups*
1875 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1876 CORBA::Short theSubShapeID,
1877 const char* theGroupName )
1879 Unexpect aCatch(SALOME_SalomeException);
1881 SMESH::ListOfGroups_var groups;
1883 if ( CORBA::is_nil( theMesh ) )
1884 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1887 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1889 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1890 TPythonDump(this) << groups << " = " << this
1891 << ".MakeGroupsOfBadInputElements( "
1892 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1895 catch ( SALOME_Exception& S_ex ) {
1896 INFOS( "catch exception "<< S_ex.what() );
1898 return groups._retn();
1901 //================================================================================
1903 * \brief Returns errors of hypotheses definition
1904 * \param theMesh - the mesh
1905 * \param theSubObject - the main or sub- shape
1906 * \retval SMESH::algo_error_array* - sequence of errors
1908 //================================================================================
1910 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1911 GEOM::GEOM_Object_ptr theSubObject )
1913 Unexpect aCatch(SALOME_SalomeException);
1914 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1916 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1917 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1919 if ( CORBA::is_nil( theMesh ) )
1920 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1922 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1924 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1925 ASSERT( meshServant );
1926 if ( meshServant ) {
1927 TopoDS_Shape myLocShape;
1928 if(theMesh->HasShapeToMesh())
1929 myLocShape = GeomObjectToShape( theSubObject );
1931 myLocShape = SMESH_Mesh::PseudoShape();
1933 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1934 list< ::SMESH_Gen::TAlgoStateError > error_list;
1935 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1936 // call ::SMESH_Gen::GetAlgoState()
1937 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1938 error_array->length( error_list.size() );
1940 for ( error = error_list.begin(); error != error_list.end(); ++error )
1942 // fill AlgoStateError structure
1943 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1944 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1945 errStruct.algoDim = error->_algoDim;
1946 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1947 errStruct.algoName = "";
1948 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1949 if ( !algoSO->_is_nil() ) {
1950 CORBA::String_var algoName = algoSO->GetName();
1951 errStruct.algoName = algoName.in();
1956 catch ( SALOME_Exception& S_ex ) {
1957 INFOS( "catch exception "<< S_ex.what() );
1959 return error_array._retn();
1962 //=============================================================================
1964 * SMESH_Gen_i::GetSubShapesId
1966 * Get sub-shapes unique ID's list
1968 //=============================================================================
1971 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1972 const SMESH::object_array& theListOfSubShapeObject )
1974 Unexpect aCatch(SALOME_SalomeException);
1975 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1977 SMESH::long_array_var shapesId = new SMESH::long_array;
1980 if ( CORBA::is_nil( theMainShapeObject ) )
1981 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1985 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1986 TopTools_IndexedMapOfShape myIndexToShape;
1987 TopExp::MapShapes(myMainShape,myIndexToShape);
1989 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1991 GEOM::GEOM_Object_var aShapeObject
1992 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1993 if ( CORBA::is_nil( aShapeObject ) )
1994 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1995 SALOME::BAD_PARAM );
1997 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1998 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
2000 const TopoDS_Face& F = TopoDS::Face(exp.Current());
2001 setId.insert(myIndexToShape.FindIndex(F));
2002 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
2004 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
2006 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
2007 setId.insert(myIndexToShape.FindIndex(E));
2008 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
2010 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
2012 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
2013 setId.insert(myIndexToShape.FindIndex(V));
2014 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
2017 shapesId->length(setId.size());
2018 set<int>::iterator iind;
2020 for (iind = setId.begin(); iind != setId.end(); iind++)
2022 if(MYDEBUG) SCRUTE((*iind));
2023 shapesId[i] = (*iind);
2024 if(MYDEBUG) SCRUTE(shapesId[i]);
2028 catch (SALOME_Exception& S_ex)
2030 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2033 return shapesId._retn();
2036 //=============================================================================
2038 * SMESH_Gen_i::Compute
2040 * Compute mesh on a shape
2042 //=============================================================================
2044 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2045 GEOM::GEOM_Object_ptr theShapeObject )
2048 Unexpect aCatch(SALOME_SalomeException);
2049 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2051 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2052 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2053 SALOME::BAD_PARAM );
2055 if ( CORBA::is_nil( theMesh ) )
2056 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2057 SALOME::BAD_PARAM );
2059 // Update Python script
2060 TPythonDump(this) << "isDone = " << this << ".Compute( "
2061 << theMesh << ", " << theShapeObject << ")";
2065 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2066 ASSERT( meshServant );
2067 if ( meshServant ) {
2068 if ( isGeomModifIcon( theMesh ))
2069 meshServant->Clear();
2071 meshServant->Load();
2072 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2073 meshServant->CheckGeomModif();
2074 // get local TopoDS_Shape
2075 TopoDS_Shape myLocShape;
2076 if(theMesh->HasShapeToMesh())
2077 myLocShape = GeomObjectToShape( theShapeObject );
2079 myLocShape = SMESH_Mesh::PseudoShape();
2080 // call implementation compute
2081 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2082 myGen.PrepareCompute( myLocMesh, myLocShape );
2083 int how = ::SMESH_Gen::COMPACT_MESH;
2084 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2085 how |= ::SMESH_Gen::SHAPE_ONLY;
2086 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2087 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2088 myLocMesh.GetMeshDS()->Modified();
2089 UpdateIcons( theMesh );
2091 HighLightInvalid( theMesh, /*isInvalid=*/false );
2095 catch ( std::bad_alloc& ) {
2096 INFOS( "Compute(): lack of memory" );
2098 catch ( SALOME_Exception& S_ex ) {
2099 INFOS( "Compute(): catch exception "<< S_ex.what() );
2102 INFOS( "Compute(): unknown exception " );
2107 //=============================================================================
2109 * SMESH_Gen_i::CancelCompute
2111 * Cancel Compute mesh on a shape
2113 //=============================================================================
2115 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2116 GEOM::GEOM_Object_ptr theShapeObject )
2118 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2120 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2121 TopoDS_Shape myLocShape;
2122 if(theMesh->HasShapeToMesh())
2123 myLocShape = GeomObjectToShape( theShapeObject );
2125 myLocShape = SMESH_Mesh::PseudoShape();
2126 myGen.CancelCompute( myLocMesh, myLocShape);
2130 //=============================================================================
2132 * SMESH_Gen_i::Precompute
2134 * Compute mesh as preview till indicated dimension on shape
2136 //=============================================================================
2138 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2139 GEOM::GEOM_Object_ptr theShapeObject,
2140 SMESH::Dimension theDimension,
2141 SMESH::long_array& theShapesId)
2143 Unexpect aCatch(SALOME_SalomeException);
2144 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2146 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2147 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2148 SALOME::BAD_PARAM );
2150 if ( CORBA::is_nil( theMesh ) )
2151 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2152 SALOME::BAD_PARAM );
2154 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2157 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2158 meshServant->Load();
2159 ASSERT( meshServant );
2160 if ( meshServant ) {
2161 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2162 meshServant->CheckGeomModif();
2163 // get local TopoDS_Shape
2164 TopoDS_Shape myLocShape;
2165 if(theMesh->HasShapeToMesh())
2166 myLocShape = GeomObjectToShape( theShapeObject );
2168 return result._retn();
2170 // call implementation compute
2171 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2173 ::MeshDimension aDim = (MeshDimension)theDimension;
2174 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2176 int nbShapeId = shapeIds.size();
2177 theShapesId.length( nbShapeId );
2178 // iterates on shapes and collect mesh entities into mesh preview
2179 TSetOfInt::const_iterator idIt = shapeIds.begin();
2180 TSetOfInt::const_iterator idEnd = shapeIds.end();
2181 std::map< int, int > mapOfShIdNb;
2182 std::set< SMESH_TLink > setOfEdge;
2183 std::list< SMDSAbs_ElementType > listOfElemType;
2184 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2185 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2186 TNode2LocalIDMap mapNode2LocalID;
2187 list< TNodeLocalID > connectivity;
2188 int i, nbConnNodes = 0;
2189 std::set< const SMESH_subMesh* > setOfVSubMesh;
2190 // iterates on shapes
2191 for ( ; idIt != idEnd; idIt++ )
2193 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2195 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2196 if ( !sm || !sm->IsMeshComputed() )
2199 const TopoDS_Shape& aSh = sm->GetSubShape();
2200 const int shDim = myGen.GetShapeDim( aSh );
2201 if ( shDim < 1 || shDim > theDimension )
2204 mapOfShIdNb[ *idIt ] = 0;
2205 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2207 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2208 if ( !smDS ) continue;
2210 if ( theDimension == SMESH::DIM_2D )
2212 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2213 while ( faceIt->more() )
2215 const SMDS_MeshElement* face = faceIt->next();
2216 int aNbNode = face->NbNodes();
2218 aNbNode /= 2; // do not take into account additional middle nodes
2220 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2221 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2223 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2224 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2226 listOfElemType.push_back( SMDSAbs_Edge );
2227 connectivity.push_back
2228 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2229 connectivity.push_back
2230 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2236 else if ( theDimension == SMESH::DIM_1D )
2238 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2239 while ( nodeIt->more() )
2241 listOfElemType.push_back( SMDSAbs_Node );
2242 connectivity.push_back
2243 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2245 // add corner nodes by first vertex from edge
2246 SMESH_subMeshIteratorPtr edgeSmIt =
2247 sm->getDependsOnIterator(/*includeSelf*/false,
2248 /*complexShapeFirst*/false);
2249 while ( edgeSmIt->more() )
2251 SMESH_subMesh* vertexSM = edgeSmIt->next();
2252 // check that vertex is not already treated
2253 if ( !setOfVSubMesh.insert( vertexSM ).second )
2255 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2258 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2259 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2260 while ( nodeIt->more() )
2262 listOfElemType.push_back( SMDSAbs_Node );
2263 connectivity.push_back
2264 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2270 // fill node coords and assign local ids to the nodes
2271 int nbNodes = mapNode2LocalID.size();
2272 result->nodesXYZ.length( nbNodes );
2273 TNodeLocalID node2ID = mapNode2LocalID.begin();
2274 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2275 node2ID->second = i;
2276 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2277 result->nodesXYZ[i].x = node->X();
2278 result->nodesXYZ[i].y = node->Y();
2279 result->nodesXYZ[i].z = node->Z();
2281 // fill connectivity
2282 result->elementConnectivities.length( nbConnNodes );
2283 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2284 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2285 result->elementConnectivities[i] = (*connIt)->second;
2288 // fill element types
2289 result->elementTypes.length( listOfElemType.size() );
2290 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2291 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2292 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2294 SMDSAbs_ElementType elemType = *typeIt;
2295 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2296 result->elementTypes[i].isPoly = false;
2297 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2300 // correct number of shapes
2301 theShapesId.length( mapOfShIdNb.size() );
2305 catch ( std::bad_alloc& ) {
2306 INFOS( "Precompute(): lack of memory" );
2308 catch ( SALOME_Exception& S_ex ) {
2309 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2312 INFOS( "Precompute(): unknown exception " );
2314 return result._retn();
2318 //=============================================================================
2320 * SMESH_Gen_i::Evaluate
2322 * Evaluate mesh on a shape
2324 //=============================================================================
2326 SMESH::smIdType_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2327 GEOM::GEOM_Object_ptr theShapeObject)
2329 Unexpect aCatch(SALOME_SalomeException);
2330 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2332 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2333 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2335 if ( CORBA::is_nil( theMesh ) )
2336 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2338 SMESH::smIdType_array_var nbels = new SMESH::smIdType_array;
2339 nbels->length(SMESH::Entity_Last);
2340 int i = SMESH::Entity_Node;
2341 for (; i < SMESH::Entity_Last; i++)
2344 // Update Python script
2345 TPythonDump(this) << "theNbElems = " << this << ".Evaluate( "
2346 << theMesh << ", " << theShapeObject << ")";
2350 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2351 ASSERT( meshServant );
2352 if ( meshServant ) {
2353 meshServant->Load();
2354 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2355 meshServant->CheckGeomModif();
2356 // get local TopoDS_Shape
2357 TopoDS_Shape myLocShape;
2358 if(theMesh->HasShapeToMesh())
2359 myLocShape = GeomObjectToShape( theShapeObject );
2361 myLocShape = SMESH_Mesh::PseudoShape();
2362 // call implementation compute
2363 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2364 MapShapeNbElems aResMap;
2365 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2366 MapShapeNbElemsItr anIt = aResMap.begin();
2367 for(; anIt!=aResMap.end(); anIt++) {
2368 const vector<smIdType>& aVec = (*anIt).second;
2369 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2370 smIdType nbElem = aVec[i];
2371 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2373 SMESH_subMesh* sm = anIt->first;
2374 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2375 const SMESH_Algo* algo = sm->GetAlgo();
2376 if ( (algo && !error.get()) || error->IsOK() )
2377 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2381 nbels[i] += aVec[i];
2385 return nbels._retn();
2388 catch ( std::bad_alloc& ) {
2389 INFOS( "Evaluate(): lack of memory" );
2391 catch ( SALOME_Exception& S_ex ) {
2392 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2395 INFOS( "Evaluate(): unknown exception " );
2398 return nbels._retn();
2401 //================================================================================
2403 * \brief Return geometrical object the given element is built on
2404 * \param theMesh - the mesh the element is in
2405 * \param theElementID - the element ID
2406 * \param theGeomName - the name of the result geom object if it is not yet published
2407 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2409 //================================================================================
2411 GEOM::GEOM_Object_ptr
2412 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2413 SMESH::smIdType theElementID,
2414 const char* theGeomName)
2416 Unexpect aCatch(SALOME_SalomeException);
2418 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2419 if ( !geom->_is_nil() ) {
2420 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2421 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2423 // try to find the corresponding SObject
2424 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2425 if ( SObj->_is_nil() ) // submesh can be not found even if published
2427 // try to find published submesh
2428 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2429 if ( !geom->IsMainShape() && list->length() == 1 ) {
2430 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2431 SALOMEDS::ChildIterator_wrap it;
2432 if ( !mainSO->_is_nil() ) {
2433 it = getStudyServant()->NewChildIterator( mainSO );
2435 if ( !it->_is_nil() ) {
2436 for ( it->InitEx(true); it->More(); it->Next() ) {
2437 SALOMEDS::SObject_wrap so = it->Value();
2438 CORBA::Object_var obj = SObjectToObject( so );
2439 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2440 if ( !subGeom->_is_nil() ) {
2441 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2442 if ( subList->length() == 1 && list[0] == subList[0] ) {
2452 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2453 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2455 // return only published geometry
2456 if ( !SObj->_is_nil() ) {
2457 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2458 CORBA::Object_var obj = SObjectToObject( SObj );
2459 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2463 return GEOM::GEOM_Object::_nil();
2466 //================================================================================
2468 * \brief Return geometrical object the given element is built on.
2469 * \param theMesh - the mesh the element is in
2470 * \param theElementID - the element ID
2471 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2473 //================================================================================
2475 GEOM::GEOM_Object_ptr
2476 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2477 SMESH::smIdType theElementID)
2479 Unexpect aCatch(SALOME_SalomeException);
2480 if ( CORBA::is_nil( theMesh ) )
2481 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2483 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2484 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2486 // get a core mesh DS
2487 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2488 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2490 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2491 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2492 // find the element in mesh
2493 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2494 // find a shape id by the element
2495 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2496 // get a geom object by the shape id
2497 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2498 if ( geom->_is_nil() ) {
2499 // try to find a published sub-shape
2500 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2501 SALOMEDS::ChildIterator_wrap it;
2502 if ( !mainSO->_is_nil() ) {
2503 it = getStudyServant()->NewChildIterator( mainSO );
2505 if ( !it->_is_nil() ) {
2506 for ( it->InitEx(true); it->More(); it->Next() ) {
2507 SALOMEDS::SObject_wrap so = it->Value();
2508 CORBA::Object_var obj = SObjectToObject( so );
2509 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2510 if ( !subGeom->_is_nil() ) {
2511 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2512 if ( subList->length() == 1 && shapeID == subList[0] ) {
2520 if ( geom->_is_nil() ) {
2522 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2523 if ( !op->_is_nil() )
2524 geom = op->GetSubShape( mainShape, shapeID );
2529 if ( !geom->_is_nil() ) {
2530 GeomObjectToShape( geom ); // let geom client remember the found shape
2531 return geom._retn();
2536 return GEOM::GEOM_Object::_nil();
2539 //================================================================================
2541 * SMESH_Gen_i::Concatenate
2543 * Concatenate the given meshes into one mesh
2545 //================================================================================
2547 SMESH::SMESH_Mesh_ptr
2548 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2549 CORBA::Boolean theUniteIdenticalGroups,
2550 CORBA::Boolean theMergeNodesAndElements,
2551 CORBA::Double theMergeTolerance,
2552 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2554 return ConcatenateCommon(theMeshesArray,
2555 theUniteIdenticalGroups,
2556 theMergeNodesAndElements,
2562 //================================================================================
2564 * SMESH_Gen_i::ConcatenateWithGroups
2566 * Concatenate the given meshes into one mesh
2567 * Create the groups of all elements from initial meshes
2569 //================================================================================
2571 SMESH::SMESH_Mesh_ptr
2572 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2573 CORBA::Boolean theUniteIdenticalGroups,
2574 CORBA::Boolean theMergeNodesAndElements,
2575 CORBA::Double theMergeTolerance,
2576 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2578 return ConcatenateCommon(theMeshesArray,
2579 theUniteIdenticalGroups,
2580 theMergeNodesAndElements,
2586 //================================================================================
2588 * SMESH_Gen_i::ConcatenateCommon
2590 * Concatenate the given meshes into one mesh
2592 //================================================================================
2594 SMESH::SMESH_Mesh_ptr
2595 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2596 CORBA::Boolean theUniteIdenticalGroups,
2597 CORBA::Boolean theMergeNodesAndElements,
2598 CORBA::Double theMergeTolerance,
2599 CORBA::Boolean theCommonGroups,
2600 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2602 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump(this) );
2603 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2605 // create mesh if theMeshToAppendTo not provided
2606 SMESH::SMESH_Mesh_var newMesh;
2607 if ( CORBA::is_nil( theMeshToAppendTo ))
2608 newMesh = CreateEmptyMesh();
2610 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2611 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2612 if ( !newImpl ) return newMesh._retn();
2615 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2616 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2618 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2619 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2620 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2621 TGroupsMap groupsMap;
2622 TListOfNewGroups listOfNewGroups;
2624 if ( !CORBA::is_nil( theMeshToAppendTo ))
2626 // fill groupsMap with existing groups
2627 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2628 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2630 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2631 if ( !group->_is_nil() )
2633 CORBA::String_var name = group->GetName();
2634 SMESH::ElementType type = group->GetType();
2635 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2640 ::SMESH_MeshEditor newEditor( &locMesh );
2641 ::SMESH_MeshEditor::ElemFeatures elemType;
2643 // loop on sub-meshes
2644 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2646 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2647 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2648 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2649 if ( !initImpl ) continue;
2650 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2654 // assure that IDs increment by one during iteration
2655 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2656 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2657 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2658 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2660 initMeshDS->Modified();
2661 initMeshDS->CompactMesh();
2664 // remember nb of elements before filling in
2665 SMESH::smIdType_array_var prevState = newMesh->GetNbElementsByType();
2669 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2670 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2671 while ( elemIt->more() )
2673 SMESH_NodeXYZ node = elemIt->next();
2674 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2679 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2680 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2682 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2683 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2684 while ( elemIt->more() )
2686 const SMDS_MeshElement* elem = elemIt->next();
2687 elemType.myNodes.resize( elem->NbNodes() );
2689 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2690 for ( int k = 0; itNodes->more(); k++)
2692 const SMDS_MeshNode* node = itNodes->next();
2693 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2696 // creates a corresponding element on existent nodes in new mesh
2697 newElems[ elem->GetID() ] =
2698 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2700 newEditor.ClearLastCreated(); // forget the history
2703 // create groups of just added elements
2704 SMESH::SMESH_Group_var newGroup;
2705 SMESH::ElementType groupType;
2706 if ( theCommonGroups )
2709 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2711 // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2712 static_assert( sizeof(typeNames) / sizeof(const char*) ==SMESH::NB_ELEMENT_TYPES,
2713 "Update names of ElementType's!!!" );
2715 SMESH::smIdType_array_var curState = newMesh->GetNbElementsByType();
2717 for( groupType = SMESH::NODE;
2718 groupType < SMESH::NB_ELEMENT_TYPES;
2719 groupType = (SMESH::ElementType)( groupType + 1 ))
2721 if ( curState[ groupType ] <= prevState[ groupType ])
2722 continue; // no elements of groupType added from the i-th mesh
2724 // make a group name
2725 std::string groupName = "Gr";
2726 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2728 CORBA::String_var name = meshSO->GetName();
2732 groupName += typeNames[ groupType ];
2734 // make and fill a group
2735 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2736 std::vector< const SMDS_MeshElement* > & elemVec =
2737 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2738 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2740 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2742 for ( size_t j = 0; j < elemVec.size(); ++j )
2744 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2745 grpDS->Add( elemVec[j] );
2749 listOfNewGroups.clear();
2750 listOfNewGroups.push_back( newGroup );
2751 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2756 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2760 SMESH::SMESH_GroupBase_ptr group;
2761 CORBA::String_var groupName;
2762 SMESH::smIdType_array_var newIDs = new SMESH::smIdType_array();
2764 // loop on groups of a source mesh
2765 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2766 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2768 group = listOfGroups[iG];
2769 groupType = group->GetType();
2770 groupName = group->GetName();
2771 std::string name = groupName.in();
2773 // convert a list of IDs
2774 newIDs->length( group->Size() );
2775 std::vector< const SMDS_MeshElement* > & elemVec =
2776 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2777 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2779 while ( itGrElems->more() )
2781 const SMDS_MeshElement* elem = itGrElems->next();
2782 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2784 newIDs[ nbElems++ ] = newElem->GetID();
2786 newIDs->length( nbElems );
2788 // check that a current group name and type don't have identical ones in final mesh
2789 listOfNewGroups.clear();
2790 TNameAndType nameAndType( name, groupType );
2791 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2792 if ( anIter == groupsMap.end() )
2794 // add a new group in the mesh
2795 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2796 newGroup->Add( newIDs );
2798 listOfNewGroups.push_back( newGroup );
2799 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2801 else if ( theUniteIdenticalGroups )
2803 // unite identical groups
2804 TListOfNewGroups& aNewGroups = anIter->second;
2805 aNewGroups.front()->Add( newIDs );
2809 // rename identical groups
2810 newGroup = newImpl->CreateGroup( groupType, groupName );
2811 newGroup->Add( newIDs );
2813 TListOfNewGroups& newGroups = anIter->second;
2814 std::string newGroupName;
2815 if ( newGroups.size() == 1 )
2817 newGroupName = name + "_1";
2818 newGroups.front()->SetName( newGroupName.c_str() );
2820 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2821 newGroup->SetName( newGroupName.c_str() );
2822 newGroups.push_back( newGroup );
2825 } // if an IDSource is a mesh
2828 if ( theMergeNodesAndElements ) // merge nodes
2830 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2831 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2832 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2833 /*SeparateCornersAndMedium=*/ false );
2834 newEditor.MergeNodes( groupsOfNodes );
2836 newEditor.MergeEqualElements();
2839 // Update Python script
2840 pythonDump << newMesh << " = " << this
2841 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2842 << theMeshesArray << ", "
2843 << theUniteIdenticalGroups << ", "
2844 << theMergeNodesAndElements << ", "
2845 << TVar( theMergeTolerance ) << ", "
2846 << theMeshToAppendTo << " )";
2848 pPythonDump.reset(); // enable python dump from GetGroups()
2850 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2851 if ( !newMesh->_is_nil() )
2853 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2856 // IPAL21468 Change icon of compound because it need not be computed.
2857 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2858 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2860 newMeshDS->Modified();
2862 return newMesh._retn();
2865 //================================================================================
2867 * \brief Create a mesh by copying a part of another mesh
2868 * \param meshPart - a part of mesh to copy
2869 * \param toCopyGroups - to create in the new mesh groups
2870 * the copied elements belongs to
2871 * \param toKeepIDs - to preserve IDs of the copied elements or not
2872 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2874 //================================================================================
2876 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2877 const char* meshName,
2878 CORBA::Boolean toCopyGroups,
2879 CORBA::Boolean toKeepIDs)
2881 Unexpect aCatch(SALOME_SalomeException);
2883 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2884 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2886 // 1. Get source mesh
2888 if ( CORBA::is_nil( meshPart ))
2889 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2891 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2892 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2894 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2896 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2898 // 2. Make a new mesh
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, "Mesh" );
2908 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2910 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2911 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2912 ::SMESH_MeshEditor::ElemFeatures elemType;
2914 // 3. Get elements to copy
2916 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2917 TIDSortedElemSet srcElems;
2918 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2919 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2922 srcElemIt = srcMeshDS->elementsIterator();
2923 srcNodeIt = srcMeshDS->nodesIterator();
2927 SMESH::smIdType_array_var ids = meshPart->GetIDs();
2928 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2930 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2931 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2932 srcElems.insert( elem );
2936 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2937 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2938 srcElems.insert( elem );
2940 if ( srcElems.empty() )
2941 return newMesh._retn();
2943 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2944 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2949 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2950 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2951 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2953 const SMDS_MeshNode *nSrc, *nTgt;
2954 vector< const SMDS_MeshNode* > nodes;
2955 while ( srcElemIt->more() )
2957 const SMDS_MeshElement * elem = srcElemIt->next();
2959 nodes.resize( elem->NbNodes());
2960 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2962 for ( iN = 0; nIt->more(); ++iN )
2964 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2965 nTgt = newMeshDS->FindNode( nSrc->GetID());
2967 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2972 for ( iN = 0; nIt->more(); ++iN )
2974 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2975 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2977 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2978 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2982 if ( elem->GetType() != SMDSAbs_Node )
2984 elemType.Init( elem, /*basicOnly=*/false );
2985 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2987 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2988 if ( toCopyGroups && !toKeepIDs )
2989 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2991 } // while ( srcElemIt->more() )
2993 // 4(b). Copy free nodes
2995 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2997 while ( srcNodeIt->more() )
2999 nSrc = srcNodeIt->next();
3000 if ( nSrc->NbInverseElements() == 0 )
3003 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3005 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3012 int nbNewGroups = 0;
3015 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3016 while ( gIt->more() )
3018 SMESH_Group* group = gIt->next();
3019 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3021 // Check group type. We copy nodal groups containing nodes of copied element
3022 SMDSAbs_ElementType groupType = groupDS->GetType();
3023 if ( groupType != SMDSAbs_Node &&
3024 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3025 continue; // group type differs from types of meshPart
3027 // Find copied elements in the group
3028 vector< const SMDS_MeshElement* > groupElems;
3029 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3032 const SMDS_MeshElement* foundElem;
3033 if ( groupType == SMDSAbs_Node )
3035 while ( eIt->more() )
3036 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3037 groupElems.push_back( foundElem );
3041 while ( eIt->more() )
3042 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3043 groupElems.push_back( foundElem );
3048 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3049 if ( e2eMap.empty() ) continue;
3050 smIdType minID = e2eMap.begin()->first->GetID();
3051 smIdType maxID = e2eMap.rbegin()->first->GetID();
3052 TE2EMap::iterator e2e;
3053 while ( eIt->more() && groupElems.size() < e2eMap.size())
3055 const SMDS_MeshElement* e = eIt->next();
3056 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3057 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3058 groupElems.push_back( e2e->second );
3062 if ( !groupElems.empty() )
3064 SMESH::SMESH_Group_var newGroupObj =
3065 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3066 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3068 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3069 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3070 for ( unsigned i = 0; i < groupElems.size(); ++i )
3071 smdsGroup.Add( groupElems[i] );
3079 newMeshDS->Modified();
3081 *pyDump << newMesh << " = " << this
3082 << ".CopyMesh( " << meshPart << ", "
3083 << "'" << meshName << "', "
3084 << toCopyGroups << ", "
3085 << toKeepIDs << ")";
3087 pyDumpDeleter.reset(); // allow dump in GetGroups()
3089 if ( nbNewGroups > 0 ) // dump created groups
3090 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3092 return newMesh._retn();
3096 namespace // utils for CopyMeshWithGeom()
3098 typedef std::map< std::string, std::string > TStr2StrMap;
3099 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3100 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3101 typedef std::map< std::string, int > TName2IndexMap;
3103 //================================================================================
3105 * \brief Return a new sub-shape corresponding to an old one
3107 //================================================================================
3111 SMESH_Mesh_i* mySrcMesh_i;
3112 SMESH_Mesh_i* myNewMesh_i;
3113 SMESH_Gen_i* myGen_i;
3117 TStr2StrMap myOld2NewEntryMap; // map of study entries
3119 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3120 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3121 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3124 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3126 // not directly relating to shape search
3127 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3129 //================================================================================
3131 * \brief Constructor
3133 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3134 SMESH_Mesh_i* newMesh_i,
3135 SMESH_Gen_i* smeshGen_i )
3136 : mySrcMesh_i( srcMesh_i ),
3137 myNewMesh_i( newMesh_i ),
3138 myGen_i ( smeshGen_i ),
3139 myToPublish( smeshGen_i->IsEnablePublish() ),
3140 myGIPMapDone( false )
3142 // retrieve from the study shape mapping made thanks to
3143 // "Set presentation parameters and sub-shapes from arguments" option
3145 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3146 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3147 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3148 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3149 if ( newSO->_is_nil() )
3151 myToPublish = false;
3154 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3156 CORBA::String_var oldEntry = oldSO->GetID();
3157 CORBA::String_var newEntry = newSO->GetID();
3158 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3159 std::string( newEntry.in() )));
3160 std::string newMainEntry = newEntry.in();
3162 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3163 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3164 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3165 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3166 /*groupsOnly=*/false );
3167 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3169 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3170 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3171 bool refFound = false;
3172 for ( ; anIter->More(); anIter->Next() )
3174 SALOMEDS::SObject_wrap so = anIter->Value();
3175 if ( so->ReferencedObject( oldSO.inout() ))
3177 oldEntry = oldSO->GetID();
3178 newEntry = newSO->GetID();
3179 if (( refFound = ( newMainEntry != oldEntry.in() )))
3180 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3181 std::string( newEntry.in() )));
3186 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3187 if ( father->_is_equivalent( mainShapeNew ))
3189 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3190 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3191 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3192 CORBA::String_var name = newSO->GetName();
3194 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3200 //================================================================================
3202 * \brief Find a new sub-shape corresponding to an old one
3204 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3207 return GEOM::GEOM_Object::_duplicate( oldShape );
3209 GEOM::GEOM_Object_var newShape;
3211 if ( CORBA::is_nil( oldShape ))
3212 return newShape._retn();
3214 if ( !isChildOfOld( oldShape ))
3215 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3217 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3218 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3220 // try to find by entry or name
3223 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3224 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3225 if ( o2nID != myOld2NewEntryMap.end() )
3227 newShape = getShapeByEntry( o2nID->second );
3229 if ( newShape->_is_nil() )
3231 CORBA::String_var name = oldShape->GetName();
3232 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3233 if ( n2ind != myName2SubshapeIndex.end() )
3235 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3236 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3237 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3238 if ( oldIndices->length() == 0 ||
3239 newIndices->length() == 0 ||
3240 getShapeType( myNewMesh_i, newIndices[0] ) !=
3241 getShapeType( mySrcMesh_i, oldIndices[0] ))
3242 newShape = GEOM::GEOM_Object::_nil();
3247 if ( newShape->_is_nil() )
3249 // try to construct a new sub-shape using myGIPMap
3251 std::vector< int > newIndices;
3252 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3253 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3255 findNewIDs( oldIndices[i], newIndices );
3257 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3260 newShape = getInPlace( oldShape );
3262 if ( !newIndices.empty() && newShape->_is_nil() )
3264 // search for a sub-shape with same ids
3265 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3266 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3267 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3268 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3270 if ( newShape->_is_nil() )
3273 // create a new shape
3274 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3276 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3278 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3279 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3281 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3282 newIndicesList->length( newIndices.size() );
3283 for ( size_t i = 0; i < newIndices.size(); ++i )
3284 newIndicesList[ i ] = newIndices[ i ];
3285 grOp->UnionIDs( newShape, newIndicesList );
3289 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3290 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3299 if ( !newShape->_is_nil() && myToPublish )
3301 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3302 if ( !newEntry.in() || !newEntry.in()[0] )
3304 CORBA::String_var name = oldShape->GetName();
3305 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3306 newEntry = newShape->GetStudyEntry();
3307 oldEntry = oldShape->GetStudyEntry();
3308 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3309 std::string( newEntry.in() )));
3313 return newShape._retn();
3316 //================================================================================
3318 * \brief Return a study entry of a new shape by study entry of the old one
3320 std::string FindNew( const std::string & oldEntry )
3325 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3326 if ( o2nID != myOld2NewEntryMap.end() )
3327 return o2nID->second;
3329 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3330 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3333 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3334 if ( newShape->_is_nil() )
3335 return std::string();
3337 CORBA::String_var newEntry = newShape->GetStudyEntry();
3338 return newEntry.in();
3341 //================================================================================
3343 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3344 * Return zero if not found or there are more than one new ID
3346 int FindNew( int oldID )
3355 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3357 if ( myGIPMap[ oldID ].length() == 1 )
3359 newID = myGIPMap[ oldID ][ 0 ];
3361 else if ( myGIPMap[ oldID ].length() > 1 &&
3362 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3364 // select a meshed VERTEX
3365 SMESH_subMesh* newSM;
3366 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3367 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3368 ( !newSM->IsEmpty() ))
3369 newID = myGIPMap[ oldID ][ i ];
3375 //================================================================================
3377 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3378 * Return zero if the old shape is not kept as is in the new shape.
3380 int FindNewNotChanged( SMESH_subMesh* oldSM )
3383 return oldSM->GetId();
3385 int newID = FindNew( oldSM->GetId() );
3389 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3393 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3394 // one new sub-shape of the same type.
3396 if ( oldSM->DependsOn().size() !=
3397 newSM->DependsOn().size() )
3400 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3401 while ( srcSMIt->more() )
3403 oldSM = srcSMIt->next();
3404 int newSubID = FindNew( oldSM->GetId() );
3405 if ( getShapeType( myNewMesh_i, newSubID ) !=
3406 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3412 //================================================================================
3414 * \brief Return shape by study entry
3416 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3418 GEOM::GEOM_Object_var shape;
3419 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3420 if ( !so->_is_nil() )
3422 CORBA::Object_var obj = so->GetObject();
3423 shape = GEOM::GEOM_Object::_narrow( obj );
3425 return shape._retn();
3428 //================================================================================
3430 * \brief Fill myGIPMap by calling GetInPlaceMap()
3434 if ( !myGIPMapDone )
3436 myGIPMapDone = true;
3438 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3439 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3440 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3441 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3444 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3448 myGIPMap = new GEOM::ListOfListOfLong();
3453 //================================================================================
3455 * \brief Get new sub-shape by calling GetInPlace()
3457 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3459 GEOM::GEOM_Object_var newShape;
3461 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3462 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3463 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3466 newShape = op->GetInPlace( mainShapeNew, oldShape );
3471 return newShape._retn();
3474 //================================================================================
3476 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3477 * number of found IDs
3479 int findNewIDs( int oldID, std::vector< int >& newIDs )
3481 size_t prevNbIDs = newIDs.size();
3483 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3485 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3486 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3488 return newIDs.size() - prevNbIDs;
3491 //================================================================================
3493 * \brief Check if an object relates to the old shape
3495 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3497 if ( CORBA::is_nil( oldShape ))
3499 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3500 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3501 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3502 mainShapeOld1->_is_equivalent( oldShape ));
3505 //================================================================================
3507 * \brief Return shape type by shape ID
3509 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3511 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3512 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3513 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3516 //================================================================================
3518 * \brief Store a source sub-shape for which a counterpart not found and
3519 * a smesh object invalid due to that
3521 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3522 SALOMEDS::SObject_wrap smeshSO )
3524 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3525 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3527 CORBA::String_var smeshEntry = smeshSO->GetID();
3528 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3532 //================================================================================
3534 * \brief Store a source sub-shape for which a counterpart not found and
3535 * a smesh object invalid due to that
3537 void AddInvalid( std::string geomEntry,
3538 SALOMEDS::SObject_wrap smeshSO )
3540 if ( !geomEntry.empty() )
3542 CORBA::String_var smeshEntry = smeshSO->GetID();
3543 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3547 //================================================================================
3549 * \brief Store a source sub-shape for which a counterpart not found and
3550 * a smesh object invalid due to that
3552 void AddInvalid( int oldGeomID,
3553 SALOMEDS::SObject_wrap smeshSO )
3555 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3556 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3559 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3560 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3562 SMESH_Comment geomName( typeName[ shapeType ]);
3563 geomName << " #" << oldGeomID;
3565 CORBA::String_var smeshEntry = smeshSO->GetID();
3566 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3569 //================================================================================
3571 * \brief Return entries of a source sub-shape for which a counterpart not found and
3572 * of smesh objects invalid due to that
3574 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3575 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3578 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3579 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3581 nbSO += 1 + entry2entrySet->second.size();
3583 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3584 theInvalidEntries->length ( nbSO );
3585 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3587 entry2entrySet = myInvalidMap.begin();
3588 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3590 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3592 std::set< std::string > & entrySet = entry2entrySet->second;
3593 std::set< std::string >::iterator entry = entrySet.begin();
3594 for ( ; entry != entrySet.end(); ++entry )
3596 theInvalidEntries[ iEntry++ ] = entry->c_str();
3598 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3599 if ( !so->_is_nil() )
3600 theInvalidMeshSObjects[ iSO++ ] = so;
3605 }; // struct ShapeMapper
3607 //================================================================================
3609 * \brief Append an item to a CORBA sequence
3611 template < class CORBA_seq, class ITEM >
3612 void append( CORBA_seq& seq, ITEM item )
3614 if ( !CORBA::is_nil( item ))
3616 seq->length( 1 + seq->length() );
3617 seq[ seq->length() - 1 ] = item;
3620 } // namespace // utils for CopyMeshWithGeom()
3622 //================================================================================
3624 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3625 * \param [in] sourceMesh - a mesh to copy
3626 * \param [in] newGeometry - a new geometry
3627 * \param [in] toCopyGroups - to create groups in the new mesh
3628 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3629 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3630 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3631 * \param [out] newMesh - return a new mesh
3632 * \param [out] newGroups - return new groups
3633 * \param [out] newSubmeshes - return new sub-meshes
3634 * \param [out] newHypotheses - return new algorithms and hypotheses
3635 * \param [out] invalidEntries - return study entries of objects whose
3636 * counterparts are not found in the newGeometry, followed by entries
3637 * of mesh sub-objects that are invalid because they depend on a not found
3638 * preceding sub-shape
3639 * \return CORBA::Boolean - is a success
3641 //================================================================================
3643 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3644 GEOM::GEOM_Object_ptr theNewGeometry,
3645 const char* theMeshName,
3646 CORBA::Boolean theToCopyGroups,
3647 CORBA::Boolean theToReuseHypotheses,
3648 CORBA::Boolean theToCopyElements,
3649 SMESH::SMESH_Mesh_out theNewMesh,
3650 SMESH::ListOfGroups_out theNewGroups,
3651 SMESH::submesh_array_out theNewSubmeshes,
3652 SMESH::ListOfHypothesis_out theNewHypotheses,
3653 SMESH::string_array_out theInvalidEntries)
3655 if ( CORBA::is_nil( theSourceMesh ) ||
3656 CORBA::is_nil( theNewGeometry ))
3657 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3659 if ( !theSourceMesh->HasShapeToMesh() )
3660 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3665 TPythonDump pyDump(this); // prevent dump from CreateMesh()
3667 theNewMesh = CreateMesh( theNewGeometry );
3668 theNewGroups = new SMESH::ListOfGroups();
3669 theNewSubmeshes = new SMESH::submesh_array();
3670 theNewHypotheses = new SMESH::ListOfHypothesis();
3671 theInvalidEntries = new SMESH::string_array();
3673 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3675 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3676 GEOM::GEOM_Object_var geom, newGeom;
3677 SALOMEDS::SObject_wrap so;
3679 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3680 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3683 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3685 // treat hypotheses of mesh and sub-meshes
3686 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3687 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3689 bool isSubMesh = ( iSM < smList->length() );
3692 // create a new sub-mesh
3693 SMESH::SMESH_subMesh_var newSM;
3694 geom = smList[iSM]->GetSubShape();
3695 so = ObjectToSObject( smList[iSM] );
3696 CORBA::String_var name;
3697 if ( !so->_is_nil() )
3698 name = so->GetName();
3699 newGeom = shapeMapper.FindNew( geom );
3700 if ( newGeom->_is_nil() )
3702 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3703 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3708 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3710 append( theNewSubmeshes, newSM );
3712 if ( newGeom->_is_nil() )
3713 continue; // don't assign hypotheses
3717 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3719 so = ObjectToSObject( theNewMesh );
3720 SetName( so, theMeshName, "Mesh" );
3723 // assign hypotheses
3724 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3725 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3727 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3728 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3730 // get geometry hyp depends on
3731 std::vector< std::string > entryArray;
3732 std::vector< int > subIDArray;
3733 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3735 if ( !theToReuseHypotheses || dependsOnGeom )
3737 // create a new hypothesis
3738 CORBA::String_var type = hyp->GetName();
3739 CORBA::String_var lib = hyp->GetLibName();
3740 CORBA::String_var data = hyp_i->SaveTo();
3743 hyp = CreateHypothesis( type, lib );
3744 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3745 hyp_i->LoadFrom( data.in() );
3746 append( theNewHypotheses, hyp );
3750 // update geometry hyp depends on
3751 if ( dependsOnGeom )
3753 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3755 if ( !entryArray[ iGeo ].empty() )
3757 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3758 if ( newEntry.empty() )
3761 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3762 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3764 entryArray[ iGeo ] = newEntry;
3767 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3769 if ( subIDArray[ iGeo ] > 0 )
3771 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3775 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3776 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3778 subIDArray[ iGeo ] = newID;
3781 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3785 CORBA::String_var errorText;
3786 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3787 if ( errorText.in()[0] )
3790 } // loop on hypotheses
3791 } // loop on sub-meshes and mesh
3794 // copy mesh elements, keeping IDs
3795 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3796 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3798 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3799 ::SMESH_MeshEditor::ElemFeatures elemData;
3801 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3802 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3803 /*vertexLast=*/false);
3804 while ( srcSMIt->more() )
3806 SMESH_subMesh* srcSM = srcSMIt->next();
3807 if ( srcSM->IsEmpty() )
3808 continue; // not yet computed
3809 int newID = shapeMapper.FindNewNotChanged( srcSM );
3813 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3814 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3815 while ( nIt->more() )
3817 SMESH_NodeXYZ node( nIt->next() );
3818 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3820 const SMDS_PositionPtr pos = node->GetPosition();
3821 const double* uv = pos->GetParameters();
3822 switch ( pos->GetTypeOfPosition() )
3824 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3825 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3826 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3827 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3831 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3832 while( eIt->more() )
3834 const SMDS_MeshElement* e = eIt->next();
3835 elemData.Init( e, /*basicOnly=*/false );
3836 elemData.SetID( e->GetID() );
3837 elemData.myNodes.resize( e->NbNodes() );
3838 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3840 for ( iN = 0; nnIt->more(); ++iN )
3842 const SMDS_MeshNode* srcNode = nnIt->next();
3843 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3844 if ( !elemData.myNodes[ iN ])
3847 if ( iN == elemData.myNodes.size() )
3848 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3849 newMeshDS->SetMeshElementOnShape( newElem, newID );
3851 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3852 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3855 newMeshDS->Modified();
3861 TStr2StrMap old2newGroupMap;
3863 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3865 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3866 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3867 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3869 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3870 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3871 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3873 CORBA::String_var name = groups[ i ]->GetName();
3874 SMESH::ElementType elemType = groups[ i ]->GetType();
3876 SMESH::SMESH_GroupBase_var newGroup;
3878 if ( !stdlGroup->_is_nil() )
3880 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3882 SMESH::smIdType_array_var elemIDs = stdlGroup->GetIDs();
3883 const bool isElem = ( elemType != SMESH::NODE );
3884 CORBA::ULong iE = 0;
3885 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3886 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3888 if ( iE < elemIDs->length() )
3890 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3891 stdlGroup->Add( elemIDs );
3892 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3896 else if ( !geomGroup->_is_nil() )
3898 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3899 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3900 if ( newGeom->_is_nil() )
3902 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3903 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3908 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3911 else if ( !fltrGroup->_is_nil() )
3913 // replace geometry in a filter
3914 SMESH::Filter_var filter = fltrGroup->GetFilter();
3915 SMESH::Filter::Criteria_var criteria;
3916 filter->GetCriteria( criteria.out() );
3918 bool isMissingGroup = false;
3919 std::vector< std::string > badEntries;
3921 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3923 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3924 switch ( criteria[ iCr ].Type )
3926 case SMESH::FT_BelongToMeshGroup:
3928 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3929 btgg->SetGroupID( thresholdID );
3930 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3931 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3932 if ( refGroupSO->_is_nil() )
3934 CORBA::String_var refID = refGroupSO->GetID();
3935 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3936 if ( o2nID == old2newGroupMap.end() )
3938 isMissingGroup = true; // corresponding new group not yet created
3941 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3943 if ( o2nID->second.empty() ) // new referred group is invalid
3944 badEntries.push_back( refID.in() );
3947 case SMESH::FT_BelongToGeom:
3948 case SMESH::FT_BelongToPlane:
3949 case SMESH::FT_BelongToCylinder:
3950 case SMESH::FT_BelongToGenSurface:
3951 case SMESH::FT_LyingOnGeom:
3953 std::string newID = shapeMapper.FindNew( thresholdID );
3954 criteria[ iCr ].ThresholdID = newID.c_str();
3955 if ( newID.empty() )
3956 badEntries.push_back( thresholdID );
3959 case SMESH::FT_ConnectedElements:
3961 if ( thresholdID && thresholdID[0] )
3963 std::string newID = shapeMapper.FindNew( thresholdID );
3964 criteria[ iCr ].ThresholdID = newID.c_str();
3965 if ( newID.empty() )
3966 badEntries.push_back( thresholdID );
3972 } // loop on criteria
3974 if ( isMissingGroup && i < nbGroups )
3976 // to treat the group again
3977 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3981 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3982 newFilter->SetCriteria( criteria );
3984 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3985 newFilter->UnRegister();
3987 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3988 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3989 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3991 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3993 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3996 if ( !badEntries.empty() )
3999 } // treat a group on filter
4001 append( theNewGroups, newGroup );
4003 // fill old2newGroupMap
4004 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4005 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4006 if ( !srcSO->_is_nil() )
4008 CORBA::String_var srcID, newID("");
4009 srcID = srcSO->GetID();
4010 if ( !newSO->_is_nil() )
4011 newID = newSO->GetID();
4012 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4013 std::string( newID.in() )));
4016 if ( newGroup->_is_nil() )
4021 newMeshDS->CompactMesh();
4024 if ( !theMeshName || !theMeshName[0] )
4026 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4027 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4028 CORBA::String_var oldName = soOld->GetName();
4029 SetName( soNew, oldName.in(), "Mesh" );
4031 // mark invalid objects
4032 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4034 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4035 highLightInvalid( invalidSObjects[i].in(), true );
4038 << theNewMesh << ", "
4039 << theNewGroups << ", "
4040 << *theNewSubmeshes.ptr() << ", "
4041 << *theNewHypotheses.ptr() << ", "
4042 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4043 << theSourceMesh << ", "
4044 << theNewGeometry << ", "
4045 << "'" << theMeshName << "', "
4046 << theToCopyGroups << ", "
4047 << theToReuseHypotheses << ", "
4048 << theToCopyElements << " )";
4050 SMESH_CATCH( SMESH::throwCorbaException );
4055 //================================================================================
4057 * \brief Get version of MED format being used.
4059 //================================================================================
4061 char* SMESH_Gen_i::GetMEDFileVersion()
4063 MED::TInt majeur, mineur, release;
4064 majeur = mineur = release = 0;
4065 MED::GetVersionRelease(majeur, mineur, release);
4066 std::ostringstream version;
4067 version << majeur << "." << mineur << "." << release;
4068 return CORBA::string_dup( version.str().c_str() );
4071 //================================================================================
4073 * SMESH_Gen_i::GetMEDVersion
4075 * Get MED version of the file by its name
4077 //================================================================================
4079 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4081 std::string version = MED::GetMEDVersion( theFileName );
4082 return CORBA::string_dup( version.c_str() );
4085 //================================================================================
4087 * SMESH_Gen_i::CheckCompatibility
4089 * Check compatibility of file with MED format being used, read only.
4091 //================================================================================
4093 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4095 return MED::CheckCompatibility( theFileName );
4098 //================================================================================
4100 * SMESH_Gen_i::CheckWriteCompatibility
4102 * Check compatibility of file with MED format being used, for append on write.
4104 //================================================================================
4106 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4108 return MED::CheckCompatibility( theFileName, true );
4111 //================================================================================
4113 * SMESH_Gen_i::GetMeshNames
4115 * Get names of meshes defined in file with the specified name
4117 //================================================================================
4118 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4121 SMESH::string_array_var aResult = new SMESH::string_array();
4122 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4124 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4126 aResult->length( aNbMeshes );
4127 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4128 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4129 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4132 return aResult._retn();
4135 //=============================================================================
4139 * Save SMESH module's data
4141 //=============================================================================
4143 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4148 Kernel_Utils::Localizer loc;
4150 if (!myStudyContext)
4153 // Store study contents as a set of python commands
4156 SALOMEDS::Study_var aStudy = getStudyServant();
4158 // Declare a byte stream
4159 SALOMEDS::TMPFile_var aStreamFile;
4161 // Obtain a temporary dir
4162 TCollection_AsciiString tmpDir =
4163 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4165 // Create a sequence of files processed
4166 SALOMEDS_Tool::ListOfFiles aFileSeq;
4167 aFileSeq.reserve( NUM_TMP_FILES );
4169 TCollection_AsciiString aStudyName( "" );
4171 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4173 // Set names of temporary files
4174 TCollection_AsciiString filename =
4175 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4176 TCollection_AsciiString meshfile =
4177 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4178 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4179 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4180 filename = tmpDir + filename;
4181 meshfile = tmpDir + meshfile;
4184 HDFdataset* aDataset;
4185 HDFgroup* aTopGroup;
4187 HDFgroup* aSubGroup;
4188 HDFgroup* aSubSubGroup;
4189 hdf_size aSize[ 1 ];
4192 //Remove the files if they exist: BugID: 11225
4193 #ifndef WIN32 /* unix functionality */
4194 TCollection_AsciiString cmd("rm -f \"");
4196 TCollection_AsciiString cmd("del /F \"");
4206 system(cmd.ToCString());
4208 // MED writer to be used by storage process
4209 DriverMED_W_SMESHDS_Mesh writer;
4210 writer.SetFile( meshfile.ToCString() );
4211 //writer.SetSaveNumbers( false ); // bos #24400 -- it leads to change of element IDs
4214 // SetStoreName() to groups before storing hypotheses to let them refer to
4215 // groups using "store name", which is "Group <group_persistent_id>"
4217 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4218 for ( ; itBig->More(); itBig->Next() ) {
4219 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4220 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4221 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4222 if ( !CORBA::is_nil( anObject ) ) {
4223 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4224 if ( !myMesh->_is_nil() ) {
4225 myMesh->Load(); // load from study file if not yet done
4226 TPythonDump pd(this); // not to dump GetGroups()
4227 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4228 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4230 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4233 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4234 int anId = myStudyContext->findId( string( objStr.in() ) );
4236 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4237 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4238 aGrpBaseDS->SetStoreName( grpName );
4248 // ---> create HDF file
4249 aFile = new HDFfile( (char*) filename.ToCString() );
4250 aFile->CreateOnDisk();
4252 // --> iterator for top-level objects
4253 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4254 for ( ; itBig->More(); itBig->Next() ) {
4255 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4257 // --> hypotheses root branch (only one for the study)
4258 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4259 // create hypotheses root HDF group
4260 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4261 aTopGroup->CreateOnDisk();
4263 // iterator for all hypotheses
4264 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4265 for ( ; it->More(); it->Next() ) {
4266 SALOMEDS::SObject_wrap mySObject = it->Value();
4267 CORBA::Object_var anObject = SObjectToObject( mySObject );
4268 if ( !CORBA::is_nil( anObject ) ) {
4269 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4270 if ( !myHyp->_is_nil() ) {
4271 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4273 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4274 std::string hypname = hn.in();
4275 std::string libname = ln.in();
4277 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4278 // WIN32 and ".so" for X-system) must be deleted
4279 int libname_len = libname.length();
4281 if( libname_len > 4 )
4282 libname.resize( libname_len - 4 );
4284 // PAL17753 (Regression: missing hypothesis in restored study)
4285 // "lib" also should be removed from the beginning
4286 if( libname_len > 6 )
4287 libname = libname.substr( 3, libname_len - 3 - 3 );
4289 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4290 CORBA::String_var hypdata = myImpl->SaveTo();
4291 int id = myStudyContext->findId( string( objStr.in() ));
4293 // for each hypothesis create HDF group basing on its id
4294 char hypGrpName[30];
4295 sprintf( hypGrpName, "Hypothesis %d", id );
4296 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4297 aGroup->CreateOnDisk();
4298 // --> type name of hypothesis
4299 aSize[ 0 ] = hypname.length() + 1;
4300 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4301 aDataset->CreateOnDisk();
4302 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4303 aDataset->CloseOnDisk();
4304 // --> server plugin library name of hypothesis
4305 aSize[ 0 ] = libname.length() + 1;
4306 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4307 aDataset->CreateOnDisk();
4308 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4309 aDataset->CloseOnDisk();
4310 // --> persistent data of hypothesis
4311 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4312 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4313 aDataset->CreateOnDisk();
4314 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4315 aDataset->CloseOnDisk();
4316 // close hypothesis HDF group
4317 aGroup->CloseOnDisk();
4322 // close hypotheses root HDF group
4323 aTopGroup->CloseOnDisk();
4325 // --> algorithms root branch (only one for the study)
4326 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4327 // create algorithms root HDF group
4328 aTopGroup = new HDFgroup( "Algorithms", aFile );
4329 aTopGroup->CreateOnDisk();
4331 // iterator for all algorithms
4332 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4333 for ( ; it->More(); it->Next() ) {
4334 SALOMEDS::SObject_wrap mySObject = it->Value();
4335 CORBA::Object_var anObject = SObjectToObject( mySObject );
4336 if ( !CORBA::is_nil( anObject ) ) {
4337 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4338 if ( !myHyp->_is_nil() ) {
4339 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4341 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4342 std::string hypname = hn.in();
4343 std::string libname = ln.in();
4345 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4346 // WIN32 and ".so" for X-system) must be deleted
4347 int libname_len = libname.length();
4349 if( libname_len > 4 )
4350 libname.resize( libname_len - 4 );
4352 // PAL17753 (Regression: missing hypothesis in restored study)
4353 // "lib" also should be removed from the beginning
4354 if( libname_len > 6 )
4355 libname = libname.substr( 3, libname_len - 3 - 3 );
4357 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4358 CORBA::String_var hypdata = myImpl->SaveTo();
4359 int id = myStudyContext->findId( string( objStr.in() ) );
4361 // for each algorithm create HDF group basing on its id
4362 char hypGrpName[30];
4363 sprintf( hypGrpName, "Algorithm %d", id );
4364 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4365 aGroup->CreateOnDisk();
4366 // --> type name of algorithm
4367 aSize[0] = hypname.length() + 1;
4368 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4369 aDataset->CreateOnDisk();
4370 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4371 aDataset->CloseOnDisk();
4372 // --> server plugin library name of hypothesis
4373 aSize[0] = libname.length() + 1;
4374 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4375 aDataset->CreateOnDisk();
4376 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4377 aDataset->CloseOnDisk();
4378 // --> persistent data of algorithm
4379 aSize[0] = strlen( hypdata.in() ) + 1;
4380 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4381 aDataset->CreateOnDisk();
4382 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4383 aDataset->CloseOnDisk();
4384 // close algorithm HDF group
4385 aGroup->CloseOnDisk();
4390 // close algorithms root HDF group
4391 aTopGroup->CloseOnDisk();
4393 // --> mesh objects roots branches
4394 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4395 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4396 if ( !CORBA::is_nil( anObject ) ) {
4397 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4398 if ( !myMesh->_is_nil() ) {
4399 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4401 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4402 int id = myStudyContext->findId( string( objStr.in() ) );
4403 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4404 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4405 bool hasShape = myLocMesh.HasShapeToMesh();
4407 // for each mesh open the HDF group basing on its id
4408 char meshGrpName[ 30 ];
4409 sprintf( meshGrpName, "Mesh %d", id );
4410 aTopGroup = new HDFgroup( meshGrpName, aFile );
4411 aTopGroup->CreateOnDisk();
4413 // --> put dataset to hdf file which is a flag that mesh has data
4414 string strHasData = "0";
4415 // check if the mesh is not empty
4416 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4417 // write mesh data to med file
4418 writer.SetMesh( mySMESHDSMesh );
4419 writer.SetMeshId( id );
4422 aSize[ 0 ] = strHasData.length() + 1;
4423 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4424 aDataset->CreateOnDisk();
4425 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4426 aDataset->CloseOnDisk();
4429 // for each mesh open the HDF group basing on its auto color parameter
4430 char meshAutoColorName[ 30 ];
4431 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4433 anAutoColor[0] = myImpl->GetAutoColor();
4435 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4436 aDataset->CreateOnDisk();
4437 aDataset->WriteOnDisk( anAutoColor );
4438 aDataset->CloseOnDisk();
4440 // issue 0020693. Store _isModified flag
4441 int isModified = myLocMesh.GetIsModified();
4443 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4444 aDataset->CreateOnDisk();
4445 aDataset->WriteOnDisk( &isModified );
4446 aDataset->CloseOnDisk();
4448 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4449 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4451 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4452 aDataset->CreateOnDisk();
4453 aDataset->WriteOnDisk( &meshPersistentId );
4454 aDataset->CloseOnDisk();
4456 // Store SMESH_Mesh_i::_mainShapeTick
4457 int shapeTick = myImpl->MainShapeTick();
4459 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4460 aDataset->CreateOnDisk();
4461 aDataset->WriteOnDisk( &shapeTick );
4462 aDataset->CloseOnDisk();
4464 // write reference on a shape if exists
4465 SALOMEDS::SObject_wrap myRef;
4466 bool shapeRefFound = false;
4467 bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4469 SALOMEDS::SObject_wrap myShape;
4470 bool ok = myRef->ReferencedObject( myShape.inout() );
4472 CORBA::Object_var shapeObj = myShape->GetObject();
4473 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4474 CORBA::String_var myRefOnObject = myShape->GetID();
4475 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4476 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4477 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4478 aDataset->CreateOnDisk();
4479 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4480 aDataset->CloseOnDisk();
4486 std::string info = myImpl->FileInfoToString();
4487 if ( !info.empty() )
4489 aSize[ 0 ] = info.size();
4490 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4491 aDataset->CreateOnDisk();
4492 aDataset->WriteOnDisk( (char*) info.data() );
4493 aDataset->CloseOnDisk();
4496 // write applied hypotheses if exist
4497 SALOMEDS::SObject_wrap myHypBranch;
4498 found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4499 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4500 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4502 if ( found && (shapeRefFound || !hasShape) ) {
4503 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4504 aGroup->CreateOnDisk();
4506 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4508 for ( ; it->More(); it->Next() ) {
4509 SALOMEDS::SObject_wrap mySObject = it->Value();
4510 SALOMEDS::SObject_wrap myRefOnHyp;
4511 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4513 // san - it is impossible to recover applied hypotheses
4514 // using their entries within Load() method,
4515 // for there are no AttributeIORs in the study when Load() is working.
4516 // Hence, it is better to store persistent IDs of hypotheses as references to them
4518 //string myRefOnObject = myRefOnHyp->GetID();
4519 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4520 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4521 int id = myStudyContext->findId( string( objStr.in() ) );
4522 //if ( myRefOnObject.length() > 0 ) {
4523 //aSize[ 0 ] = myRefOnObject.length() + 1;
4524 char hypName[ 30 ], hypId[ 30 ];
4525 sprintf( hypName, "Hyp %d", ++hypNb );
4526 sprintf( hypId, "%d", id );
4527 aSize[ 0 ] = strlen( hypId ) + 1;
4528 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4529 aDataset->CreateOnDisk();
4530 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4531 aDataset->WriteOnDisk( hypId );
4532 aDataset->CloseOnDisk();
4536 aGroup->CloseOnDisk();
4539 // write applied algorithms if exist
4540 SALOMEDS::SObject_wrap myAlgoBranch;
4541 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4542 myAlgoBranch.inout() );
4543 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4544 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4546 if ( found && (shapeRefFound || !hasShape)) {
4547 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4548 aGroup->CreateOnDisk();
4550 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4552 for ( ; it->More(); it->Next() ) {
4553 SALOMEDS::SObject_wrap mySObject = it->Value();
4554 SALOMEDS::SObject_wrap myRefOnAlgo;
4555 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4557 // san - it is impossible to recover applied algorithms
4558 // using their entries within Load() method,
4559 // for there are no AttributeIORs in the study when Load() is working.
4560 // Hence, it is better to store persistent IDs of algorithms as references to them
4562 //string myRefOnObject = myRefOnAlgo->GetID();
4563 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4564 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4565 int id = myStudyContext->findId( string( objStr.in() ) );
4566 //if ( myRefOnObject.length() > 0 ) {
4567 //aSize[ 0 ] = myRefOnObject.length() + 1;
4568 char algoName[ 30 ], algoId[ 30 ];
4569 sprintf( algoName, "Algo %d", ++algoNb );
4570 sprintf( algoId, "%d", id );
4571 aSize[ 0 ] = strlen( algoId ) + 1;
4572 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4573 aDataset->CreateOnDisk();
4574 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4575 aDataset->WriteOnDisk( algoId );
4576 aDataset->CloseOnDisk();
4580 aGroup->CloseOnDisk();
4583 // --> submesh objects sub-branches
4585 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4586 SALOMEDS::SObject_wrap mySubmeshBranch;
4587 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4589 if ( found ) // check if there is shape reference in submeshes
4591 bool hasShapeRef = false;
4592 SALOMEDS::ChildIterator_wrap itSM =
4593 aStudy->NewChildIterator( mySubmeshBranch );
4594 for ( ; itSM->More(); itSM->Next() ) {
4595 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4596 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4597 mySubRef->ReferencedObject( myShape.inout() );
4598 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4601 { // remove one submesh
4602 if ( shapeRefFound )
4603 { // unassign hypothesis
4604 SMESH::SMESH_subMesh_var mySubMesh =
4605 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4606 if ( !mySubMesh->_is_nil() ) {
4607 int shapeID = mySubMesh->GetId();
4608 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4609 const list<const SMESHDS_Hypothesis*>& hypList =
4610 mySMESHDSMesh->GetHypothesis( S );
4611 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4612 while ( hyp != hypList.end() ) {
4613 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4614 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4618 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4620 } // loop on submeshes of a type
4621 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4622 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4625 } // end check if there is shape reference in submeshes
4627 char name_meshgroup[ 30 ];
4628 if ( i == GetSubMeshOnVertexTag() )
4629 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4630 else if ( i == GetSubMeshOnEdgeTag() )
4631 strcpy( name_meshgroup, "SubMeshes On Edge" );
4632 else if ( i == GetSubMeshOnWireTag() )
4633 strcpy( name_meshgroup, "SubMeshes On Wire" );
4634 else if ( i == GetSubMeshOnFaceTag() )
4635 strcpy( name_meshgroup, "SubMeshes On Face" );
4636 else if ( i == GetSubMeshOnShellTag() )
4637 strcpy( name_meshgroup, "SubMeshes On Shell" );
4638 else if ( i == GetSubMeshOnSolidTag() )
4639 strcpy( name_meshgroup, "SubMeshes On Solid" );
4640 else if ( i == GetSubMeshOnCompoundTag() )
4641 strcpy( name_meshgroup, "SubMeshes On Compound" );
4643 // for each type of submeshes create container HDF group
4644 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4645 aGroup->CreateOnDisk();
4647 // iterator for all submeshes of given type
4648 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4649 for ( ; itSM->More(); itSM->Next() ) {
4650 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4651 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4652 if ( !CORBA::is_nil( anSubObject ))
4654 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4655 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4656 int subid = myStudyContext->findId( string( objStr.in() ) );
4658 // for each mesh open the HDF group basing on its id
4659 char submeshGrpName[ 30 ];
4660 sprintf( submeshGrpName, "SubMesh %d", subid );
4661 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4662 aSubGroup->CreateOnDisk();
4664 // write reference on a shape, already checked if it exists
4665 SALOMEDS::SObject_wrap mySubRef, myShape;
4666 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4667 mySubRef->ReferencedObject( myShape.inout() );
4668 string myRefOnObject = myShape->GetID();
4669 if ( myRefOnObject.length() > 0 ) {
4670 aSize[ 0 ] = myRefOnObject.length() + 1;
4671 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4672 aDataset->CreateOnDisk();
4673 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4674 aDataset->CloseOnDisk();
4677 // write applied hypotheses if exist
4678 SALOMEDS::SObject_wrap mySubHypBranch;
4679 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4680 mySubHypBranch.inout() );
4682 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4683 aSubSubGroup->CreateOnDisk();
4685 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4687 for ( ; it->More(); it->Next() ) {
4688 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4689 SALOMEDS::SObject_wrap myRefOnHyp;
4690 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4692 //string myRefOnObject = myRefOnHyp->GetID();
4693 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4694 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4695 int id = myStudyContext->findId( string( objStr.in() ) );
4696 //if ( myRefOnObject.length() > 0 ) {
4697 //aSize[ 0 ] = myRefOnObject.length() + 1;
4698 char hypName[ 30 ], hypId[ 30 ];
4699 sprintf( hypName, "Hyp %d", ++hypNb );
4700 sprintf( hypId, "%d", id );
4701 aSize[ 0 ] = strlen( hypId ) + 1;
4702 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4703 aDataset->CreateOnDisk();
4704 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4705 aDataset->WriteOnDisk( hypId );
4706 aDataset->CloseOnDisk();
4710 aSubSubGroup->CloseOnDisk();
4713 // write applied algorithms if exist
4714 SALOMEDS::SObject_wrap mySubAlgoBranch;
4715 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4716 mySubAlgoBranch.inout() );
4718 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4719 aSubSubGroup->CreateOnDisk();
4721 SALOMEDS::ChildIterator_wrap it =
4722 aStudy->NewChildIterator( mySubAlgoBranch );
4724 for ( ; it->More(); it->Next() ) {
4725 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4726 SALOMEDS::SObject_wrap myRefOnAlgo;
4727 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4729 //string myRefOnObject = myRefOnAlgo->GetID();
4730 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4731 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4732 int id = myStudyContext->findId( string( objStr.in() ) );
4733 //if ( myRefOnObject.length() > 0 ) {
4734 //aSize[ 0 ] = myRefOnObject.length() + 1;
4735 char algoName[ 30 ], algoId[ 30 ];
4736 sprintf( algoName, "Algo %d", ++algoNb );
4737 sprintf( algoId, "%d", id );
4738 aSize[ 0 ] = strlen( algoId ) + 1;
4739 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4740 aDataset->CreateOnDisk();
4741 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4742 aDataset->WriteOnDisk( algoId );
4743 aDataset->CloseOnDisk();
4747 aSubSubGroup->CloseOnDisk();
4749 // close submesh HDF group
4750 aSubGroup->CloseOnDisk();
4753 // close container of submeshes by type HDF group
4754 aGroup->CloseOnDisk();
4758 // store submesh order if any
4759 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4760 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4761 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4762 char order_list[ 30 ];
4763 strcpy( order_list, "Mesh Order" );
4764 // count number of submesh ids
4766 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4767 for ( ; idIt != theOrderIds.end(); idIt++ )
4768 nbIDs += (*idIt).size();
4769 // number of values = number of IDs +
4770 // number of lists (for separators) - 1
4771 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4772 idIt = theOrderIds.begin();
4773 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4774 const TListOfInt& idList = *idIt;
4775 if (idIt != theOrderIds.begin()) // not first list
4776 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4777 // dump submesh ids from current list
4778 TListOfInt::const_iterator id_smId = idList.begin();
4779 for( ; id_smId != idList.end(); id_smId++ )
4780 smIDs[ i++ ] = *id_smId;
4783 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4785 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4786 aDataset->CreateOnDisk();
4787 aDataset->WriteOnDisk( smIDs );
4788 aDataset->CloseOnDisk();
4792 if ( !theOrderIds.empty() && isNewOrederVersion )
4794 // convert ids to entries
4795 std::list< std::list< std::string > > orderEntryLists;
4796 for ( const TListOfInt& idList : theOrderIds )
4798 orderEntryLists.emplace_back();
4799 std::list< std::string > & entryList = orderEntryLists.back();
4800 for ( const int& id : idList )
4802 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4803 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4804 SALOMEDS::SObject_var so = ObjectToSObject( go );
4805 if ( !so->_is_nil() )
4807 CORBA::String_var entry = so->GetID();
4808 entryList.emplace_back( entry.in() );
4812 // convert orderEntryLists to string
4813 std::ostringstream ostream;
4814 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4815 std::string orderEntryString = ostream.str();
4818 aSize[ 0 ] = orderEntryString.size() + 1;
4819 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4820 aDataset->CreateOnDisk();
4821 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4822 aDataset->CloseOnDisk();
4825 // groups root sub-branch
4826 SALOMEDS::SObject_wrap myGroupsBranch;
4827 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4828 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4830 char name_group[ 30 ];
4831 if ( i == GetNodeGroupsTag() )
4832 strcpy( name_group, "Groups of Nodes" );
4833 else if ( i == GetEdgeGroupsTag() )
4834 strcpy( name_group, "Groups of Edges" );
4835 else if ( i == GetFaceGroupsTag() )
4836 strcpy( name_group, "Groups of Faces" );
4837 else if ( i == GetVolumeGroupsTag() )
4838 strcpy( name_group, "Groups of Volumes" );
4839 else if ( i == Get0DElementsGroupsTag() )
4840 strcpy( name_group, "Groups of 0D Elements" );
4841 else if ( i == GetBallElementsGroupsTag() )
4842 strcpy( name_group, "Groups of Balls" );
4844 aGroup = new HDFgroup( name_group, aTopGroup );
4845 aGroup->CreateOnDisk();
4847 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4848 for ( ; it->More(); it->Next() ) {
4849 SALOMEDS::SObject_wrap mySObject = it->Value();
4850 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4851 if ( !CORBA::is_nil( aSubObject ) ) {
4852 SMESH_GroupBase_i* myGroupImpl =
4853 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4856 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4860 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4861 int anId = myStudyContext->findId( string( objStr.in() ) );
4863 // For each group, create a dataset named "Group <group_persistent_id>"
4864 // and store the group's user name into it
4865 const char* grpName = aGrpBaseDS->GetStoreName();
4866 CORBA::String_var aUserName = myGroupImpl->GetName();
4867 aSize[ 0 ] = strlen( aUserName ) + 1;
4869 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4870 aDataset->CreateOnDisk();
4871 aDataset->WriteOnDisk( aUserName );
4872 aDataset->CloseOnDisk();
4875 // For each group, create a dataset named "Group <group_persistent_id> Color"
4876 // and store the group's color into it
4877 char grpColorName[ 30 ];
4878 sprintf( grpColorName, "ColorGroup %d", anId );
4879 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4881 anRGB[ 0 ] = aColor.R;
4882 anRGB[ 1 ] = aColor.G;
4883 anRGB[ 2 ] = aColor.B;
4885 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4886 aDataset->CreateOnDisk();
4887 aDataset->WriteOnDisk( anRGB );
4888 aDataset->CloseOnDisk();
4890 // Pass SMESHDS_Group to MED writer
4891 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4893 writer.AddGroup( aGrpDS );
4895 // write reference on a shape if exists
4896 SMESHDS_GroupOnGeom* aGeomGrp =
4897 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4899 SALOMEDS::SObject_wrap mySubRef, myShape;
4900 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4901 mySubRef->ReferencedObject( myShape.inout() ) &&
4902 !CORBA::is_nil( myShape->GetObject() ))
4904 CORBA::String_var myRefOnObject = myShape->GetID();
4905 if ( myRefOnObject.in()[0] ) {
4906 char aRefName[ 30 ];
4907 sprintf( aRefName, "Ref on shape %d", anId);
4908 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4909 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4910 aDataset->CreateOnDisk();
4911 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4912 aDataset->CloseOnDisk();
4915 else // shape ref is invalid:
4917 // save a group on geometry as ordinary group
4918 writer.AddGroup( aGeomGrp );
4921 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4922 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4924 std::string str = aFilterGrp_i->FilterToString();
4925 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4926 aSize[ 0 ] = str.length() + 1;
4927 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4928 aDataset->CreateOnDisk();
4929 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4930 aDataset->CloseOnDisk();
4934 aGroup->CloseOnDisk();
4938 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4940 // Flush current mesh information into MED file
4943 // save info on nb of elements
4944 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4946 // maybe a shape was deleted in the study
4947 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4948 TopoDS_Shape nullShape;
4949 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4952 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4957 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4958 aGroup->CreateOnDisk();
4960 // each element belongs to one or none submesh,
4961 // so for each node/element, we store a submesh ID
4963 // Store submesh IDs
4964 for ( int isNode = 0; isNode < 2; ++isNode )
4966 SMDS_ElemIteratorPtr eIt =
4967 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4968 smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4971 std::vector<int> smIDs; smIDs.reserve( nbElems );
4972 while ( eIt->more() )
4973 if ( const SMDS_MeshElement* e = eIt->next())
4974 smIDs.push_back( e->getshapeId() );
4976 aSize[ 0 ] = nbElems;
4977 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4978 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4979 aDataset->CreateOnDisk();
4980 aDataset->WriteOnDisk( & smIDs[0] );
4981 aDataset->CloseOnDisk();
4984 aGroup->CloseOnDisk();
4986 // Store node positions on sub-shapes (SMDS_Position):
4987 // ----------------------------------------------------
4989 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4990 aGroup->CreateOnDisk();
4992 // in aGroup, create 5 datasets to contain:
4993 // "Nodes on Edges" - ID of node on edge
4994 // "Edge positions" - U parameter on node on edge
4995 // "Nodes on Faces" - ID of node on face
4996 // "Face U positions" - U parameter of node on face
4997 // "Face V positions" - V parameter of node on face
4999 // Find out nb of nodes on edges and faces
5000 // Collect corresponding sub-meshes
5001 int nbEdgeNodes = 0, nbFaceNodes = 0;
5002 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5003 // loop on SMESHDS_SubMesh'es
5004 while ( smIt->more() )
5006 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5007 if ( aSubMesh->IsComplexSubmesh() )
5008 continue; // submesh containing other submeshs
5009 smIdType nbNodes = aSubMesh->NbNodes();
5010 if ( nbNodes == 0 ) continue;
5012 int aShapeID = aSubMesh->GetID();
5013 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5015 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5016 // write only SMDS_FacePosition and SMDS_EdgePosition
5017 switch ( aShapeType ) {
5019 nbFaceNodes += nbNodes;
5020 aFaceSM.push_back( aSubMesh );
5023 nbEdgeNodes += nbNodes;
5024 aEdgeSM.push_back( aSubMesh );
5030 // Treat positions on edges or faces
5031 for ( int onFace = 0; onFace < 2; onFace++ )
5033 // Create arrays to store in datasets
5034 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5035 if (!nbNodes) continue;
5036 int* aNodeIDs = new int [ nbNodes ];
5037 double* aUPos = new double [ nbNodes ];
5038 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5041 // loop on sub-meshes
5042 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5043 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5044 for ( ; itSM != pListSM->end(); itSM++ )
5046 SMESHDS_SubMesh* aSubMesh = (*itSM);
5048 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5049 // loop on nodes in aSubMesh
5050 while ( itNode->more() )
5053 const SMDS_MeshNode* node = itNode->next();
5054 aNodeIDs [ iNode ] = node->GetID();
5057 const SMDS_PositionPtr pos = node->GetPosition();
5058 if ( onFace ) { // on FACE
5059 SMDS_FacePositionPtr fPos = pos;
5061 aUPos[ iNode ] = fPos->GetUParameter();
5062 aVPos[ iNode ] = fPos->GetVParameter();
5069 SMDS_EdgePositionPtr ePos = pos;
5071 aUPos[ iNode ] = ePos->GetUParameter();
5077 } // loop on nodes in aSubMesh
5078 } // loop on sub-meshes
5083 aSize[ 0 ] = nbNodes;
5085 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5086 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5087 aDataset->CreateOnDisk();
5088 aDataset->WriteOnDisk( aNodeIDs );
5089 aDataset->CloseOnDisk();
5092 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5093 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5094 aDataset->CreateOnDisk();
5095 aDataset->WriteOnDisk( aUPos );
5096 aDataset->CloseOnDisk();
5099 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5100 aDataset->CreateOnDisk();
5101 aDataset->WriteOnDisk( aVPos );
5102 aDataset->CloseOnDisk();
5107 if ( aVPos ) delete [] aVPos;
5109 } // treat positions on edges or faces
5111 // close "Node Positions" group
5112 aGroup->CloseOnDisk();
5114 } // if ( there are submeshes in SMESHDS_Mesh )
5117 // close mesh HDF group
5118 aTopGroup->CloseOnDisk();
5126 aFile->CloseOnDisk();
5129 // Convert temporary files to stream
5130 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5132 // Remove temporary files and directory
5134 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5136 return aStreamFile._retn();
5139 //=============================================================================
5141 * SMESH_Gen_i::SaveASCII
5143 * Save SMESH module's data in ASCII format
5145 //=============================================================================
5147 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5149 bool isMultiFile ) {
5150 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5151 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5152 return aStreamFile._retn();
5154 //after usual saving needs to encipher binary to text string
5155 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5156 int size = aStreamFile.in().length();
5157 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5158 for ( int i = 0; i < size; i++ )
5159 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5161 buffer[size * 3] = '\0';
5163 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5165 return anAsciiStreamFile._retn();
5168 //=============================================================================
5172 * Load SMESH module's data
5174 //=============================================================================
5176 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5177 const SALOMEDS::TMPFile& theStream,
5181 UpdateStudy(); // load geom data
5182 Kernel_Utils::Localizer loc;
5184 SALOMEDS::Study_var aStudy = getStudyServant();
5186 // Get temporary files location
5187 TCollection_AsciiString tmpDir =
5188 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5190 // Convert the stream into sequence of files to process
5191 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5194 TCollection_AsciiString aStudyName( "" );
5195 if ( isMultiFile ) {
5196 CORBA::WString_var url = aStudy->URL();
5197 SMESHUtils::ArrayDeleter<const char> urlMulibyte( Kernel_Utils::encode( url.in()) );
5198 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( urlMulibyte.get() ).c_str();
5200 // Set names of temporary files
5201 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5202 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5206 HDFdataset* aDataset;
5207 HDFgroup* aTopGroup;
5209 HDFgroup* aSubGroup;
5210 HDFgroup* aSubSubGroup;
5213 // ---> open HDF file
5214 aFile = new HDFfile( (char*) filename.ToCString() );
5216 aFile->OpenOnDisk( HDF_RDONLY );
5218 catch ( HDFexception ) {
5219 INFOS( "Load(): " << filename << " not found!" );
5223 TPythonDump pd(this); // prevent dump during loading
5225 // For PAL13473 ("Repetitive mesh") implementation.
5226 // New dependencies between SMESH objects are established:
5227 // now hypotheses can refer to meshes, shapes and other hypotheses.
5228 // To keep data consistent, the following order of data restoration
5230 // 1. Create hypotheses
5231 // 2. Create all meshes
5232 // 3. Load hypotheses' data
5235 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5236 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5237 list< SMESH::Filter_var > filters;
5239 // get total number of top-level groups
5240 int aNbGroups = aFile->nInternalObjects();
5241 if ( aNbGroups > 0 ) {
5242 // --> in first turn we should read&create hypotheses
5243 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5244 // open hypotheses root HDF group
5245 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5246 aTopGroup->OpenOnDisk();
5248 // get number of hypotheses
5249 int aNbObjects = aTopGroup->nInternalObjects();
5250 for ( int j = 0; j < aNbObjects; j++ ) {
5251 // try to identify hypothesis
5252 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5253 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5255 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5256 // open hypothesis group
5257 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5258 aGroup->OpenOnDisk();
5260 // --> get hypothesis id
5261 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5266 // get number of datasets
5267 int aNbSubObjects = aGroup->nInternalObjects();
5268 for ( int k = 0; k < aNbSubObjects; k++ ) {
5270 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5271 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5272 // --> get hypothesis name
5273 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5274 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5275 aDataset->OpenOnDisk();
5276 size = aDataset->GetSize();
5277 char* hypname_str = new char[ size ];
5278 aDataset->ReadFromDisk( hypname_str );
5279 hypname = string( hypname_str );
5280 delete [] hypname_str;
5281 aDataset->CloseOnDisk();
5283 // --> get hypothesis plugin library name
5284 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5285 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5286 aDataset->OpenOnDisk();
5287 size = aDataset->GetSize();
5288 char* libname_str = new char[ size ];
5289 aDataset->ReadFromDisk( libname_str );
5290 if(MYDEBUG) SCRUTE( libname_str );
5291 libname = string( libname_str );
5292 delete [] libname_str;
5293 aDataset->CloseOnDisk();
5295 // --> get hypothesis data
5296 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5297 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5298 aDataset->OpenOnDisk();
5299 size = aDataset->GetSize();
5300 char* hypdata_str = new char[ size ];
5301 aDataset->ReadFromDisk( hypdata_str );
5302 hypdata = string( hypdata_str );
5303 delete [] hypdata_str;
5304 aDataset->CloseOnDisk();
5307 // close hypothesis HDF group
5308 aGroup->CloseOnDisk();
5310 // --> restore hypothesis from data
5311 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5312 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5313 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5314 SMESH::SMESH_Hypothesis_var myHyp;
5316 try { // protect persistence mechanism against exceptions
5317 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5320 INFOS( "Exception during hypothesis creation" );
5323 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5325 // myImpl->LoadFrom( hypdata.c_str() );
5326 hypDataList.push_back( make_pair( myImpl, hypdata ));
5327 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5328 int newId = myStudyContext->findId( iorString.in() );
5329 myStudyContext->mapOldToNew( id, newId );
5332 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5336 // close hypotheses root HDF group
5337 aTopGroup->CloseOnDisk();
5341 // --> then we should read&create algorithms
5342 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5343 // open algorithms root HDF group
5344 aTopGroup = new HDFgroup( "Algorithms", aFile );
5345 aTopGroup->OpenOnDisk();
5347 // get number of algorithms
5348 int aNbObjects = aTopGroup->nInternalObjects();
5349 for ( int j = 0; j < aNbObjects; j++ ) {
5350 // try to identify algorithm
5351 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5352 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5354 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5355 // open algorithm group
5356 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5357 aGroup->OpenOnDisk();
5359 // --> get algorithm id
5360 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5365 // get number of datasets
5366 int aNbSubObjects = aGroup->nInternalObjects();
5367 for ( int k = 0; k < aNbSubObjects; k++ ) {
5369 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5370 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5371 // --> get algorithm name
5372 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5373 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5374 aDataset->OpenOnDisk();
5375 size = aDataset->GetSize();
5376 char* hypname_str = new char[ size ];
5377 aDataset->ReadFromDisk( hypname_str );
5378 hypname = string( hypname_str );
5379 delete [] hypname_str;
5380 aDataset->CloseOnDisk();
5382 // --> get algorithm plugin library name
5383 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5384 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5385 aDataset->OpenOnDisk();
5386 size = aDataset->GetSize();
5387 char* libname_str = new char[ size ];
5388 aDataset->ReadFromDisk( libname_str );
5389 if(MYDEBUG) SCRUTE( libname_str );
5390 libname = string( libname_str );
5391 delete [] libname_str;
5392 aDataset->CloseOnDisk();
5394 // --> get algorithm data
5395 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5396 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5397 aDataset->OpenOnDisk();
5398 size = aDataset->GetSize();
5399 char* hypdata_str = new char[ size ];
5400 aDataset->ReadFromDisk( hypdata_str );
5401 if(MYDEBUG) SCRUTE( hypdata_str );
5402 hypdata = string( hypdata_str );
5403 delete [] hypdata_str;
5404 aDataset->CloseOnDisk();
5407 // close algorithm HDF group
5408 aGroup->CloseOnDisk();
5410 // --> restore algorithm from data
5411 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5412 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5413 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5414 SMESH::SMESH_Hypothesis_var myHyp;
5416 try { // protect persistence mechanism against exceptions
5417 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5419 catch( SALOME::SALOME_Exception& ex )
5421 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5424 INFOS( "Exception during hypothesis creation" );
5427 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5429 //myImpl->LoadFrom( hypdata.c_str() );
5430 hypDataList.push_back( make_pair( myImpl, hypdata ));
5431 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5432 int newId = myStudyContext->findId( iorString.in() );
5433 myStudyContext->mapOldToNew( id, newId );
5436 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5440 // close algorithms root HDF group
5441 aTopGroup->CloseOnDisk();
5445 // --> the rest groups should be meshes
5446 for ( int i = 0; i < aNbGroups; i++ ) {
5447 // identify next group
5448 char meshName[ HDF_NAME_MAX_LEN+1 ];
5449 aFile->InternalObjectIndentify( i, meshName );
5451 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5453 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5457 // open mesh HDF group
5458 aTopGroup = new HDFgroup( meshName, aFile );
5459 aTopGroup->OpenOnDisk();
5461 // get number of child HDF objects
5462 int aNbObjects = aTopGroup->nInternalObjects();
5463 if ( aNbObjects > 0 ) {
5465 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5466 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5467 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5468 if ( !myNewMeshImpl )
5470 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5472 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5473 int newId = myStudyContext->findId( iorString.in() );
5474 myStudyContext->mapOldToNew( id, newId );
5477 // try to read and set auto color flag
5478 char aMeshAutoColorName[ 30 ];
5479 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5480 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5482 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5483 aDataset->OpenOnDisk();
5484 size = aDataset->GetSize();
5485 int* anAutoColor = new int[ size ];
5486 aDataset->ReadFromDisk( anAutoColor );
5487 aDataset->CloseOnDisk();
5488 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5489 delete [] anAutoColor;
5492 // try to read and set reference to shape
5493 GEOM::GEOM_Object_var aShapeObject;
5494 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5495 // load mesh "Ref on shape" - it's an entry to SObject
5496 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5497 aDataset->OpenOnDisk();
5498 size = aDataset->GetSize();
5499 char* refFromFile = new char[ size ];
5500 aDataset->ReadFromDisk( refFromFile );
5501 aDataset->CloseOnDisk();
5502 if ( strlen( refFromFile ) > 0 ) {
5503 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5504 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5505 if ( !CORBA::is_nil( shapeObject ) ) {
5506 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5507 if ( !aShapeObject->_is_nil() )
5508 myNewMeshImpl->SetShape( aShapeObject );
5511 delete [] refFromFile;
5514 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5515 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5517 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5518 aDataset->OpenOnDisk();
5519 size = aDataset->GetSize();
5520 int* meshPersistentId = new int[ size ];
5521 aDataset->ReadFromDisk( meshPersistentId );
5522 aDataset->CloseOnDisk();
5523 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5524 delete [] meshPersistentId;
5527 // Restore SMESH_Mesh_i::_mainShapeTick
5528 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5530 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5531 aDataset->OpenOnDisk();
5532 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5533 aDataset->ReadFromDisk( shapeTick );
5534 aDataset->CloseOnDisk();
5537 // Restore file info
5538 if ( aTopGroup->ExistInternalObject( "file info" ))
5540 aDataset = new HDFdataset( "file info", aTopGroup );
5541 aDataset->OpenOnDisk();
5542 size = aDataset->GetSize();
5543 std::string info( size, ' ');
5544 aDataset->ReadFromDisk( (char*) info.data() );
5545 aDataset->CloseOnDisk();
5546 myNewMeshImpl->FileInfoFromString( info );
5552 // As all objects that can be referred by hypothesis are created,
5553 // we can restore hypothesis data
5555 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5556 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5558 SMESH_Hypothesis_i* hyp = hyp_data->first;
5559 string & data = hyp_data->second;
5560 hyp->LoadFrom( data.c_str() );
5563 // Restore the rest mesh data
5565 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5566 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5568 aTopGroup = meshi_group->second;
5569 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5571 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5572 bool hasData = false;
5575 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5576 int newId = myStudyContext->findId( iorString.in() );
5577 int meshOldId = myStudyContext->getOldId( newId );
5579 // try to find mesh data dataset
5580 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5581 // load mesh "has data" flag
5582 aDataset = new HDFdataset( "Has data", aTopGroup );
5583 aDataset->OpenOnDisk();
5584 size = aDataset->GetSize();
5585 char* strHasData = new char[ size ];
5586 aDataset->ReadFromDisk( strHasData );
5587 aDataset->CloseOnDisk();
5588 if ( strcmp( strHasData, "1") == 0 ) {
5591 delete [] strHasData;
5594 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5595 // nodes and elements are not yet put into sub-meshes)
5596 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5597 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5598 aGroup->OpenOnDisk();
5599 // get number of applied algorithms
5600 int aNbSubObjects = aGroup->nInternalObjects();
5601 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5602 for ( int j = 0; j < aNbSubObjects; j++ ) {
5603 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5604 aGroup->InternalObjectIndentify( j, name_dataset );
5605 // check if it is an algorithm
5606 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5607 aDataset = new HDFdataset( name_dataset, aGroup );
5608 aDataset->OpenOnDisk();
5609 size = aDataset->GetSize();
5610 char* refFromFile = new char[ size ];
5611 aDataset->ReadFromDisk( refFromFile );
5612 aDataset->CloseOnDisk();
5613 // san - it is impossible to recover applied algorithms using their entries within Load() method
5614 int id = atoi( refFromFile );
5615 delete [] refFromFile;
5616 string anIOR = myStudyContext->getIORbyOldId( id );
5617 if ( !anIOR.empty() ) {
5618 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5619 if ( !CORBA::is_nil( hypObject ) ) {
5620 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5621 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5622 || !myNewMeshImpl->HasShapeToMesh()) )
5623 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5628 aGroup->CloseOnDisk();
5631 // try to get applied hypotheses
5632 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5633 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5634 aGroup->OpenOnDisk();
5635 // get number of applied hypotheses
5636 int aNbSubObjects = aGroup->nInternalObjects();
5637 for ( int j = 0; j < aNbSubObjects; j++ ) {
5638 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5639 aGroup->InternalObjectIndentify( j, name_dataset );
5640 // check if it is a hypothesis
5641 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5642 aDataset = new HDFdataset( name_dataset, aGroup );
5643 aDataset->OpenOnDisk();
5644 size = aDataset->GetSize();
5645 char* refFromFile = new char[ size ];
5646 aDataset->ReadFromDisk( refFromFile );
5647 aDataset->CloseOnDisk();
5648 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5649 int id = atoi( refFromFile );
5650 delete [] refFromFile;
5651 string anIOR = myStudyContext->getIORbyOldId( id );
5652 if ( !anIOR.empty() ) {
5653 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5654 if ( !CORBA::is_nil( hypObject ) ) {
5655 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5656 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5657 || !myNewMeshImpl->HasShapeToMesh()) )
5658 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5663 aGroup->CloseOnDisk();
5666 // --> try to find SUB-MESHES containers for each type of submesh
5667 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5668 const char* name_meshgroup = 0;
5669 if ( j == GetSubMeshOnVertexTag() )
5670 name_meshgroup = "SubMeshes On Vertex";
5671 else if ( j == GetSubMeshOnEdgeTag() )
5672 name_meshgroup = "SubMeshes On Edge";
5673 else if ( j == GetSubMeshOnWireTag() )
5674 name_meshgroup = "SubMeshes On Wire";
5675 else if ( j == GetSubMeshOnFaceTag() )
5676 name_meshgroup = "SubMeshes On Face";
5677 else if ( j == GetSubMeshOnShellTag() )
5678 name_meshgroup = "SubMeshes On Shell";
5679 else if ( j == GetSubMeshOnSolidTag() )
5680 name_meshgroup = "SubMeshes On Solid";
5681 else if ( j == GetSubMeshOnCompoundTag() )
5682 name_meshgroup = "SubMeshes On Compound";
5684 // try to get submeshes container HDF group
5685 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5686 // open submeshes containers HDF group
5687 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5688 aGroup->OpenOnDisk();
5690 // get number of submeshes
5691 int aNbSubMeshes = aGroup->nInternalObjects();
5692 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5694 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5695 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5696 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5697 // --> get submesh id
5698 int subid = atoi( name_submeshgroup + 7 );
5701 // open submesh HDF group
5702 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5703 aSubGroup->OpenOnDisk();
5705 // try to read and set reference to subshape
5706 GEOM::GEOM_Object_var aSubShapeObject;
5707 SMESH::SMESH_subMesh_var aSubMesh;
5709 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5710 // load submesh "Ref on shape" - it's an entry to SObject
5711 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5712 aDataset->OpenOnDisk();
5713 size = aDataset->GetSize();
5714 char* refFromFile = new char[ size ];
5715 aDataset->ReadFromDisk( refFromFile );
5716 aDataset->CloseOnDisk();
5717 if ( strlen( refFromFile ) > 0 ) {
5718 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5719 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5720 if ( !CORBA::is_nil( subShapeObject ) ) {
5721 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5722 if ( !aSubShapeObject->_is_nil() )
5723 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5724 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5725 if ( aSubMesh->_is_nil() )
5727 string iorSubString = GetORB()->object_to_string( aSubMesh );
5728 int newSubId = myStudyContext->findId( iorSubString );
5729 myStudyContext->mapOldToNew( subid, newSubId );
5732 delete [] refFromFile;
5735 if ( aSubMesh->_is_nil() )
5738 // try to get applied algorithms
5739 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5740 // open "applied algorithms" HDF group
5741 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5742 aSubSubGroup->OpenOnDisk();
5743 // get number of applied algorithms
5744 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5745 for ( int l = 0; l < aNbSubObjects; l++ ) {
5746 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5747 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5748 // check if it is an algorithm
5749 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5750 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5751 aDataset->OpenOnDisk();
5752 size = aDataset->GetSize();
5753 char* refFromFile = new char[ size ];
5754 aDataset->ReadFromDisk( refFromFile );
5755 aDataset->CloseOnDisk();
5757 int id = atoi( refFromFile );
5758 string anIOR = myStudyContext->getIORbyOldId( id );
5759 if ( !anIOR.empty() ) {
5760 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5761 if ( !CORBA::is_nil( hypObject ) ) {
5762 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5763 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5764 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5767 delete [] refFromFile;
5770 // close "applied algorithms" HDF group
5771 aSubSubGroup->CloseOnDisk();
5774 // try to get applied hypotheses
5775 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5776 // open "applied hypotheses" HDF group
5777 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5778 aSubSubGroup->OpenOnDisk();
5779 // get number of applied hypotheses
5780 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5781 for ( int l = 0; l < aNbSubObjects; l++ ) {
5782 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5783 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5784 // check if it is a hypothesis
5785 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5786 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5787 aDataset->OpenOnDisk();
5788 size = aDataset->GetSize();
5789 char* refFromFile = new char[ size ];
5790 aDataset->ReadFromDisk( refFromFile );
5791 aDataset->CloseOnDisk();
5793 int id = atoi( refFromFile );
5794 string anIOR = myStudyContext->getIORbyOldId( id );
5795 if ( !anIOR.empty() ) {
5796 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5797 if ( !CORBA::is_nil( hypObject ) ) {
5798 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5799 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5800 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5803 delete [] refFromFile;
5806 // close "APPLIED HYPOTHESES" hdf group
5807 aSubSubGroup->CloseOnDisk();
5810 // close SUB-MESH hdf group
5811 aSubGroup->CloseOnDisk();
5814 // close SUB-MESHES containers hdf group
5815 aGroup->CloseOnDisk();
5819 // try to get GROUPS
5820 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5821 char name_group[ 30 ];
5822 if ( ii == GetNodeGroupsTag() )
5823 strcpy( name_group, "Groups of Nodes" );
5824 else if ( ii == GetEdgeGroupsTag() )
5825 strcpy( name_group, "Groups of Edges" );
5826 else if ( ii == GetFaceGroupsTag() )
5827 strcpy( name_group, "Groups of Faces" );
5828 else if ( ii == GetVolumeGroupsTag() )
5829 strcpy( name_group, "Groups of Volumes" );
5830 else if ( ii == Get0DElementsGroupsTag() )
5831 strcpy( name_group, "Groups of 0D Elements" );
5832 else if ( ii == GetBallElementsGroupsTag() )
5833 strcpy( name_group, "Groups of Balls" );
5835 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5836 aGroup = new HDFgroup( name_group, aTopGroup );
5837 aGroup->OpenOnDisk();
5838 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5839 // within aGroup->ExistInternalObject( name )
5840 std::vector< std::string > subNames;
5841 TColStd_MapOfAsciiString mapOfNames;
5842 aGroup->GetAllObjects( subNames );
5843 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5844 mapOfNames.Add( subNames[ iN ].c_str() );
5846 for ( size_t j = 0; j < subNames.size(); j++ ) {
5847 const std::string& name_dataset = subNames[ j ];
5848 // check if it is a group
5849 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5852 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5855 int groupID = -1; // group local ID (also persistent)
5857 groupID = atoi( endptr + 1 );
5858 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5859 aDataset->OpenOnDisk();
5861 // Retrieve actual group name
5862 size = aDataset->GetSize();
5863 char* nameFromFile = new char[ size ];
5864 aDataset->ReadFromDisk( nameFromFile );
5865 aDataset->CloseOnDisk();
5867 // Try to find a shape reference
5868 TopoDS_Shape aShape;
5869 char aRefName[ 30 ];
5870 sprintf( aRefName, "Ref on shape %d", subid);
5871 if ( mapOfNames.Contains( aRefName ))
5873 // load mesh "Ref on shape" - it's an entry to SObject
5874 aDataset = new HDFdataset( aRefName, aGroup );
5875 aDataset->OpenOnDisk();
5876 size = aDataset->GetSize();
5877 char* refFromFile = new char[ size ];
5878 aDataset->ReadFromDisk( refFromFile );
5879 aDataset->CloseOnDisk();
5880 if ( strlen( refFromFile ) > 0 ) {
5881 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5882 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5883 if ( !CORBA::is_nil( shapeObject ) ) {
5884 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5885 if ( !aShapeObject->_is_nil() )
5886 aShape = GeomObjectToShape( aShapeObject );
5889 delete [] refFromFile;
5891 // Try to read a filter of SMESH_GroupOnFilter
5892 SMESH::Filter_var filter;
5893 SMESH_PredicatePtr predicate;
5894 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5895 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5897 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5898 aDataset->OpenOnDisk();
5899 size = aDataset->GetSize();
5900 char* persistStr = new char[ size ];
5901 aDataset->ReadFromDisk( persistStr );
5902 aDataset->CloseOnDisk();
5903 if ( strlen( persistStr ) > 0 ) {
5904 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5905 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5906 filters.push_back( filter );
5908 delete [] persistStr;
5911 // Create group servant
5912 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5913 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5914 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5915 delete [] nameFromFile;
5916 // Obtain a SMESHDS_Group object
5917 if ( aNewGroup->_is_nil() )
5920 CORBA::String_var iorSubStringVar = GetORB()->object_to_string( aNewGroup );
5921 string iorSubString(iorSubStringVar.in());
5922 int newSubId = myStudyContext->findId( iorSubString );
5923 myStudyContext->mapOldToNew( subid, newSubId );
5925 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5929 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5930 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5932 aFilterGroup->SetFilter( filter );
5933 filter->UnRegister();
5935 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5936 if ( !aGroupBaseDS )
5939 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5942 // Read color of the group
5943 char aGroupColorName[ 30 ];
5944 sprintf( aGroupColorName, "ColorGroup %d", subid);
5945 if ( mapOfNames.Contains( aGroupColorName ))
5947 aDataset = new HDFdataset( aGroupColorName, aGroup );
5948 aDataset->OpenOnDisk();
5949 size = aDataset->GetSize();
5950 double* anRGB = new double[ size ];
5951 aDataset->ReadFromDisk( anRGB );
5952 aDataset->CloseOnDisk();
5953 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5954 aGroupBaseDS->SetColor( aColor );
5959 aGroup->CloseOnDisk();
5963 // instead of reading mesh data, we read only brief information of all
5964 // objects: mesh, groups, sub-meshes (issue 0021208)
5967 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5968 meshfile.ToCString(), filename.ToCString(),
5972 // read Sub-Mesh ORDER if any
5973 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
5974 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5975 aDataset->OpenOnDisk();
5976 size = aDataset->GetSize();
5977 int* smIDs = new int[ size ];
5978 aDataset->ReadFromDisk( smIDs );
5979 aDataset->CloseOnDisk();
5980 TListOfListOfInt anOrderIds;
5981 anOrderIds.push_back( TListOfInt() );
5982 for ( int i = 0; i < size; i++ )
5983 if ( smIDs[ i ] < 0 ) // is separator
5984 anOrderIds.push_back( TListOfInt() );
5986 anOrderIds.back().push_back(smIDs[ i ]);
5988 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5991 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
5993 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
5994 aDataset->OpenOnDisk();
5995 size = aDataset->GetSize();
5996 std::string dataString; dataString.resize( size );
5997 aDataset->ReadFromDisk((char*) dataString.data() );
5998 aDataset->CloseOnDisk();
6000 std::list< std::list< std::string > > orderEntryLists;
6001 SMESHUtils::BoostTxtArchive( dataString ) >> orderEntryLists;
6003 TListOfListOfInt anOrderIds;
6004 for ( const std::list< std::string >& entryList : orderEntryLists )
6006 anOrderIds.emplace_back();
6007 for ( const std::string & entry : entryList )
6009 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6010 TopoDS_Shape shape = GeomObjectToShape( go );
6011 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6012 anOrderIds.back().emplace_back( sm->GetId() );
6015 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6019 // update hyps needing full mesh data restored (issue 20918)
6020 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6022 SMESH_Hypothesis_i* hyp = hyp_data->first;
6023 hyp->UpdateAsMeshesRestored();
6026 // notify algos on completed restoration to set sub-mesh event listeners
6027 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6029 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6030 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6032 TopoDS_Shape myLocShape;
6033 if(myLocMesh.HasShapeToMesh())
6034 myLocShape = myLocMesh.GetShapeToMesh();
6036 myLocShape = SMESH_Mesh::PseudoShape();
6038 myLocMesh.GetSubMesh(myLocShape)->
6039 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6042 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6043 list< SMESH::Filter_var >::iterator f = filters.begin();
6044 for ( ; f != filters.end(); ++f )
6045 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6046 fi->FindBaseObjects();
6051 aTopGroup->CloseOnDisk();
6054 aFile->CloseOnDisk();
6057 // Remove temporary files created from the stream
6060 SMESH_File meshFile( meshfile.ToCString() );
6061 if ( !meshFile ) // no meshfile exists
6063 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6067 Engines::Container_var container = GetContainerRef();
6068 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6070 container_i->registerTemporaryFile( filename.ToCString() );
6071 container_i->registerTemporaryFile( meshfile.ToCString() );
6072 container_i->registerTemporaryFile( tmpDir.ToCString() );
6077 // creation of tree nodes for all data objects in the study
6078 // to support tree representation customization and drag-n-drop:
6079 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6080 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6081 useCaseBuilder->SetRootCurrent();
6082 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6083 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6084 for (it->InitEx(true); it->More(); it->Next()) {
6085 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6092 //=============================================================================
6094 * SMESH_Gen_i::LoadASCII
6096 * Load SMESH module's data in ASCII format
6098 //=============================================================================
6100 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6101 const SALOMEDS::TMPFile& theStream,
6103 bool isMultiFile ) {
6104 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6105 return Load( theComponent, theStream, theURL, isMultiFile );
6107 //before call main ::Load method it's need for decipher text format to
6108 //binary ( "|xx" => x' )
6109 int size = theStream.length();
6110 if ( int((size / 3 )*3) != size ) //error size of buffer
6113 int real_size = int(size / 3);
6115 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6118 unsigned int c = -1;
6119 for ( int i = 0; i < real_size; i++ )
6121 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6122 sscanf( tmp, "%x", &c );
6123 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6126 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6128 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6131 //=============================================================================
6133 * SMESH_Gen_i::Close
6135 * Clears study-connected data when it is closed
6137 //=============================================================================
6139 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6141 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6143 // Clear study contexts data
6144 myStudyContext->Clear();
6146 // remove the tmp files meshes are loaded from
6147 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6149 // Clean trace of API methods calls
6155 //=============================================================================
6157 * SMESH_Gen_i::ComponentDataType
6159 * Get component data type
6161 //=============================================================================
6163 char* SMESH_Gen_i::ComponentDataType()
6165 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6166 return CORBA::string_dup( "SMESH" );
6170 //=============================================================================
6172 * SMESH_Gen_i::IORToLocalPersistentID
6174 * Transform data from transient form to persistent
6176 //=============================================================================
6178 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6179 const char* IORString,
6180 CORBA::Boolean /*isMultiFile*/,
6181 CORBA::Boolean /*isASCII*/ )
6183 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6185 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6186 int anId = myStudyContext->findId( IORString );
6188 if(MYDEBUG) MESSAGE( "VSR " << anId )
6190 sprintf( strId, "%d", anId );
6191 return CORBA::string_dup( strId );
6194 return CORBA::string_dup( "" );
6197 //=============================================================================
6199 * SMESH_Gen_i::LocalPersistentIDToIOR
6201 * Transform data from persistent form to transient
6203 //=============================================================================
6205 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6206 const char* aLocalPersistentID,
6207 CORBA::Boolean /*isMultiFile*/,
6208 CORBA::Boolean /*isASCII*/ )
6210 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6212 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6213 int anId = atoi( aLocalPersistentID );
6214 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6216 return CORBA::string_dup( "" );
6219 //=======================================================================
6220 //function : RegisterObject
6222 //=======================================================================
6224 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6226 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6227 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6228 return myStudyContext->addObject( string( iorString.in() ) );
6233 //================================================================================
6235 * \brief Return id of registered object
6236 * \param theObject - the Object
6237 * \retval int - Object id
6239 //================================================================================
6241 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6243 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6244 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6245 string iorStringCpp(iorString.in());
6246 return myStudyContext->findId( iorStringCpp );
6251 //=============================================================================
6253 * SMESH_Gen_i::SetName
6255 * Set a new object name
6257 //=============================================================================
6259 void SMESH_Gen_i::SetName(const char* theIOR,
6260 const char* theName)
6262 if ( theIOR && strcmp( theIOR, "" ) ) {
6263 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6264 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6265 if ( !aSO->_is_nil() ) {
6266 SetName( aSO, theName );
6271 // Version information
6272 char* SMESH_Gen_i::getVersion()
6274 #if SMESH_DEVELOPMENT
6275 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6277 return CORBA::string_dup(SMESH_VERSION_STR);
6281 //=================================================================================
6282 // function : Move()
6283 // purpose : Moves objects to the specified position.
6284 // Is used in the drag-n-drop functionality.
6285 //=================================================================================
6287 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6288 SALOMEDS::SObject_ptr where,
6291 if ( CORBA::is_nil( where ) ) return;
6293 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6294 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6295 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6296 std::string dataType = father->ComponentDataType();
6297 if ( dataType != "SMESH" ) return; // not a SMESH component
6299 SALOMEDS::SObject_var objAfter;
6300 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6301 // insert at given row -> find insertion position
6302 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6304 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6305 if ( i == row && useCaseIt->More() ) {
6306 objAfter = useCaseIt->Value();
6310 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6311 SALOMEDS::SObject_var sobj = what[i];
6312 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6313 // insert the object to the use case tree
6314 if ( !CORBA::is_nil( objAfter ) )
6315 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6317 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6320 //================================================================================
6322 * \brief Returns true if algorithm can be used to mesh a given geometry
6323 * \param [in] theAlgoType - the algorithm type
6324 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6325 * \param [in] theGeomObject - the geometry to mesh
6326 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6327 * else, returns \c True if at least one shape is meshable
6328 * \return CORBA::Boolean - can or can't
6330 //================================================================================
6332 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6333 const char* theLibName,
6334 GEOM::GEOM_Object_ptr theGeomObject,
6335 CORBA::Boolean toCheckAll)
6339 std::string aPlatformLibName;
6340 GenericHypothesisCreator_i* aCreator =
6341 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6344 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6345 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6346 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6353 SMESH_CATCH( SMESH::doNothing );
6356 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6361 //================================================================================
6363 * \brief Collect indices of elements, which are located inside the sphere
6365 //================================================================================
6367 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6368 SMESH::ElementType theElemType,
6374 SMESH::long_array_var aResult = new SMESH::long_array();
6375 if ( meshPart->_is_nil() )
6376 return aResult._retn();
6378 // 1. Create geometrical object
6379 gp_Pnt aP( theX, theY, theZ );
6380 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6382 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6384 if ( lst.size() > 0 ) {
6385 aResult->length( lst.size() );
6386 for ( size_t i = 0; i < lst.size(); i++ ) {
6387 aResult[i] = lst[i];
6390 return aResult._retn();
6393 //================================================================================
6395 * \brief Collect indices of elements, which are located inside the box
6397 //================================================================================
6399 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6400 SMESH::ElementType theElemType,
6401 CORBA::Double theX1,
6402 CORBA::Double theY1,
6403 CORBA::Double theZ1,
6404 CORBA::Double theX2,
6405 CORBA::Double theY2,
6406 CORBA::Double theZ2)
6408 SMESH::long_array_var aResult = new SMESH::long_array();
6409 if( meshPart->_is_nil() )
6410 return aResult._retn();
6412 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6413 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6415 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6417 if( lst.size() > 0 ) {
6418 aResult->length( lst.size() );
6419 for ( size_t i = 0; i < lst.size(); i++ ) {
6420 aResult[i] = lst[i];
6423 return aResult._retn();
6426 //================================================================================
6428 * \brief Collect indices of elements, which are located inside the cylinder
6430 //================================================================================
6432 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6433 SMESH::ElementType theElemType,
6437 CORBA::Double theDX,
6438 CORBA::Double theDY,
6439 CORBA::Double theDZ,
6441 CORBA::Double theR )
6443 SMESH::long_array_var aResult = new SMESH::long_array();
6444 if( meshPart->_is_nil() )
6445 return aResult._retn();
6447 gp_Pnt aP( theX, theY, theZ );
6448 gp_Vec aV( theDX, theDY, theDZ );
6449 gp_Ax2 anAxes (aP, aV);
6451 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6453 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6455 if( lst.size() > 0 ) {
6456 aResult->length( lst.size() );
6457 for ( size_t i = 0; i < lst.size(); i++ ) {
6458 aResult[i] = lst[i];
6461 return aResult._retn();
6464 //================================================================================
6466 * \brief Collect indices of elements, which are located inside the geom object
6468 //================================================================================
6470 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6471 SMESH::ElementType theElemType,
6472 GEOM::GEOM_Object_ptr theGeom,
6473 CORBA::Double theTolerance )
6475 SMESH::long_array_var aResult = new SMESH::long_array();
6476 if( meshPart->_is_nil() || theGeom->_is_nil() )
6477 return aResult._retn();
6479 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6481 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6483 if( lst.size() > 0 ) {
6484 aResult->length( lst.size() );
6485 for ( size_t i = 0; i < lst.size(); i++ ) {
6486 aResult[i] = lst[i];
6489 return aResult._retn();
6492 //================================================================================
6494 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6496 //================================================================================
6498 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6499 SMESH::ElementType theElemType,
6500 const TopoDS_Shape& theShape,
6501 double* theTolerance) {
6503 std::vector<long> res;
6504 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6506 if ( mesh->_is_nil() )
6509 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6513 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6518 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6519 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6520 anElementsOnShape->SetAllNodes( true );
6521 anElementsOnShape->SetMesh( meshDS );
6522 anElementsOnShape->SetShape( theShape, aType );
6525 anElementsOnShape->SetTolerance(*theTolerance);
6527 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6528 if ( !msource->_is_nil() ) { // Mesh case
6529 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6531 while ( elemIt->more() ) {
6532 const SMDS_MeshElement* anElem = elemIt->next();
6533 long anId = anElem->GetID();
6534 if ( anElementsOnShape->IsSatisfy( anId ) )
6535 res.push_back( anId );
6539 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6540 if ( !gsource->_is_nil() ) {
6541 if(theElemType == SMESH::NODE) {
6542 SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6543 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6544 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6545 long anId = node->GetID();
6546 if ( anElementsOnShape->IsSatisfy( anId ) )
6547 res.push_back( anId );
6550 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6551 SMESH::smIdType_array_var elems = gsource->GetListOfID();
6552 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6553 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6554 long anId = elem->GetID();
6555 if ( anElementsOnShape->IsSatisfy( anId ) )
6556 res.push_back( anId );
6561 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6562 if ( !smsource->_is_nil() ) {
6563 SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6564 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6565 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6567 long anId = elem->GetID();
6568 if ( anElementsOnShape->IsSatisfy( anId ) )
6569 res.push_back( anId );