1 // Copyright (C) 2007-2016 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
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>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_SetIterator.hxx"
89 #include "SMDS_SpacePosition.hxx"
90 #include "SMDS_VertexPosition.hxx"
91 #include "SMESHDS_Document.hxx"
92 #include "SMESHDS_Group.hxx"
93 #include "SMESHDS_GroupOnGeom.hxx"
94 #include "SMESH_Algo_i.hxx"
95 #include "SMESH_File.hxx"
96 #include "SMESH_Group.hxx"
97 #include "SMESH_Group_i.hxx"
98 #include "SMESH_Hypothesis.hxx"
99 #include "SMESH_Hypothesis_i.hxx"
100 #include "SMESH_Mesh.hxx"
101 #include "SMESH_MeshEditor.hxx"
102 #include "SMESH_Mesh_i.hxx"
103 #include "SMESH_PreMeshInfo.hxx"
104 #include "SMESH_PythonDump.hxx"
105 #include "SMESH_ControlsDef.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>
148 using SMESH::TPythonDump;
151 #define NUM_TMP_FILES 2
154 static int MYDEBUG = 0;
156 static int MYDEBUG = 0;
159 // Static variables definition
160 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen = GEOM::GEOM_Gen::_nil();
161 CORBA::ORB_var SMESH_Gen_i::myOrb;
162 PortableServer::POA_var SMESH_Gen_i::myPoa;
163 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
164 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
165 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
168 const int nbElemPerDiagonal = 10;
170 //=============================================================================
172 * GetServant [ static ]
174 * Get servant of the CORBA object
176 //=============================================================================
178 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
180 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
183 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
186 catch (PortableServer::POA::ObjectNotActive &ex)
188 INFOS("GetServant: ObjectNotActive");
191 catch (PortableServer::POA::WrongAdapter &ex)
193 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
196 catch (PortableServer::POA::WrongPolicy &ex)
198 INFOS("GetServant: WrongPolicy");
203 INFOS( "GetServant - Unknown exception was caught!!!" );
208 //=============================================================================
210 * SObjectToObject [ static ]
212 * Get CORBA object corresponding to the SALOMEDS::SObject
214 //=============================================================================
216 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
218 SALOMEDS::GenericAttribute_wrap anAttr;
219 CORBA::Object_var anObj;
220 if ( !theSObject->_is_nil() ) {
222 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
223 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
224 CORBA::String_var aValue = anIOR->Value();
225 if( strcmp( aValue, "" ) != 0 )
226 anObj = GetORB()->string_to_object( aValue );
230 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
236 //=============================================================================
240 * Get SALOME_NamingService object
242 //=============================================================================
244 SALOME_NamingService* SMESH_Gen_i::GetNS()
246 if ( myNS == NULL ) {
247 myNS = SINGLETON_<SALOME_NamingService>::Instance();
248 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
249 myNS->init_orb( GetORB() );
254 //=============================================================================
258 * Get SALOME_LifeCycleCORBA object
260 //=============================================================================
261 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC() {
262 if ( myLCC == NULL ) {
263 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
269 //=============================================================================
271 * GetGeomEngine [ static ]
273 * Get GEOM::GEOM_Gen reference
275 //=============================================================================
276 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine() {
277 //CCRT GEOM::GEOM_Gen_var aGeomEngine =
278 //CCRT GEOM::GEOM_Gen::_narrow( GetLCC()->FindOrLoad_Component("FactoryServer","GEOM") );
279 //CCRT return aGeomEngine._retn();
280 if(CORBA::is_nil(myGeomGen))
282 Engines::EngineComponent_ptr temp=GetLCC()->FindOrLoad_Component("FactoryServer","GEOM");
283 myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
288 //=============================================================================
290 * SMESH_Gen_i::SMESH_Gen_i
292 * Default constructor: not for use
294 //=============================================================================
296 SMESH_Gen_i::SMESH_Gen_i()
300 //=============================================================================
302 * SMESH_Gen_i::SMESH_Gen_i
304 * Standard constructor, used with Container
306 //=============================================================================
308 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
309 PortableServer::POA_ptr poa,
310 PortableServer::ObjectId* contId,
311 const char* instanceName,
312 const char* interfaceName )
313 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
316 myOrb = CORBA::ORB::_duplicate(orb);
317 myPoa = PortableServer::POA::_duplicate(poa);
320 _id = myPoa->activate_object( _thisObj );
322 myStudyContext = new StudyContext;
324 myIsEmbeddedMode = false;
325 myIsEnablePublish = true;
326 myShapeReader = NULL; // shape reader
328 myIsHistoricalPythonDump = true;
329 myToForgetMeshDataOnHypModif = false;
331 // set it in standalone mode only
332 //OSD::SetSignal( true );
334 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
335 // find out mode (embedded or standalone) here else
336 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
337 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
338 if ( SALOME_NamingService* ns = GetNS() )
340 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
341 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
342 if ( !session->_is_nil() )
344 CORBA::String_var str_host = session->getHostname();
345 CORBA::Long s_pid = session->getPID();
346 string my_host = Kernel_Utils::GetHostname();
348 long my_pid = (long)_getpid();
350 long my_pid = (long) getpid();
352 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
357 //=============================================================================
359 * SMESH_Gen_i::~SMESH_Gen_i
363 //=============================================================================
365 SMESH_Gen_i::~SMESH_Gen_i()
367 // delete hypothesis creators
368 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
369 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
371 // same creator can be mapped under different names
372 GenericHypothesisCreator_i* creator = (*itHyp).second;
376 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
377 if ( creator == (*itHyp2).second )
378 (*itHyp2).second = 0;
380 myHypCreatorMap.clear();
382 // Clear study contexts data
383 delete myStudyContext;
385 // delete shape reader
387 delete myShapeReader;
389 //=============================================================================
391 * SMESH_Gen_i::getHypothesisCreator
393 * Get hypothesis creator
395 //=============================================================================
396 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
397 const char* theLibName,
398 std::string& thePlatformLibName)
399 throw (SALOME::SALOME_Exception)
401 std::string aPlatformLibName;
402 /* It's Need to translate lib name for WIN32 or X platform */
403 if ( theLibName && theLibName[0] != '\0' )
405 int libNameLen = strlen(theLibName);
406 //check for old format "libXXXXXXX.so"
407 if (libNameLen > 7 &&
408 !strncmp( theLibName, "lib", 3 ) &&
409 !strcmp( theLibName+libNameLen-3, ".so" ))
413 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
414 #elif defined(__APPLE__)
415 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
417 aPlatformLibName = theLibName;
422 //try to use new format
424 aPlatformLibName = theLibName;
425 aPlatformLibName += ".dll";
426 #elif defined(__APPLE__)
427 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
429 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
433 thePlatformLibName = aPlatformLibName;
435 Unexpect aCatch(SALOME_SalomeException);
436 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
438 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
439 GenericHypothesisCreator_i* aCreator;
442 // check, if creator for this hypothesis type already exists
443 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
445 // load plugin library
446 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
449 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
451 const char* path = aPlatformLibName.c_str();
454 const char* path = aPlatformLibName.c_str();
456 LibHandle libHandle = LoadLib( path );
457 #if defined(WIN32) && defined(UNICODE)
462 // report any error, if occurred
464 const char* anError = dlerror();
465 throw(SALOME_Exception(anError));
467 throw(SALOME_Exception(LOCALIZED( "Can't load server meshers plugin library" )));
471 // get method, returning hypothesis creator
472 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
473 GetHypothesisCreator procHandle =
474 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
477 throw(SALOME_Exception(LOCALIZED("bad hypothesis plugin library")));
478 UnLoadLib(libHandle);
481 // get hypothesis creator
482 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
483 aCreator = procHandle(theHypName);
486 throw(SALOME_Exception(LOCALIZED("no such a hypothesis in this plugin")));
488 // map hypothesis creator to a hypothesis name
489 myHypCreatorMap[string(theHypName)] = aCreator;
494 return myHypCreatorMap[string(theHypName)];
497 catch (SALOME_Exception& S_ex)
499 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
504 //=============================================================================
506 * SMESH_Gen_i::createHypothesis
508 * Create hypothesis of given type
510 //=============================================================================
511 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
512 const char* theLibName)
514 SMESH_Hypothesis_i* myHypothesis_i = 0;
515 SMESH::SMESH_Hypothesis_var hypothesis_i;
516 std::string aPlatformLibName;
517 GenericHypothesisCreator_i* aCreator =
518 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
520 // create a new hypothesis object, store its ref. in studyContext
521 myHypothesis_i = aCreator->Create(myPoa, &myGen);
524 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
525 CORBA::String_var hypName = myHypothesis_i->GetName();
526 myHypCreatorMap[ hypName.in() ] = aCreator;
528 // activate the CORBA servant of hypothesis
529 hypothesis_i = myHypothesis_i->_this();
530 int nextId = RegisterObject( hypothesis_i );
531 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
532 else { nextId = 0; } // avoid "unused variable" warning in release mode
534 return hypothesis_i._retn();
537 //=============================================================================
539 * SMESH_Gen_i::createMesh
541 * Create empty mesh on shape
543 //=============================================================================
544 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
545 throw ( SALOME::SALOME_Exception )
547 Unexpect aCatch(SALOME_SalomeException);
548 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
550 // Get or create the GEOM_Client instance
552 // create a new mesh object servant, store it in a map in study context
553 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
554 // create a new mesh object
555 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
556 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
558 // activate the CORBA servant of Mesh
559 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
560 int nextId = RegisterObject( mesh );
561 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
562 else { nextId = 0; } // avoid "unused variable" warning in release mode
565 catch (SALOME_Exception& S_ex) {
566 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
568 return SMESH::SMESH_Mesh::_nil();
571 //=============================================================================
573 * SMESH_Gen_i::GetShapeReader
577 //=============================================================================
578 GEOM_Client* SMESH_Gen_i::GetShapeReader()
580 // create shape reader if necessary
581 if ( !myShapeReader )
582 myShapeReader = new GEOM_Client(GetContainerRef());
583 ASSERT( myShapeReader );
584 return myShapeReader;
587 //=============================================================================
589 * SMESH_Gen_i::SetGeomEngine
591 * Set GEOM::GEOM_Gen reference
593 //=============================================================================
594 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
595 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
597 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
598 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
599 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
603 //=============================================================================
605 * SMESH_Gen_i::SetEmbeddedMode
609 //=============================================================================
611 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
613 myIsEmbeddedMode = theMode;
615 if ( !myIsEmbeddedMode ) {
616 //PAL10867: disable signals catching with "noexcepthandler" option
617 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
618 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
623 char* envDisableFPE = getenv("DISABLE_FPE");
624 if (envDisableFPE && atoi(envDisableFPE))
629 OSD::SetSignal( raiseFPE );
631 // else OSD::SetSignal() is called in GUI
635 //=============================================================================
637 * SMESH_Gen_i::IsEmbeddedMode
641 //=============================================================================
643 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
645 return myIsEmbeddedMode;
648 //=============================================================================
650 * SMESH_Gen_i::SetEnablePublish
652 * Set enable publishing in the study
654 //=============================================================================
655 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
657 myIsEnablePublish = theIsEnablePublish;
660 //=============================================================================
662 * SMESH_Gen_i::IsEnablePublish
664 * Check enable publishing
666 //=============================================================================
668 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
670 return myIsEnablePublish;
673 //=============================================================================
675 * SMESH_Gen_i::UpdateStudy
677 * Update study (needed at switching GEOM->SMESH)
679 //=============================================================================
681 void SMESH_Gen_i::UpdateStudy()
683 if ( !myStudyContext )
684 myStudyContext = new StudyContext;
686 SALOMEDS::Study_var aStudy = getStudyServant();
687 if ( !CORBA::is_nil( aStudy ) ) {
688 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
689 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
690 if( !GEOM_var->_is_nil() )
691 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine() );
692 // NPAL16168, issue 0020210
693 // Let meshes update their data depending on GEOM groups that could change
694 CORBA::String_var compDataType = ComponentDataType();
695 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
696 if ( !me->_is_nil() ) {
697 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
698 for ( ; anIter->More(); anIter->Next() ) {
699 SALOMEDS::SObject_wrap so = anIter->Value();
700 CORBA::Object_var ior = SObjectToObject( so );
701 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
702 mesh->CheckGeomModif();
708 //=============================================================================
710 * SMESH_Gen_i::GetStudyContext
714 //=============================================================================
715 StudyContext* SMESH_Gen_i::GetStudyContext()
717 return myStudyContext;
720 //=============================================================================
722 * SMESH_Gen_i::CreateHypothesis
724 * Create hypothesis/algorothm of given type and publish it in the study
726 //=============================================================================
728 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
729 const char* theLibName )
730 throw ( SALOME::SALOME_Exception )
732 Unexpect aCatch(SALOME_SalomeException);
733 // Create hypothesis/algorithm
734 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
736 // Publish hypothesis/algorithm in the study
737 if ( CanPublishInStudy( hyp ) ) {
738 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
739 if ( !aSO->_is_nil() ) {
740 // Update Python script
741 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
742 << theHypName << "', '" << theLibName << "')";
749 //================================================================================
751 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
752 * existing on the given geometry or to size of the geometry.
753 * \param theHypType - hypothesis type name
754 * \param theLibName - plugin library name
755 * \param theMesh - The mesh of interest
756 * \param theGeom - The shape to get parameter values from
757 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
758 * in a study and used to compute the mesh, or a temporary one created just to pass
761 //================================================================================
763 SMESH::SMESH_Hypothesis_ptr
764 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
765 const char* theLibName,
766 SMESH::SMESH_Mesh_ptr theMesh,
767 GEOM::GEOM_Object_ptr theGeom,
768 CORBA::Boolean byMesh)
769 throw ( SALOME::SALOME_Exception )
771 Unexpect aCatch(SALOME_SalomeException);
772 if ( byMesh && CORBA::is_nil( theMesh ) )
773 return SMESH::SMESH_Hypothesis::_nil();
774 if ( byMesh && CORBA::is_nil( theGeom ) )
775 return SMESH::SMESH_Hypothesis::_nil();
777 // -----------------------------------------------
778 // find hypothesis used to mesh theGeom
779 // -----------------------------------------------
781 // get mesh and shape
782 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
783 TopoDS_Shape shape = GeomObjectToShape( theGeom );
784 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
785 return SMESH::SMESH_Hypothesis::_nil();
786 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
788 // create a temporary hypothesis to know its dimension
789 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
790 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
792 return SMESH::SMESH_Hypothesis::_nil();
793 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
796 // look for a hypothesis of theHypType used to mesh the shape
797 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
800 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
801 int nbLocalHyps = aHypList->length();
802 for ( int i = 0; i < nbLocalHyps; i++ ) {
803 CORBA::String_var hypName = aHypList[i]->GetName();
804 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
805 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
807 // check super shapes
808 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
809 while ( nbLocalHyps == 0 && itShape.More() ) {
810 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
811 if ( ! CORBA::is_nil( geomObj )) {
812 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
813 nbLocalHyps = aHypList->length();
814 for ( int i = 0; i < nbLocalHyps; i++ )
815 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
816 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
822 // let the temporary hypothesis find out somehow parameter values by mesh
823 if ( hyp->SetParametersByMesh( mesh, shape ))
824 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
829 diagonal = mesh->GetShapeDiagonalSize();
831 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
832 ::SMESH_Hypothesis::TDefaults dflts;
833 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
834 dflts._nbSegments = myGen.GetDefaultNbSegments();
835 dflts._shape = &shape;
836 // let the temporary hypothesis initialize it's values
837 if ( hyp->SetParametersByDefaults( dflts, mesh ))
838 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
841 return SMESH::SMESH_Hypothesis::_nil();
844 //=============================================================================
846 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
847 * \param [in] theHyp - the hypothesis of interest
848 * \param [out] theMesh - the sole mesh using \a theHyp
849 * \param [out] theShape - the sole geometry \a theHyp is assigned to
850 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
852 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
853 * considered as SAME sub-mesh => result is \c true.
854 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
855 * a shape to which an hyp being edited is assigned.
857 //=============================================================================
859 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
860 SMESH::SMESH_Mesh_out theMesh,
861 GEOM::GEOM_Object_out theShape)
863 if ( CORBA::is_nil( theHyp ))
866 // get Mesh component SO
867 CORBA::String_var compDataType = ComponentDataType();
868 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
869 if ( CORBA::is_nil( comp ))
872 // look for child SO of meshes
873 SMESH::SMESH_Mesh_var foundMesh;
874 TopoDS_Shape foundShape;
876 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
877 for ( ; meshIter->More() && isSole; meshIter->Next() )
879 SALOMEDS::SObject_wrap curSO = meshIter->Value();
880 CORBA::Object_var obj = SObjectToObject( curSO );
881 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
885 // look for a sole shape where theHyp is assigned
886 bool isHypFound = false;
887 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
888 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
889 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
891 const THypList& hyps = s2hypsIt.Value();
892 THypList::const_iterator h = hyps.begin();
893 for ( ; h != hyps.end(); ++h )
894 if ( (*h)->GetID() == theHyp->GetId() )
896 if ( h != hyps.end()) // theHyp found
899 if ( ! foundShape.IsNull() &&
900 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
902 foundShape.Nullify();
906 foundShape = s2hypsIt.Key();
908 } // loop on assigned hyps
910 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
912 if ( !foundMesh->_is_nil() ) // not a sole mesh
914 if ( !foundMesh->HasShapeToMesh() ||
915 !mesh_i ->HasShapeToMesh() )
917 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
921 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
922 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
923 isSole = s1->IsSame( s2 );
926 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
932 ! foundMesh->_is_nil() &&
933 ! foundShape.IsNull() )
935 theMesh = foundMesh._retn();
936 theShape = ShapeToGeomObject( foundShape );
937 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
942 //=============================================================================
944 * Sets number of segments per diagonal of boundary box of geometry by which
945 * default segment length of appropriate 1D hypotheses is defined
947 //=============================================================================
949 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
950 throw ( SALOME::SALOME_Exception )
952 if ( theNbSegments > 0 )
953 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
955 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
957 //=============================================================================
959 * \brief Sets default number of segments per edge
961 //=============================================================================
962 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
963 throw ( SALOME::SALOME_Exception )
965 if ( theNbSegments > 0 )
966 myGen.SetDefaultNbSegments( int(theNbSegments) );
968 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
971 //=============================================================================
975 //=============================================================================
977 void SMESH_Gen_i::SetOption(const char* name, const char* value)
979 if ( name && value && strlen( value ) > 0 )
982 if ( strcmp(name, "historical_python_dump") == 0 )
984 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
985 msgToGUI = "preferences/SMESH/historical_python_dump/";
986 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
988 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
990 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
991 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
992 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
994 else if ( strcmp(name, "default_grp_color") == 0 )
998 // color must be presented as a string of following form:
999 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1000 str = str.substr(1);
1001 for ( size_t i = 0; i < str.length()/2; i++ )
1002 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1003 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1005 else if ( value ) { // rgb color ("255,170,0", for example)
1006 string tempValue( value );
1007 char* colorValue = strtok( &tempValue[0], "," );
1008 while ( colorValue != NULL ) {
1009 int c_value = atoi( colorValue );
1010 if ( c_value >= 0 && c_value <= 255 )
1011 color.push_back( c_value );
1012 colorValue = strtok( NULL, "," );
1015 if ( color.size() == 3 ) { // color must have three valid component
1016 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1017 myDefaultGroupColor = value;
1018 msgToGUI = "preferences/SMESH/default_grp_color/";
1023 // update preferences in case if SetOption() is invoked from python console
1024 if ( !msgToGUI.empty() )
1026 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1027 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1028 if ( !CORBA::is_nil( session ) )
1029 session->emitMessageOneWay(msgToGUI.c_str());
1034 //=============================================================================
1036 Return an option value
1038 //=============================================================================
1040 char* SMESH_Gen_i::GetOption(const char* name)
1044 if ( strcmp(name, "historical_python_dump") == 0 )
1046 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1048 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1050 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1052 if ( strcmp(name, "default_grp_color") == 0 )
1054 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1057 return CORBA::string_dup( "" );
1060 //=============================================================================
1062 * SMESH_Gen_i::CreateMesh
1064 * Create empty mesh on a shape and publish it in the study
1066 //=============================================================================
1068 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1069 throw ( SALOME::SALOME_Exception )
1071 Unexpect aCatch(SALOME_SalomeException);
1072 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1074 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1076 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1077 ASSERT( meshServant );
1078 meshServant->SetShape( theShapeObject );
1080 // publish mesh in the study
1081 if ( CanPublishInStudy( mesh ) ) {
1082 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1083 aStudyBuilder->NewCommand(); // There is a transaction
1084 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1085 aStudyBuilder->CommitCommand();
1086 if ( !aSO->_is_nil() ) {
1087 // Update Python script
1088 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1092 return mesh._retn();
1095 //=============================================================================
1097 * SMESH_Gen_i::CreateEmptyMesh
1101 //=============================================================================
1103 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1104 throw ( SALOME::SALOME_Exception )
1106 Unexpect aCatch(SALOME_SalomeException);
1107 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1109 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1111 // publish mesh in the study
1112 if ( CanPublishInStudy( mesh ) ) {
1113 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1114 aStudyBuilder->NewCommand(); // There is a transaction
1115 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1116 aStudyBuilder->CommitCommand();
1117 if ( !aSO->_is_nil() ) {
1118 // Update Python script
1119 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1123 return mesh._retn();
1128 //================================================================================
1130 * \brief Throws an exception in case if the file can't be read
1132 //================================================================================
1134 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1136 SMESH_File f ( theFileName );
1139 if ( !f.error().empty() )
1140 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1142 THROW_SALOME_CORBA_EXCEPTION
1143 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1144 SALOME::BAD_PARAM );
1149 //=============================================================================
1151 * SMESH_Gen_i::CreateMeshFromUNV
1153 * Create mesh and import data from UNV file
1155 //=============================================================================
1157 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1158 throw ( SALOME::SALOME_Exception )
1160 Unexpect aCatch(SALOME_SalomeException);
1162 checkFileReadable( theFileName );
1164 SMESH::SMESH_Mesh_var aMesh = createMesh();
1166 // publish mesh in the study
1167 if ( CanPublishInStudy( aMesh ) ) {
1168 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1169 aStudyBuilder->NewCommand(); // There is a transaction
1170 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1171 aStudyBuilder->CommitCommand();
1172 if ( !aSO->_is_nil() ) {
1173 // Update Python script
1174 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1178 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1180 aServant->ImportUNVFile( theFileName );
1182 // Dump creation of groups
1183 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1185 aServant->GetImpl().GetMeshDS()->Modified();
1186 return aMesh._retn();
1189 //=============================================================================
1191 * SMESH_Gen_i::CreateMeshFromMED
1193 * Create mesh and import data from MED file
1195 //=============================================================================
1197 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1198 SMESH::DriverMED_ReadStatus& theStatus,
1199 const char* theCommandNameForPython,
1200 const char* theFileNameForPython)
1203 char bname[ _MAX_FNAME ];
1204 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1205 string aFileName = bname;
1207 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1209 // Retrieve mesh names from the file
1210 DriverMED_R_SMESHDS_Mesh myReader;
1211 myReader.SetFile( theFileName );
1212 myReader.SetMeshId( -1 );
1213 Driver_Mesh::Status aStatus;
1214 list<string> aNames = myReader.GetMeshNames(aStatus);
1215 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1216 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1218 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1221 TPythonDump aPythonDump;
1222 aPythonDump << "([";
1224 if (theStatus == SMESH::DRS_OK) {
1225 SALOMEDS::StudyBuilder_var aStudyBuilder;
1226 aStudyBuilder = getStudyServant()->NewBuilder();
1227 aStudyBuilder->NewCommand(); // There is a transaction
1229 aResult->length( aNames.size() );
1232 // Iterate through all meshes and create mesh objects
1233 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1236 if (i > 0) aPythonDump << ", ";
1239 SMESH::SMESH_Mesh_var mesh = createMesh();
1241 // publish mesh in the study
1242 SALOMEDS::SObject_wrap aSO;
1243 if ( CanPublishInStudy( mesh ) )
1244 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1245 // - as names of meshes are stored in MED file, we use them for data publishing
1246 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1247 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1250 if ( !aSO->_is_nil() ) {
1253 aPythonDump << "mesh_" << i;
1256 // Read mesh data (groups are published automatically by ImportMEDFile())
1257 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1258 ASSERT( meshServant );
1259 SMESH::DriverMED_ReadStatus status1 =
1260 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1261 if (status1 > theStatus)
1262 theStatus = status1;
1264 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1265 meshServant->GetImpl().GetMeshDS()->Modified();
1267 if ( !aStudyBuilder->_is_nil() )
1268 aStudyBuilder->CommitCommand();
1271 // Update Python script
1272 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1274 // Dump creation of groups
1275 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1276 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1278 return aResult._retn();
1281 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1282 SMESH::DriverMED_ReadStatus& theStatus)
1283 throw ( SALOME::SALOME_Exception )
1285 Unexpect aCatch(SALOME_SalomeException);
1286 checkFileReadable( theFileName );
1288 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1292 //=============================================================================
1294 * SMESH_Gen_i::CreateMeshFromSAUV
1296 * Create mesh and import data from SAUV file
1298 //=============================================================================
1300 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1301 SMESH::DriverMED_ReadStatus& theStatus)
1302 throw ( SALOME::SALOME_Exception )
1304 Unexpect aCatch(SALOME_SalomeException);
1305 checkFileReadable( theFileName );
1307 std::string sauvfilename(theFileName);
1308 std::string medfilename(theFileName);
1309 medfilename += ".med";
1312 cmd = "%PYTHONBIN% ";
1317 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1319 system(cmd.c_str());
1320 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1322 cmd = "%PYTHONBIN% ";
1327 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1329 system(cmd.c_str());
1333 //=============================================================================
1335 * SMESH_Gen_i::CreateMeshFromSTL
1337 * Create mesh and import data from STL file
1339 //=============================================================================
1341 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1342 throw ( SALOME::SALOME_Exception )
1344 Unexpect aCatch(SALOME_SalomeException);
1345 checkFileReadable( theFileName );
1347 SMESH::SMESH_Mesh_var aMesh = createMesh();
1350 char bname[ _MAX_FNAME ];
1351 _splitpath( theFileName, NULL, NULL, bname, NULL );
1352 string aFileName = bname;
1354 string aFileName = basename( const_cast<char *>(theFileName) );
1356 // publish mesh in the study
1357 if ( CanPublishInStudy( aMesh ) ) {
1358 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1359 aStudyBuilder->NewCommand(); // There is a transaction
1360 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1361 aStudyBuilder->CommitCommand();
1362 if ( !aSO->_is_nil() ) {
1363 // Update Python script
1364 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1368 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1370 aServant->ImportSTLFile( theFileName );
1371 aServant->GetImpl().GetMeshDS()->Modified();
1372 return aMesh._retn();
1375 //================================================================================
1377 * \brief Create meshes and import data from the CGSN file
1379 //================================================================================
1381 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1382 SMESH::DriverMED_ReadStatus& theStatus)
1383 throw ( SALOME::SALOME_Exception )
1385 Unexpect aCatch(SALOME_SalomeException);
1386 checkFileReadable( theFileName );
1388 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1391 // Retrieve nb meshes from the file
1392 DriverCGNS_Read myReader;
1393 myReader.SetFile( theFileName );
1394 Driver_Mesh::Status aStatus;
1395 int nbMeshes = myReader.GetNbMeshes(aStatus);
1396 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1398 aResult->length( nbMeshes );
1400 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1403 TPythonDump aPythonDump;
1404 aPythonDump << "([";
1406 if (theStatus == SMESH::DRS_OK)
1408 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1409 aStudyBuilder->NewCommand(); // There is a transaction
1413 // Iterate through all meshes and create mesh objects
1414 for ( ; i < nbMeshes; ++i )
1417 if (i > 0) aPythonDump << ", ";
1420 SMESH::SMESH_Mesh_var mesh = createMesh();
1421 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1423 // Read mesh data (groups are published automatically by ImportMEDFile())
1424 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1425 ASSERT( meshServant );
1427 SMESH::DriverMED_ReadStatus status1 =
1428 meshServant->ImportCGNSFile( theFileName, i, meshName );
1429 if (status1 > theStatus)
1430 theStatus = status1;
1432 meshServant->GetImpl().GetMeshDS()->Modified();
1433 // publish mesh in the study
1434 SALOMEDS::SObject_wrap aSO;
1435 if ( CanPublishInStudy( mesh ) )
1436 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1439 if ( !aSO->_is_nil() ) {
1443 aPythonDump << "mesh_" << i;
1446 aStudyBuilder->CommitCommand();
1449 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1451 // Dump creation of groups
1452 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1453 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1455 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1458 return aResult._retn();
1461 //================================================================================
1463 * \brief Create a mesh and import data from a GMF file
1465 //================================================================================
1467 SMESH::SMESH_Mesh_ptr
1468 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1469 CORBA::Boolean theMakeRequiredGroups,
1470 SMESH::ComputeError_out theError)
1471 throw ( SALOME::SALOME_Exception )
1473 Unexpect aCatch(SALOME_SalomeException);
1474 checkFileReadable( theFileName );
1476 SMESH::SMESH_Mesh_var aMesh = createMesh();
1478 char bname[ _MAX_FNAME ];
1479 _splitpath( theFileName, NULL, NULL, bname, NULL );
1480 string aFileName = bname;
1482 string aFileName = basename( const_cast<char *>(theFileName) );
1484 // publish mesh in the study
1485 if ( CanPublishInStudy( aMesh ) ) {
1486 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1487 aStudyBuilder->NewCommand(); // There is a transaction
1488 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1489 aStudyBuilder->CommitCommand();
1490 if ( !aSO->_is_nil() ) {
1491 // Update Python script
1492 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1493 << theFileName << "', "
1494 << theMakeRequiredGroups << " )";
1497 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1499 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1500 aServant->GetImpl().GetMeshDS()->Modified();
1501 return aMesh._retn();
1505 //=============================================================================
1507 * SMESH_Gen_i::IsReadyToCompute
1509 * Returns true if mesh contains enough data to be computed
1511 //=============================================================================
1513 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1514 GEOM::GEOM_Object_ptr theShapeObject )
1515 throw ( SALOME::SALOME_Exception )
1517 Unexpect aCatch(SALOME_SalomeException);
1518 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1520 if ( CORBA::is_nil( theShapeObject ) )
1521 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1522 SALOME::BAD_PARAM );
1524 if ( CORBA::is_nil( theMesh ) )
1525 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1526 SALOME::BAD_PARAM );
1530 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1531 ASSERT( meshServant );
1532 if ( meshServant ) {
1533 // get local TopoDS_Shape
1534 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1535 // call implementation
1536 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1537 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1540 catch ( SALOME_Exception& S_ex ) {
1541 INFOS( "catch exception "<< S_ex.what() );
1546 //================================================================================
1548 * \brief Find SObject for an algo
1550 //================================================================================
1552 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1555 SALOMEDS::Study_var aStudy = getStudyServant();
1556 if ( !aStudy->_is_nil() ) {
1557 // find algo in the study
1558 CORBA::String_var compDataType = ComponentDataType();
1559 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1560 if ( !father->_is_nil() ) {
1561 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1562 for ( ; itBig->More(); itBig->Next() ) {
1563 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1564 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1565 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1566 for ( ; algoIt->More(); algoIt->Next() ) {
1567 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1568 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1569 if ( !CORBA::is_nil( algoIOR )) {
1570 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1571 if ( impl && impl->GetImpl() == algo )
1572 return algoSO._retn();
1574 } // loop on algo SO's
1577 } // SMESH component iterator
1581 return SALOMEDS::SObject::_nil();
1584 //================================================================================
1586 * \brief Return errors of mesh computation
1588 //================================================================================
1590 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1591 GEOM::GEOM_Object_ptr theSubObject )
1592 throw ( SALOME::SALOME_Exception )
1594 Unexpect aCatch(SALOME_SalomeException);
1595 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1597 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1598 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1600 if ( CORBA::is_nil( theMesh ) )
1601 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1603 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1605 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1608 if(theMesh->HasShapeToMesh())
1609 shape = GeomObjectToShape( theSubObject );
1611 shape = SMESH_Mesh::PseudoShape();
1613 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1615 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1618 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1619 const bool includeSelf = true, complexShapeFirst = true;
1620 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1622 while ( smIt->more() )
1625 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1627 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1628 if ( error && !error->IsOK() )
1630 if ( !( error->myAlgo ) &&
1631 !( error->myAlgo = sm->GetAlgo() ))
1633 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1634 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1635 errStruct.comment = error->myComment.c_str();
1636 errStruct.subShapeID = sm->GetId();
1637 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1638 if ( !algoSO->_is_nil() ) {
1639 CORBA::String_var algoName = algoSO->GetName();
1640 errStruct.algoName = algoName;
1643 errStruct.algoName = error->myAlgo->GetName();
1645 errStruct.hasBadMesh = error->HasBadElems();
1648 error_array->length( nbErr );
1651 catch ( SALOME_Exception& S_ex ) {
1652 INFOS( "catch exception "<< S_ex.what() );
1655 return error_array._retn();
1658 //================================================================================
1660 * \brief Return mesh elements preventing computation of a subshape
1662 //================================================================================
1664 SMESH::MeshPreviewStruct*
1665 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1666 CORBA::Short theSubShapeID )
1667 throw ( SALOME::SALOME_Exception )
1669 Unexpect aCatch(SALOME_SalomeException);
1670 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1672 if ( CORBA::is_nil( theMesh ) )
1673 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1675 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1678 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1680 // mesh implementation
1681 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1682 // submesh by subshape id
1683 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1686 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1687 if ( error && error->HasBadElems() )
1689 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1690 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1692 // get nodes of elements and count elements
1693 TNode2LocalIDMap mapNode2LocalID;
1694 list< TNodeLocalID > connectivity;
1695 int i, nbElements = 0, nbConnNodes = 0;
1697 const list<const SMDS_MeshElement*>& badElems =
1698 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1699 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1700 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1701 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1703 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1704 while ( nIt->more() )
1705 connectivity.push_back
1706 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1708 // fill node coords and assign local ids to the nodes
1709 int nbNodes = mapNode2LocalID.size();
1710 result->nodesXYZ.length( nbNodes );
1711 TNodeLocalID node2ID = mapNode2LocalID.begin();
1712 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1713 node2ID->second = i;
1714 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1715 result->nodesXYZ[i].x = node->X();
1716 result->nodesXYZ[i].y = node->Y();
1717 result->nodesXYZ[i].z = node->Z();
1719 // fill connectivity
1720 result->elementConnectivities.length( nbConnNodes );
1721 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1722 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1723 result->elementConnectivities[i] = (*connIt)->second;
1725 // fill element types
1726 result->elementTypes.length( nbElements );
1727 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1729 const SMDS_MeshElement* elem = *elemIt;
1730 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1731 result->elementTypes[i].isPoly = elem->IsPoly();
1732 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1738 catch ( SALOME_Exception& S_ex ) {
1739 INFOS( "catch exception "<< S_ex.what() );
1742 return result._retn();
1745 //================================================================================
1747 * \brief Create a group of elements preventing computation of a sub-shape
1749 //================================================================================
1751 SMESH::ListOfGroups*
1752 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1753 CORBA::Short theSubShapeID,
1754 const char* theGroupName )
1755 throw ( SALOME::SALOME_Exception )
1757 Unexpect aCatch(SALOME_SalomeException);
1759 SMESH::ListOfGroups_var groups;
1761 if ( CORBA::is_nil( theMesh ) )
1762 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1765 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1767 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1768 TPythonDump() << groups << " = " << this
1769 << ".MakeGroupsOfBadInputElements( "
1770 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1773 catch ( SALOME_Exception& S_ex ) {
1774 INFOS( "catch exception "<< S_ex.what() );
1776 return groups._retn();
1779 //================================================================================
1781 * \brief Returns errors of hypotheses definition
1782 * \param theMesh - the mesh
1783 * \param theSubObject - the main or sub- shape
1784 * \retval SMESH::algo_error_array* - sequence of errors
1786 //================================================================================
1788 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1789 GEOM::GEOM_Object_ptr theSubObject )
1790 throw ( SALOME::SALOME_Exception )
1792 Unexpect aCatch(SALOME_SalomeException);
1793 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1795 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1796 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1798 if ( CORBA::is_nil( theMesh ) )
1799 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1801 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1803 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1804 ASSERT( meshServant );
1805 if ( meshServant ) {
1806 TopoDS_Shape myLocShape;
1807 if(theMesh->HasShapeToMesh())
1808 myLocShape = GeomObjectToShape( theSubObject );
1810 myLocShape = SMESH_Mesh::PseudoShape();
1812 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1813 list< ::SMESH_Gen::TAlgoStateError > error_list;
1814 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1815 // call ::SMESH_Gen::GetAlgoState()
1816 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1817 error_array->length( error_list.size() );
1819 for ( error = error_list.begin(); error != error_list.end(); ++error )
1821 // fill AlgoStateError structure
1822 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1823 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1824 errStruct.algoDim = error->_algoDim;
1825 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1826 errStruct.algoName = "";
1827 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1828 if ( !algoSO->_is_nil() ) {
1829 CORBA::String_var algoName = algoSO->GetName();
1830 errStruct.algoName = algoName.in();
1835 catch ( SALOME_Exception& S_ex ) {
1836 INFOS( "catch exception "<< S_ex.what() );
1838 return error_array._retn();
1841 //=============================================================================
1843 * SMESH_Gen_i::GetSubShapesId
1845 * Get sub-shapes unique ID's list
1847 //=============================================================================
1850 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1851 const SMESH::object_array& theListOfSubShapeObject )
1852 throw ( SALOME::SALOME_Exception )
1854 Unexpect aCatch(SALOME_SalomeException);
1855 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1857 SMESH::long_array_var shapesId = new SMESH::long_array;
1860 if ( CORBA::is_nil( theMainShapeObject ) )
1861 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1865 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1866 TopTools_IndexedMapOfShape myIndexToShape;
1867 TopExp::MapShapes(myMainShape,myIndexToShape);
1869 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1871 GEOM::GEOM_Object_var aShapeObject
1872 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1873 if ( CORBA::is_nil( aShapeObject ) )
1874 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1875 SALOME::BAD_PARAM );
1877 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1878 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1880 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1881 setId.insert(myIndexToShape.FindIndex(F));
1882 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1884 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1886 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1887 setId.insert(myIndexToShape.FindIndex(E));
1888 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1890 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1892 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1893 setId.insert(myIndexToShape.FindIndex(V));
1894 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1897 shapesId->length(setId.size());
1898 set<int>::iterator iind;
1900 for (iind = setId.begin(); iind != setId.end(); iind++)
1902 if(MYDEBUG) SCRUTE((*iind));
1903 shapesId[i] = (*iind);
1904 if(MYDEBUG) SCRUTE(shapesId[i]);
1908 catch (SALOME_Exception& S_ex)
1910 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1913 return shapesId._retn();
1916 //=============================================================================
1918 * SMESH_Gen_i::Compute
1920 * Compute mesh on a shape
1922 //=============================================================================
1924 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1925 GEOM::GEOM_Object_ptr theShapeObject )
1926 throw ( SALOME::SALOME_Exception )
1929 Unexpect aCatch(SALOME_SalomeException);
1930 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
1932 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
1933 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1934 SALOME::BAD_PARAM );
1936 if ( CORBA::is_nil( theMesh ) )
1937 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1938 SALOME::BAD_PARAM );
1940 // Update Python script
1941 TPythonDump() << "isDone = " << this << ".Compute( "
1942 << theMesh << ", " << theShapeObject << ")";
1946 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1947 ASSERT( meshServant );
1948 if ( meshServant ) {
1949 meshServant->Load();
1950 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
1951 meshServant->CheckGeomModif();
1952 // get local TopoDS_Shape
1953 TopoDS_Shape myLocShape;
1954 if(theMesh->HasShapeToMesh())
1955 myLocShape = GeomObjectToShape( theShapeObject );
1957 myLocShape = SMESH_Mesh::PseudoShape();
1958 // call implementation compute
1959 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1960 myGen.PrepareCompute( myLocMesh, myLocShape );
1961 int how = ::SMESH_Gen::COMPACT_MESH;
1962 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
1963 how |= ::SMESH_Gen::SHAPE_ONLY;
1964 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
1965 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
1966 myLocMesh.GetMeshDS()->Modified();
1967 UpdateIcons( theMesh );
1969 HighLightInvalid( theMesh, /*isInvalid=*/false );
1973 catch ( std::bad_alloc ) {
1974 INFOS( "Compute(): lack of memory" );
1976 catch ( SALOME_Exception& S_ex ) {
1977 INFOS( "Compute(): catch exception "<< S_ex.what() );
1980 INFOS( "Compute(): unknown exception " );
1985 //=============================================================================
1987 * SMESH_Gen_i::CancelCompute
1989 * Cancel Compute mesh on a shape
1991 //=============================================================================
1993 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
1994 GEOM::GEOM_Object_ptr theShapeObject )
1996 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1997 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1998 TopoDS_Shape myLocShape;
1999 if(theMesh->HasShapeToMesh())
2000 myLocShape = GeomObjectToShape( theShapeObject );
2002 myLocShape = SMESH_Mesh::PseudoShape();
2003 myGen.CancelCompute( myLocMesh, myLocShape);
2006 //=============================================================================
2008 * SMESH_Gen_i::Precompute
2010 * Compute mesh as preview till indicated dimension on shape
2012 //=============================================================================
2014 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2015 GEOM::GEOM_Object_ptr theShapeObject,
2016 SMESH::Dimension theDimension,
2017 SMESH::long_array& theShapesId)
2018 throw ( SALOME::SALOME_Exception )
2020 Unexpect aCatch(SALOME_SalomeException);
2021 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2023 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2024 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2025 SALOME::BAD_PARAM );
2027 if ( CORBA::is_nil( theMesh ) )
2028 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2029 SALOME::BAD_PARAM );
2031 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2034 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2035 meshServant->Load();
2036 ASSERT( meshServant );
2037 if ( meshServant ) {
2038 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2039 meshServant->CheckGeomModif();
2040 // get local TopoDS_Shape
2041 TopoDS_Shape myLocShape;
2042 if(theMesh->HasShapeToMesh())
2043 myLocShape = GeomObjectToShape( theShapeObject );
2045 return result._retn();;
2047 // call implementation compute
2048 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2050 ::MeshDimension aDim = (MeshDimension)theDimension;
2051 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2053 int nbShapeId = shapeIds.size();
2054 theShapesId.length( nbShapeId );
2055 // iterates on shapes and collect mesh entities into mesh preview
2056 TSetOfInt::const_iterator idIt = shapeIds.begin();
2057 TSetOfInt::const_iterator idEnd = shapeIds.end();
2058 std::map< int, int > mapOfShIdNb;
2059 std::set< SMESH_TLink > setOfEdge;
2060 std::list< SMDSAbs_ElementType > listOfElemType;
2061 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2062 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2063 TNode2LocalIDMap mapNode2LocalID;
2064 list< TNodeLocalID > connectivity;
2065 int i, nbConnNodes = 0;
2066 std::set< const SMESH_subMesh* > setOfVSubMesh;
2067 // iterates on shapes
2068 for ( ; idIt != idEnd; idIt++ )
2070 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2072 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2073 if ( !sm || !sm->IsMeshComputed() )
2076 const TopoDS_Shape& aSh = sm->GetSubShape();
2077 const int shDim = myGen.GetShapeDim( aSh );
2078 if ( shDim < 1 || shDim > theDimension )
2081 mapOfShIdNb[ *idIt ] = 0;
2082 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2084 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2085 if ( !smDS ) continue;
2087 if ( theDimension == SMESH::DIM_2D )
2089 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2090 while ( faceIt->more() )
2092 const SMDS_MeshElement* face = faceIt->next();
2093 int aNbNode = face->NbNodes();
2095 aNbNode /= 2; // do not take into account additional middle nodes
2097 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2098 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2100 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2101 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2103 listOfElemType.push_back( SMDSAbs_Edge );
2104 connectivity.push_back
2105 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2106 connectivity.push_back
2107 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2113 else if ( theDimension == SMESH::DIM_1D )
2115 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2116 while ( nodeIt->more() )
2118 listOfElemType.push_back( SMDSAbs_Node );
2119 connectivity.push_back
2120 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2122 // add corner nodes by first vertex from edge
2123 SMESH_subMeshIteratorPtr edgeSmIt =
2124 sm->getDependsOnIterator(/*includeSelf*/false,
2125 /*complexShapeFirst*/false);
2126 while ( edgeSmIt->more() )
2128 SMESH_subMesh* vertexSM = edgeSmIt->next();
2129 // check that vertex is not already treated
2130 if ( !setOfVSubMesh.insert( vertexSM ).second )
2132 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2135 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2136 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2137 while ( nodeIt->more() )
2139 listOfElemType.push_back( SMDSAbs_Node );
2140 connectivity.push_back
2141 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2147 // fill node coords and assign local ids to the nodes
2148 int nbNodes = mapNode2LocalID.size();
2149 result->nodesXYZ.length( nbNodes );
2150 TNodeLocalID node2ID = mapNode2LocalID.begin();
2151 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2152 node2ID->second = i;
2153 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2154 result->nodesXYZ[i].x = node->X();
2155 result->nodesXYZ[i].y = node->Y();
2156 result->nodesXYZ[i].z = node->Z();
2158 // fill connectivity
2159 result->elementConnectivities.length( nbConnNodes );
2160 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2161 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2162 result->elementConnectivities[i] = (*connIt)->second;
2165 // fill element types
2166 result->elementTypes.length( listOfElemType.size() );
2167 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2168 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2169 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2171 SMDSAbs_ElementType elemType = *typeIt;
2172 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2173 result->elementTypes[i].isPoly = false;
2174 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2177 // correct number of shapes
2178 theShapesId.length( mapOfShIdNb.size() );
2182 catch ( std::bad_alloc ) {
2183 INFOS( "Precompute(): lack of memory" );
2185 catch ( SALOME_Exception& S_ex ) {
2186 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2189 INFOS( "Precompute(): unknown exception " );
2191 return result._retn();
2195 //=============================================================================
2197 * SMESH_Gen_i::Evaluate
2199 * Evaluate mesh on a shape
2201 //=============================================================================
2203 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2204 GEOM::GEOM_Object_ptr theShapeObject)
2205 // SMESH::long_array& theNbElems)
2206 throw ( SALOME::SALOME_Exception )
2208 Unexpect aCatch(SALOME_SalomeException);
2209 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2211 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2212 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2213 SALOME::BAD_PARAM );
2215 if ( CORBA::is_nil( theMesh ) )
2216 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2217 SALOME::BAD_PARAM );
2219 SMESH::long_array_var nbels = new SMESH::long_array;
2220 nbels->length(SMESH::Entity_Last);
2221 int i = SMESH::Entity_Node;
2222 for (; i < SMESH::Entity_Last; i++)
2225 // Update Python script
2226 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2227 << theMesh << ", " << theShapeObject << ")";
2231 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2232 ASSERT( meshServant );
2233 if ( meshServant ) {
2234 meshServant->Load();
2235 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2236 meshServant->CheckGeomModif();
2237 // get local TopoDS_Shape
2238 TopoDS_Shape myLocShape;
2239 if(theMesh->HasShapeToMesh())
2240 myLocShape = GeomObjectToShape( theShapeObject );
2242 myLocShape = SMESH_Mesh::PseudoShape();
2243 // call implementation compute
2244 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2245 MapShapeNbElems aResMap;
2246 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2247 MapShapeNbElemsItr anIt = aResMap.begin();
2248 for(; anIt!=aResMap.end(); anIt++) {
2249 const vector<int>& aVec = (*anIt).second;
2250 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2251 int nbElem = aVec[i];
2252 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2254 SMESH_subMesh* sm = anIt->first;
2255 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2256 const SMESH_Algo* algo = sm->GetAlgo();
2257 if ( (algo && !error.get()) || error->IsOK() )
2258 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2262 nbels[i] += aVec[i];
2266 return nbels._retn();
2269 catch ( std::bad_alloc ) {
2270 INFOS( "Evaluate(): lack of memory" );
2272 catch ( SALOME_Exception& S_ex ) {
2273 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2276 INFOS( "Evaluate(): unknown exception " );
2279 return nbels._retn();
2282 //================================================================================
2284 * \brief Return geometrical object the given element is built on
2285 * \param theMesh - the mesh the element is in
2286 * \param theElementID - the element ID
2287 * \param theGeomName - the name of the result geom object if it is not yet published
2288 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2290 //================================================================================
2292 GEOM::GEOM_Object_ptr
2293 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2294 CORBA::Long theElementID,
2295 const char* theGeomName)
2296 throw ( SALOME::SALOME_Exception )
2298 Unexpect aCatch(SALOME_SalomeException);
2300 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2301 if ( !geom->_is_nil() ) {
2302 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2303 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2305 // try to find the corresponding SObject
2306 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2307 if ( SObj->_is_nil() ) // submesh can be not found even if published
2309 // try to find published submesh
2310 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2311 if ( !geom->IsMainShape() && list->length() == 1 ) {
2312 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2313 SALOMEDS::ChildIterator_wrap it;
2314 if ( !mainSO->_is_nil() ) {
2315 it = getStudyServant()->NewChildIterator( mainSO );
2317 if ( !it->_is_nil() ) {
2318 for ( it->InitEx(true); it->More(); it->Next() ) {
2319 SALOMEDS::SObject_wrap so = it->Value();
2320 CORBA::Object_var obj = SObjectToObject( so );
2321 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2322 if ( !subGeom->_is_nil() ) {
2323 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2324 if ( subList->length() == 1 && list[0] == subList[0] ) {
2334 if ( SObj->_is_nil() ) // publish a new subshape
2335 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2337 // return only published geometry
2338 if ( !SObj->_is_nil() ) {
2339 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2340 CORBA::Object_var obj = SObjectToObject( SObj );
2341 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2345 return GEOM::GEOM_Object::_nil();
2348 //================================================================================
2350 * \brief Return geometrical object the given element is built on.
2351 * \param theMesh - the mesh the element is in
2352 * \param theElementID - the element ID
2353 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2355 //================================================================================
2357 GEOM::GEOM_Object_ptr
2358 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2359 CORBA::Long theElementID)
2360 throw ( SALOME::SALOME_Exception )
2362 Unexpect aCatch(SALOME_SalomeException);
2363 if ( CORBA::is_nil( theMesh ) )
2364 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2366 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2367 GEOM::GEOM_Gen_ptr geomGen = GetGeomEngine();
2369 // get a core mesh DS
2370 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2371 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2373 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2374 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2375 // find the element in mesh
2376 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2377 // find a shape id by the element
2378 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2379 // get a geom object by the shape id
2380 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2381 if ( geom->_is_nil() ) {
2382 // try to find a published sub-shape
2383 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2384 SALOMEDS::ChildIterator_wrap it;
2385 if ( !mainSO->_is_nil() ) {
2386 it = getStudyServant()->NewChildIterator( mainSO );
2388 if ( !it->_is_nil() ) {
2389 for ( it->InitEx(true); it->More(); it->Next() ) {
2390 SALOMEDS::SObject_wrap so = it->Value();
2391 CORBA::Object_var obj = SObjectToObject( so );
2392 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2393 if ( !subGeom->_is_nil() ) {
2394 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2395 if ( subList->length() == 1 && shapeID == subList[0] ) {
2403 if ( geom->_is_nil() ) {
2405 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2406 if ( !op->_is_nil() )
2407 geom = op->GetSubShape( mainShape, shapeID );
2412 if ( !geom->_is_nil() ) {
2413 GeomObjectToShape( geom ); // let geom client remember the found shape
2414 return geom._retn();
2419 return GEOM::GEOM_Object::_nil();
2422 //================================================================================
2424 * SMESH_Gen_i::Concatenate
2426 * Concatenate the given meshes into one mesh
2428 //================================================================================
2430 SMESH::SMESH_Mesh_ptr
2431 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2432 CORBA::Boolean theUniteIdenticalGroups,
2433 CORBA::Boolean theMergeNodesAndElements,
2434 CORBA::Double theMergeTolerance)
2435 throw ( SALOME::SALOME_Exception )
2437 return ConcatenateCommon(theMeshesArray,
2438 theUniteIdenticalGroups,
2439 theMergeNodesAndElements,
2444 //================================================================================
2446 * SMESH_Gen_i::ConcatenateWithGroups
2448 * Concatenate the given meshes into one mesh
2449 * Create the groups of all elements from initial meshes
2451 //================================================================================
2453 SMESH::SMESH_Mesh_ptr
2454 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2455 CORBA::Boolean theUniteIdenticalGroups,
2456 CORBA::Boolean theMergeNodesAndElements,
2457 CORBA::Double theMergeTolerance)
2458 throw ( SALOME::SALOME_Exception )
2460 return ConcatenateCommon(theMeshesArray,
2461 theUniteIdenticalGroups,
2462 theMergeNodesAndElements,
2467 //================================================================================
2469 * SMESH_Gen_i::ConcatenateCommon
2471 * Concatenate the given meshes into one mesh
2473 //================================================================================
2475 SMESH::SMESH_Mesh_ptr
2476 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2477 CORBA::Boolean theUniteIdenticalGroups,
2478 CORBA::Boolean theMergeNodesAndElements,
2479 CORBA::Double theMergeTolerance,
2480 CORBA::Boolean theCommonGroups)
2481 throw ( SALOME::SALOME_Exception )
2483 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2484 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2487 SMESH::SMESH_Mesh_var newMesh = CreateEmptyMesh();
2488 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2489 if ( !newImpl ) return newMesh._retn();
2491 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2492 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2494 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2495 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2496 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2497 TGroupsMap groupsMap;
2498 TListOfNewGroups listOfNewGroups;
2500 ::SMESH_MeshEditor newEditor( &locMesh );
2501 ::SMESH_MeshEditor::ElemFeatures elemType;
2503 // loop on sub-meshes
2504 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2506 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2507 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2508 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2509 if ( !initImpl ) continue;
2512 // assure that IDs increments by one during iteration
2513 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2514 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2515 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2516 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2518 initMeshDS->Modified();
2519 initMeshDS->CompactMesh();
2522 // remember nb of elements before filling in
2523 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2527 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2528 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2529 while ( elemIt->more() )
2531 SMESH_NodeXYZ node = elemIt->next();
2532 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2537 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2538 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2539 while ( elemIt->more() )
2541 const SMDS_MeshElement* elem = elemIt->next();
2542 elemType.myNodes.resize( elem->NbNodes() );
2544 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2545 for ( int k = 0; itNodes->more(); k++)
2547 const SMDS_MeshNode* node = itNodes->next();
2548 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2551 // creates a corresponding element on existent nodes in new mesh
2552 newElems[ elem->GetID() ] =
2553 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2555 newEditor.ClearLastCreated(); // forget the history
2558 // create groups of just added elements
2559 SMESH::SMESH_Group_var newGroup;
2560 SMESH::ElementType groupType;
2561 if ( theCommonGroups )
2564 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2565 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2566 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2567 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2570 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2572 for( groupType = SMESH::NODE;
2573 groupType < SMESH::NB_ELEMENT_TYPES;
2574 groupType = (SMESH::ElementType)( groupType + 1 ))
2576 if ( curState[ groupType ] <= prevState[ groupType ])
2577 continue; // no elements of groupType added from the i-th mesh
2579 // make a group name
2580 std::string groupName = "Gr";
2581 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2583 CORBA::String_var name = meshSO->GetName();
2587 groupName += typeNames[ groupType ];
2589 // make and fill a group
2590 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2591 std::vector< const SMDS_MeshElement* > & elemVec =
2592 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2593 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2595 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2597 for ( size_t j = 0; j < elemVec.size(); ++j )
2599 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2600 grpDS->Add( elemVec[j] );
2604 listOfNewGroups.clear();
2605 listOfNewGroups.push_back( newGroup );
2606 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2611 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2615 SMESH::SMESH_GroupBase_ptr group;
2616 CORBA::String_var groupName;
2617 SMESH::long_array_var newIDs = new SMESH::long_array();
2619 // loop on groups of a source mesh
2620 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2621 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2623 group = listOfGroups[iG];
2624 groupType = group->GetType();
2625 groupName = group->GetName();
2626 std::string name = groupName.in();
2628 // convert a list of IDs
2629 newIDs->length( group->Size() );
2630 std::vector< const SMDS_MeshElement* > & elemVec =
2631 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2632 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2634 while ( itGrElems->more() )
2636 const SMDS_MeshElement* elem = itGrElems->next();
2637 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2639 newIDs[ nbElems++ ] = newElem->GetID();
2641 newIDs->length( nbElems );
2643 // check that a current group name and type don't have identical ones in final mesh
2644 listOfNewGroups.clear();
2645 TNameAndType nameAndType( name, groupType );
2646 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2647 if ( anIter == groupsMap.end() )
2649 // add a new group in the mesh
2650 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2651 newGroup->Add( newIDs );
2653 listOfNewGroups.push_back( newGroup );
2654 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2656 else if ( theUniteIdenticalGroups )
2658 // unite identical groups
2659 TListOfNewGroups& aNewGroups = anIter->second;
2660 aNewGroups.front()->Add( newIDs );
2664 // rename identical groups
2665 newGroup = newImpl->CreateGroup( groupType, groupName );
2666 newGroup->Add( newIDs );
2668 TListOfNewGroups& newGroups = anIter->second;
2669 std::string newGroupName;
2670 if ( newGroups.size() == 1 )
2672 newGroupName = name + "_1";
2673 newGroups.front()->SetName( newGroupName.c_str() );
2675 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2676 newGroup->SetName( newGroupName.c_str() );
2677 newGroups.push_back( newGroup );
2680 } // if an IDSource is a mesh
2683 if ( theMergeNodesAndElements ) // merge nodes
2685 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2686 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2687 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2688 /*SeparateCornersAndMedium=*/ false );
2689 newEditor.MergeNodes( groupsOfNodes );
2691 newEditor.MergeEqualElements();
2694 // Update Python script
2695 pythonDump << newMesh << " = " << this
2696 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "("
2697 << theMeshesArray << ", "
2698 << theUniteIdenticalGroups << ", "
2699 << theMergeNodesAndElements << ", "
2700 << TVar( theMergeTolerance ) << ")";
2702 pPythonDump.reset(); // enable python dump from GetGroups()
2704 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2705 if ( !newMesh->_is_nil() )
2707 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2710 // IPAL21468 Change icon of compound because it need not be computed.
2711 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2712 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2714 newMeshDS->Modified();
2716 return newMesh._retn();
2719 //================================================================================
2721 * \brief Create a mesh by copying a part of another mesh
2722 * \param meshPart - a part of mesh to copy
2723 * \param toCopyGroups - to create in the new mesh groups
2724 * the copied elements belongs to
2725 * \param toKeepIDs - to preserve IDs of the copied elements or not
2726 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2728 //================================================================================
2730 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2731 const char* meshName,
2732 CORBA::Boolean toCopyGroups,
2733 CORBA::Boolean toKeepIDs)
2734 throw ( SALOME::SALOME_Exception )
2736 Unexpect aCatch(SALOME_SalomeException);
2738 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2739 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2741 // 1. Get source mesh
2743 if ( CORBA::is_nil( meshPart ))
2744 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2746 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2747 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2749 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2751 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2753 // 2. Make a new mesh
2755 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2756 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2758 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2759 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2760 if ( !meshSO->_is_nil() )
2762 SetName( meshSO, meshName, "Mesh" );
2763 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2765 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2766 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2767 ::SMESH_MeshEditor::ElemFeatures elemType;
2769 // 3. Get elements to copy
2771 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2772 TIDSortedElemSet srcElems;
2773 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2774 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2777 srcElemIt = srcMeshDS->elementsIterator();
2778 srcNodeIt = srcMeshDS->nodesIterator();
2782 SMESH::long_array_var ids = meshPart->GetIDs();
2783 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2785 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2786 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2787 srcElems.insert( elem );
2791 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2792 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2793 srcElems.insert( elem );
2795 if ( srcElems.empty() )
2796 return newMesh._retn();
2798 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2799 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2804 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2805 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2806 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2808 const SMDS_MeshNode *nSrc, *nTgt;
2809 vector< const SMDS_MeshNode* > nodes;
2810 while ( srcElemIt->more() )
2812 const SMDS_MeshElement * elem = srcElemIt->next();
2814 nodes.resize( elem->NbNodes());
2815 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2817 for ( iN = 0; nIt->more(); ++iN )
2819 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2820 nTgt = newMeshDS->FindNode( nSrc->GetID());
2822 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2827 for ( iN = 0; nIt->more(); ++iN )
2829 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2830 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2832 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2833 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2837 if ( elem->GetType() != SMDSAbs_Node )
2839 elemType.Init( elem, /*basicOnly=*/false );
2840 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2842 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2843 if ( toCopyGroups && !toKeepIDs )
2844 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2846 } // while ( srcElemIt->more() )
2848 // 4(b). Copy free nodes
2850 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2852 while ( srcNodeIt->more() )
2854 nSrc = srcNodeIt->next();
2855 if ( nSrc->NbInverseElements() == 0 )
2858 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2860 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2867 int nbNewGroups = 0;
2870 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2871 while ( gIt->more() )
2873 SMESH_Group* group = gIt->next();
2874 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2876 // Check group type. We copy nodal groups containing nodes of copied element
2877 SMDSAbs_ElementType groupType = groupDS->GetType();
2878 if ( groupType != SMDSAbs_Node &&
2879 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2880 continue; // group type differs from types of meshPart
2882 // Find copied elements in the group
2883 vector< const SMDS_MeshElement* > groupElems;
2884 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2887 const SMDS_MeshElement* foundElem;
2888 if ( groupType == SMDSAbs_Node )
2890 while ( eIt->more() )
2891 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2892 groupElems.push_back( foundElem );
2896 while ( eIt->more() )
2897 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
2898 groupElems.push_back( foundElem );
2903 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
2904 if ( e2eMap.empty() ) continue;
2905 int minID = e2eMap.begin()->first->GetID();
2906 int maxID = e2eMap.rbegin()->first->GetID();
2907 TE2EMap::iterator e2e;
2908 while ( eIt->more() && groupElems.size() < e2eMap.size())
2910 const SMDS_MeshElement* e = eIt->next();
2911 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
2912 if ((e2e = e2eMap.find( e )) != e2eMap.end())
2913 groupElems.push_back( e2e->second );
2917 if ( !groupElems.empty() )
2919 SMESH::SMESH_Group_var newGroupObj =
2920 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
2921 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
2923 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
2924 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
2925 for ( unsigned i = 0; i < groupElems.size(); ++i )
2926 smdsGroup.Add( groupElems[i] );
2934 newMeshDS->Modified();
2936 *pyDump << newMesh << " = " << this
2937 << ".CopyMesh( " << meshPart << ", "
2938 << "'" << meshName << "', "
2939 << toCopyGroups << ", "
2940 << toKeepIDs << ")";
2942 pyDumpDeleter.reset(); // allow dump in GetGroups()
2944 if ( nbNewGroups > 0 ) // dump created groups
2945 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2947 return newMesh._retn();
2951 namespace // utils for CopyMeshWithGeom()
2953 typedef std::map< std::string, std::string > TStr2StrMap;
2954 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
2955 //typedef std::map< std::set<int>, int > TIdSet2IndexMap;
2957 //================================================================================
2959 * \brief Return a new sub-shape corresponding to an old one
2961 //================================================================================
2965 SMESH_Mesh_i* mySrcMesh_i;
2966 SMESH_Mesh_i* myNewMesh_i;
2967 SMESH_Gen_i* myGen_i;
2971 TStr2StrMap myOld2NewEntryMap; // map of study entries
2973 //GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
2974 //TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
2977 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
2979 // not directly relating to shape search
2980 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
2982 //================================================================================
2984 * \brief Constructor
2986 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
2987 SMESH_Mesh_i* newMesh_i,
2988 SMESH_Gen_i* smeshGen_i )
2989 : mySrcMesh_i( srcMesh_i ),
2990 myNewMesh_i( newMesh_i ),
2991 myGen_i ( smeshGen_i ),
2992 myToPublish( smeshGen_i->IsEnablePublish() ),
2993 myGIPMapDone( false )
2995 // retrieve from the study shape mapping made thanks to
2996 // "Set presentation parameters and sub-shapes from arguments" option
2998 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
2999 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3000 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3001 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3002 if ( newSO->_is_nil() )
3004 myToPublish = false;
3007 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3009 CORBA::String_var oldEntry = oldSO->GetID();
3010 CORBA::String_var newEntry = newSO->GetID();
3011 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3012 std::string( newEntry.in() )));
3014 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3015 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3016 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3017 GEOM::ListOfGO_var subShapes = op->GetExistingSubObjects( mainShapeNew,
3018 /*groupsOnly=*/false );
3019 for ( CORBA::ULong i = 0; i < subShapes->length(); ++i )
3021 newSO = myGen_i->ObjectToSObject( subShapes[ i ]);
3022 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3023 for ( ; anIter->More(); anIter->Next() )
3025 SALOMEDS::SObject_wrap so = anIter->Value();
3026 if ( so->ReferencedObject( oldSO.inout() ))
3028 oldEntry = oldSO->GetID();
3029 newEntry = newSO->GetID();
3030 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3031 std::string( newEntry.in() )));
3037 //================================================================================
3039 * \brief Find a new sub-shape corresponding to an old one
3041 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3044 return GEOM::GEOM_Object::_duplicate( oldShape );
3046 GEOM::GEOM_Object_var newShape;
3048 if ( CORBA::is_nil( oldShape ))
3049 return newShape._retn();
3051 if ( !isChildOfOld( oldShape ))
3052 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3054 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3055 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3057 // try to find by entry
3060 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3061 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3062 if ( o2nID != myOld2NewEntryMap.end() )
3064 newShape = getShapeByEntry( o2nID->second );
3068 if ( newShape->_is_nil() )
3070 // try to construct a new sub-shape using myGIPMap
3072 std::vector< int > newIndices;
3073 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3074 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3076 findNewIDs( oldIndices[i], newIndices );
3078 if ( !newIndices.empty() )
3082 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3084 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3086 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3087 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3089 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3090 newIndicesList->length( newIndices.size() );
3091 for ( size_t i = 0; i < newIndices.size(); ++i )
3092 newIndicesList[ i ] = newIndices[ i ];
3093 grOp->UnionIDs( newShape, newIndicesList );
3097 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3098 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3107 if ( !newShape->_is_nil() && myToPublish )
3109 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3110 if ( !newEntry.in() || !newEntry.in()[0] )
3112 CORBA::String_var name = oldShape->GetName();
3113 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3114 newEntry = newShape->GetStudyEntry();
3115 oldEntry = oldShape->GetStudyEntry();
3116 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3117 std::string( newEntry.in() )));
3121 return newShape._retn();
3124 //================================================================================
3126 * \brief Return a study entry of a new shape by study entry of the old one
3128 std::string FindNew( const std::string & oldEntry )
3133 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3134 if ( o2nID != myOld2NewEntryMap.end() )
3135 return o2nID->second;
3137 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3138 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3141 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3142 if ( newShape->_is_nil() )
3143 return std::string();
3145 CORBA::String_var newEntry = newShape->GetStudyEntry();
3146 return newEntry.in();
3149 //================================================================================
3151 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3152 * Return zero if not found or there are more than one new ID
3154 int FindNew( int oldID )
3163 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3165 if ( myGIPMap[ oldID ].length() == 1 )
3167 newID = myGIPMap[ oldID ][ 0 ];
3169 else if ( myGIPMap[ oldID ].length() > 1 &&
3170 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3172 // select a meshed VERTEX
3173 SMESH_subMesh* newSM;
3174 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3175 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3176 ( !newSM->IsEmpty() ))
3177 newID = myGIPMap[ oldID ][ i ];
3183 //================================================================================
3185 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3186 * Return zero if the old shape is not kept as is in the new shape.
3188 int FindNewNotChanged( SMESH_subMesh* oldSM )
3191 return oldSM->GetId();
3193 int newID = FindNew( oldSM->GetId() );
3197 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3201 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3202 // one new sub-shape of the same type.
3204 if ( oldSM->DependsOn().size() !=
3205 newSM->DependsOn().size() )
3208 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3209 while ( srcSMIt->more() )
3211 oldSM = srcSMIt->next();
3212 int newSubID = FindNew( oldSM->GetId() );
3213 if ( getShapeType( myNewMesh_i, newSubID ) !=
3214 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3220 //================================================================================
3222 * \brief Return shape by study entry
3224 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3226 GEOM::GEOM_Object_var shape;
3227 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3228 if ( !so->_is_nil() )
3230 CORBA::Object_var obj = so->GetObject();
3231 shape = GEOM::GEOM_Object::_narrow( obj );
3233 return shape._retn();
3236 //================================================================================
3238 * \brief Fill myGIPMap by calling GetInPlaceMap()
3242 if ( !myGIPMapDone )
3244 myGIPMapDone = true;
3246 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3247 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3248 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine();
3249 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3252 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3256 myGIPMap = new GEOM::ListOfListOfLong();
3261 //================================================================================
3263 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3264 * number of found IDs
3266 int findNewIDs( int oldID, std::vector< int >& newIDs )
3268 size_t prevNbIDs = newIDs.size();
3270 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3272 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3273 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3275 return newIDs.size() - prevNbIDs;
3278 //================================================================================
3280 * \brief Check if an object relates to the old shape
3282 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3284 if ( CORBA::is_nil( oldShape ))
3286 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3287 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3288 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3289 mainShapeOld1->_is_equivalent( oldShape ));
3292 //================================================================================
3294 * \brief Return shape type by shape ID
3296 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3298 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3299 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3300 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3303 //================================================================================
3305 * \brief Store a source sub-shape for which a counterpart not found and
3306 * a smesh object invalid due to that
3308 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3309 SALOMEDS::SObject_wrap smeshSO )
3311 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3312 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3314 CORBA::String_var smeshEntry = smeshSO->GetID();
3315 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3319 //================================================================================
3321 * \brief Store a source sub-shape for which a counterpart not found and
3322 * a smesh object invalid due to that
3324 void AddInvalid( std::string geomEntry,
3325 SALOMEDS::SObject_wrap smeshSO )
3327 if ( !geomEntry.empty() )
3329 CORBA::String_var smeshEntry = smeshSO->GetID();
3330 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3334 //================================================================================
3336 * \brief Store a source sub-shape for which a counterpart not found and
3337 * a smesh object invalid due to that
3339 void AddInvalid( int oldGeomID,
3340 SALOMEDS::SObject_wrap smeshSO )
3342 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3343 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3346 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3347 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3349 SMESH_Comment geomName( typeName[ shapeType ]);
3350 geomName << " #" << oldGeomID;
3352 CORBA::String_var smeshEntry = smeshSO->GetID();
3353 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3356 //================================================================================
3358 * \brief Return entries of a source sub-shape for which a counterpart not found and
3359 * of smesh objects invalid due to that
3361 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3362 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3365 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3366 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3368 nbSO += 1 + entry2entrySet->second.size();
3370 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3371 theInvalidEntries->length ( nbSO );
3372 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3374 entry2entrySet = myInvalidMap.begin();
3375 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3377 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3379 std::set< std::string > & entrySet = entry2entrySet->second;
3380 std::set< std::string >::iterator entry = entrySet.begin();
3381 for ( ; entry != entrySet.end(); ++entry )
3383 theInvalidEntries[ iEntry++ ] = entry->c_str();
3385 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3386 if ( !so->_is_nil() )
3387 theInvalidMeshSObjects[ iSO++ ] = so;
3392 }; // struct ShapeMapper
3394 //================================================================================
3396 * \brief Append an item to a CORBA sequence
3398 template < class CORBA_seq, class ITEM >
3399 void append( CORBA_seq& seq, ITEM item )
3401 if ( !CORBA::is_nil( item ))
3403 seq->length( 1 + seq->length() );
3404 seq[ seq->length() - 1 ] = item;
3407 } // namespace // utils for CopyMeshWithGeom()
3409 //================================================================================
3411 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3412 * \param [in] sourceMesh - a mesh to copy
3413 * \param [in] newGeometry - a new geometry
3414 * \param [in] toCopyGroups - to create groups in the new mesh
3415 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3416 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3417 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3418 * \param [out] newMesh - return a new mesh
3419 * \param [out] newGroups - return new groups
3420 * \param [out] newSubmeshes - return new sub-meshes
3421 * \param [out] newHypotheses - return new algorithms and hypotheses
3422 * \param [out] invalidEntries - return study entries of objects whose
3423 * counterparts are not found in the newGeometry, followed by entries
3424 * of mesh sub-objects that are invalid because they depend on a not found
3425 * preceeding sub-shape
3426 * \return CORBA::Boolean - is a success
3428 //================================================================================
3430 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3431 GEOM::GEOM_Object_ptr theNewGeometry,
3432 const char* theMeshName,
3433 CORBA::Boolean theToCopyGroups,
3434 CORBA::Boolean theToReuseHypotheses,
3435 CORBA::Boolean theToCopyElements,
3436 SMESH::SMESH_Mesh_out theNewMesh,
3437 SMESH::ListOfGroups_out theNewGroups,
3438 SMESH::submesh_array_out theNewSubmeshes,
3439 SMESH::ListOfHypothesis_out theNewHypotheses,
3440 SMESH::string_array_out theInvalidEntries)
3441 throw ( SALOME::SALOME_Exception )
3443 if ( CORBA::is_nil( theSourceMesh ) ||
3444 CORBA::is_nil( theNewGeometry ))
3445 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3447 if ( !theSourceMesh->HasShapeToMesh() )
3448 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3453 TPythonDump pyDump; // prevent dump from CreateMesh()
3455 theNewMesh = CreateMesh( theNewGeometry );
3456 theNewGroups = new SMESH::ListOfGroups();
3457 theNewSubmeshes = new SMESH::submesh_array();
3458 theNewHypotheses = new SMESH::ListOfHypothesis();
3459 theInvalidEntries = new SMESH::string_array();
3461 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3463 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3464 GEOM::GEOM_Object_var geom, newGeom;
3465 SALOMEDS::SObject_wrap so;
3467 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3468 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3471 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3473 // treat hypotheses of mesh and sub-meshes
3474 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3475 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3477 bool isSubMesh = ( iSM < smList->length() );
3480 // create a new sub-mesh
3481 SMESH::SMESH_subMesh_var newSM;
3482 geom = smList[iSM]->GetSubShape();
3483 so = ObjectToSObject( smList[iSM] );
3484 CORBA::String_var name;
3485 if ( !so->_is_nil() )
3486 name = so->GetName();
3487 newGeom = shapeMapper.FindNew( geom );
3488 if ( newGeom->_is_nil() )
3490 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3491 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3496 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3498 append( theNewSubmeshes, newSM );
3500 if ( newGeom->_is_nil() )
3501 continue; // don't assign hypotheses
3505 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3507 so = ObjectToSObject( theNewMesh );
3508 SetName( so, theMeshName, "Mesh" );
3511 // assign hypotheses
3512 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3513 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3515 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3516 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3518 // get geometry hyp depends on
3519 std::vector< std::string > entryArray;
3520 std::vector< int > subIDArray;
3521 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3523 if ( !theToReuseHypotheses || dependsOnGeom )
3525 // create a new hypothesis
3526 CORBA::String_var type = hyp->GetName();
3527 CORBA::String_var lib = hyp->GetLibName();
3528 CORBA::String_var data = hyp_i->SaveTo();
3531 hyp = CreateHypothesis( type, lib );
3532 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3533 hyp_i->LoadFrom( data.in() );
3534 append( theNewHypotheses, hyp );
3538 // update geometry hyp depends on
3539 if ( dependsOnGeom )
3541 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3543 if ( !entryArray[ iGeo ].empty() )
3545 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3546 if ( newEntry.empty() )
3549 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3550 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3552 entryArray[ iGeo ] = newEntry;
3555 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3557 if ( subIDArray[ iGeo ] > 0 )
3559 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3563 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3564 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3566 subIDArray[ iGeo ] = newID;
3569 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3573 CORBA::String_var errorText;
3574 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3575 if ( errorText.in()[0] )
3578 } // loop on hypotheses
3579 } // loop on sub-meshes and mesh
3582 // copy mesh elements, keeping IDs
3583 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3584 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3586 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3587 ::SMESH_MeshEditor::ElemFeatures elemData;
3589 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3590 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3591 /*vertexLast=*/false);
3592 while ( srcSMIt->more() )
3594 SMESH_subMesh* srcSM = srcSMIt->next();
3595 if ( srcSM->IsEmpty() )
3596 continue; // not yet computed
3597 int newID = shapeMapper.FindNewNotChanged( srcSM );
3601 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3602 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3603 while ( nIt->more() )
3605 SMESH_NodeXYZ node( nIt->next() );
3606 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3608 const SMDS_PositionPtr pos = node->GetPosition();
3609 const double* uv = pos->GetParameters();
3610 switch ( pos->GetTypeOfPosition() )
3612 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3613 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3614 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3615 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3619 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3620 while( eIt->more() )
3622 const SMDS_MeshElement* e = eIt->next();
3623 elemData.Init( e, /*basicOnly=*/false );
3624 elemData.SetID( e->GetID() );
3625 elemData.myNodes.resize( e->NbNodes() );
3626 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3628 for ( iN = 0; nnIt->more(); ++iN )
3630 const SMDS_MeshNode* srcNode = nnIt->next();
3631 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3632 if ( !elemData.myNodes[ iN ])
3635 if ( iN == elemData.myNodes.size() )
3636 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3637 newMeshDS->SetMeshElementOnShape( newElem, newID );
3639 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3640 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3643 newMeshDS->Modified();
3649 TStr2StrMap old2newGroupMap;
3651 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3653 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3654 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3655 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3657 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3658 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3659 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3661 CORBA::String_var name = groups[ i ]->GetName();
3662 SMESH::ElementType elemType = groups[ i ]->GetType();
3664 SMESH::SMESH_GroupBase_var newGroup;
3666 if ( !stdlGroup->_is_nil() )
3668 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3670 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3671 const bool isElem = ( elemType != SMESH::NODE );
3672 CORBA::ULong iE = 0;
3673 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3674 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3676 if ( iE < elemIDs->length() )
3678 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3679 stdlGroup->Add( elemIDs );
3680 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3684 else if ( !geomGroup->_is_nil() )
3686 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3687 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3688 if ( newGeom->_is_nil() )
3690 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3691 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3696 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3699 else if ( !fltrGroup->_is_nil() )
3701 // replace geometry in a filter
3702 SMESH::Filter_var filter = fltrGroup->GetFilter();
3703 SMESH::Filter::Criteria_var criteria;
3704 filter->GetCriteria( criteria.out() );
3706 bool isMissingGroup = false;
3707 std::vector< std::string > badEntries;
3709 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3711 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3712 switch ( criteria[ iCr ].Type )
3714 case SMESH::FT_BelongToMeshGroup:
3716 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3717 btgg->SetGroupID( thresholdID );
3718 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3719 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3720 if ( refGroupSO->_is_nil() )
3722 CORBA::String_var refID = refGroupSO->GetID();
3723 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3724 if ( o2nID == old2newGroupMap.end() )
3726 isMissingGroup = true; // corresponding new group not yet created
3729 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3731 if ( o2nID->second.empty() ) // new referred group is invalid
3732 badEntries.push_back( refID.in() );
3735 case SMESH::FT_BelongToGeom:
3736 case SMESH::FT_BelongToPlane:
3737 case SMESH::FT_BelongToCylinder:
3738 case SMESH::FT_BelongToGenSurface:
3739 case SMESH::FT_LyingOnGeom:
3741 std::string newID = shapeMapper.FindNew( thresholdID );
3742 criteria[ iCr ].ThresholdID = newID.c_str();
3743 if ( newID.empty() )
3744 badEntries.push_back( thresholdID );
3747 case SMESH::FT_ConnectedElements:
3749 if ( thresholdID && thresholdID[0] )
3751 std::string newID = shapeMapper.FindNew( thresholdID );
3752 criteria[ iCr ].ThresholdID = newID.c_str();
3753 if ( newID.empty() )
3754 badEntries.push_back( thresholdID );
3760 } // loop on criteria
3762 if ( isMissingGroup && i < nbGroups )
3764 // to treat the group again
3765 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3769 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3770 newFilter->SetCriteria( criteria );
3772 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3773 newFilter->UnRegister();
3775 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3776 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3777 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3779 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3781 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3784 if ( !badEntries.empty() )
3787 } // treat a group on filter
3789 append( theNewGroups, newGroup );
3791 // fill old2newGroupMap
3792 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3793 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3794 if ( !srcSO->_is_nil() )
3796 CORBA::String_var srcID, newID("");
3797 srcID = srcSO->GetID();
3798 if ( !newSO->_is_nil() )
3799 newID = newSO->GetID();
3800 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3801 std::string( newID.in() )));
3804 if ( newGroup->_is_nil() )
3809 newMeshDS->CompactMesh();
3812 if ( !theMeshName || !theMeshName[0] )
3814 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
3815 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
3816 CORBA::String_var oldName = soOld->GetName();
3817 SetName( soNew, oldName.in(), "Mesh" );
3819 // mark invalid objects
3820 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3822 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
3823 highLightInvalid( invalidSObjects[i].in(), true );
3826 << theNewMesh << ", "
3827 << theNewGroups << ", "
3828 << *theNewSubmeshes.ptr() << ", "
3829 << *theNewHypotheses.ptr() << ", "
3830 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
3831 << theSourceMesh << ", "
3832 << theNewGeometry << ", "
3833 << "'" << theMeshName << "', "
3834 << theToCopyGroups << ", "
3835 << theToReuseHypotheses << ", "
3836 << theToCopyElements << " )";
3838 SMESH_CATCH( SMESH::throwCorbaException );
3843 //================================================================================
3845 * \brief Get version of MED format being used.
3847 //================================================================================
3849 char* SMESH_Gen_i::GetMEDFileVersion()
3851 MED::TInt majeur, mineur, release;
3852 majeur = mineur = release = 0;
3853 MED::GetVersionRelease(majeur, mineur, release);
3854 std::ostringstream version;
3855 version << majeur << "." << mineur << "." << release;
3856 return CORBA::string_dup( version.str().c_str() );
3859 //================================================================================
3861 * SMESH_Gen_i::GetMEDVersion
3863 * Get MED version of the file by its name
3865 //================================================================================
3866 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
3868 std::string version = MED::GetMEDVersion( theFileName );
3869 return CORBA::string_dup( version.c_str() );
3872 //================================================================================
3874 * SMESH_Gen_i::CheckCompatibility
3876 * Check compatibility of file with MED format being used, read only.
3878 //================================================================================
3879 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
3881 return MED::CheckCompatibility( theFileName );
3884 //================================================================================
3886 * SMESH_Gen_i::CheckWriteCompatibility
3888 * Check compatibility of file with MED format being used, for append on write.
3890 //================================================================================
3891 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
3893 return MED::CheckCompatibility( theFileName, true );
3896 //================================================================================
3898 * SMESH_Gen_i::GetMeshNames
3900 * Get names of meshes defined in file with the specified name
3902 //================================================================================
3903 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
3905 //MESSAGE("GetMeshNames " << theFileName);
3906 SMESH::string_array_var aResult = new SMESH::string_array();
3907 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
3909 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
3910 //MESSAGE("---" << aNbMeshes);
3912 aResult->length( aNbMeshes );
3913 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
3914 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
3915 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
3918 return aResult._retn();
3921 //=============================================================================
3925 * Save SMESH module's data
3927 //=============================================================================
3928 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
3932 if (!myStudyContext)
3935 // Store study contents as a set of python commands
3938 SALOMEDS::Study_var aStudy = getStudyServant();
3940 // Declare a byte stream
3941 SALOMEDS::TMPFile_var aStreamFile;
3943 // Obtain a temporary dir
3944 TCollection_AsciiString tmpDir =
3945 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
3947 // Create a sequence of files processed
3948 SALOMEDS_Tool::ListOfFiles aFileSeq;
3949 aFileSeq.reserve( NUM_TMP_FILES );
3951 TCollection_AsciiString aStudyName( "" );
3953 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
3955 // Set names of temporary files
3956 TCollection_AsciiString filename =
3957 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
3958 TCollection_AsciiString meshfile =
3959 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
3960 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
3961 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
3962 filename = tmpDir + filename;
3963 meshfile = tmpDir + meshfile;
3966 HDFdataset* aDataset;
3967 HDFgroup* aTopGroup;
3969 HDFgroup* aSubGroup;
3970 HDFgroup* aSubSubGroup;
3971 hdf_size aSize[ 1 ];
3974 //Remove the files if they exist: BugID: 11225
3975 #ifndef WIN32 /* unix functionality */
3976 TCollection_AsciiString cmd("rm -f \"");
3978 TCollection_AsciiString cmd("del /F \"");
3988 system(cmd.ToCString());
3990 // MED writer to be used by storage process
3991 DriverMED_W_SMESHDS_Mesh myWriter;
3992 myWriter.SetFile( meshfile.ToCString() );
3995 // SetStoreName() to groups before storing hypotheses to let them refer to
3996 // groups using "store name", which is "Group <group_persistent_id>"
3998 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
3999 for ( ; itBig->More(); itBig->Next() ) {
4000 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4001 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4002 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4003 if ( !CORBA::is_nil( anObject ) ) {
4004 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4005 if ( !myMesh->_is_nil() ) {
4006 myMesh->Load(); // load from study file if not yet done
4007 TPythonDump pd; // not to dump GetGroups()
4008 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4009 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4011 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4014 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4015 int anId = myStudyContext->findId( string( objStr.in() ) );
4017 sprintf( grpName, "Group %d", anId );
4018 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4019 aGrpBaseDS->SetStoreName( grpName );
4029 // ---> create HDF file
4030 aFile = new HDFfile( (char*) filename.ToCString() );
4031 aFile->CreateOnDisk();
4033 // --> iterator for top-level objects
4034 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4035 for ( ; itBig->More(); itBig->Next() ) {
4036 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4038 // --> hypotheses root branch (only one for the study)
4039 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4040 // create hypotheses root HDF group
4041 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4042 aTopGroup->CreateOnDisk();
4044 // iterator for all hypotheses
4045 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4046 for ( ; it->More(); it->Next() ) {
4047 SALOMEDS::SObject_wrap mySObject = it->Value();
4048 CORBA::Object_var anObject = SObjectToObject( mySObject );
4049 if ( !CORBA::is_nil( anObject ) ) {
4050 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4051 if ( !myHyp->_is_nil() ) {
4052 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4054 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4055 std::string hypname = hn.in();
4056 std::string libname = ln.in();
4058 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4059 // WIN32 and ".so" for X-system) must be deleted
4060 int libname_len = libname.length();
4062 if( libname_len > 4 )
4063 libname.resize( libname_len - 4 );
4065 // PAL17753 (Regression: missing hypothesis in restored study)
4066 // "lib" also should be removed from the beginning
4067 //if( libname_len > 3 )
4068 //libname.resize( libname_len - 3 );
4069 if( libname_len > 6 )
4070 libname = libname.substr( 3, libname_len - 3 - 3 );
4072 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4073 CORBA::String_var hypdata = myImpl->SaveTo();
4074 int id = myStudyContext->findId( string( objStr.in() ));
4076 // for each hypothesis create HDF group basing on its id
4077 char hypGrpName[30];
4078 sprintf( hypGrpName, "Hypothesis %d", id );
4079 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4080 aGroup->CreateOnDisk();
4081 // --> type name of hypothesis
4082 aSize[ 0 ] = hypname.length() + 1;
4083 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4084 aDataset->CreateOnDisk();
4085 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4086 aDataset->CloseOnDisk();
4087 // --> server plugin library name of hypothesis
4088 aSize[ 0 ] = libname.length() + 1;
4089 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4090 aDataset->CreateOnDisk();
4091 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4092 aDataset->CloseOnDisk();
4093 // --> persistent data of hypothesis
4094 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4095 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4096 aDataset->CreateOnDisk();
4097 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4098 aDataset->CloseOnDisk();
4099 // close hypothesis HDF group
4100 aGroup->CloseOnDisk();
4105 // close hypotheses root HDF group
4106 aTopGroup->CloseOnDisk();
4108 // --> algorithms root branch (only one for the study)
4109 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4110 // create algorithms root HDF group
4111 aTopGroup = new HDFgroup( "Algorithms", aFile );
4112 aTopGroup->CreateOnDisk();
4114 // iterator for all algorithms
4115 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4116 for ( ; it->More(); it->Next() ) {
4117 SALOMEDS::SObject_wrap mySObject = it->Value();
4118 CORBA::Object_var anObject = SObjectToObject( mySObject );
4119 if ( !CORBA::is_nil( anObject ) ) {
4120 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4121 if ( !myHyp->_is_nil() ) {
4122 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4124 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4125 std::string hypname = hn.in();
4126 std::string libname = ln.in();
4128 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4129 // WIN32 and ".so" for X-system) must be deleted
4130 int libname_len = libname.length();
4132 if( libname_len > 4 )
4133 libname.resize( libname_len - 4 );
4135 // PAL17753 (Regression: missing hypothesis in restored study)
4136 // "lib" also should be removed from the beginning
4137 //if( libname_len > 3 )
4138 //libname.resize( libname_len - 3 );
4139 if( libname_len > 6 )
4140 libname = libname.substr( 3, libname_len - 3 - 3 );
4142 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4143 CORBA::String_var hypdata = myImpl->SaveTo();
4144 int id = myStudyContext->findId( string( objStr.in() ) );
4146 // for each algorithm create HDF group basing on its id
4147 char hypGrpName[30];
4148 sprintf( hypGrpName, "Algorithm %d", id );
4149 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4150 aGroup->CreateOnDisk();
4151 // --> type name of algorithm
4152 aSize[0] = hypname.length() + 1;
4153 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4154 aDataset->CreateOnDisk();
4155 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4156 aDataset->CloseOnDisk();
4157 // --> server plugin library name of hypothesis
4158 aSize[0] = libname.length() + 1;
4159 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4160 aDataset->CreateOnDisk();
4161 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4162 aDataset->CloseOnDisk();
4163 // --> persistent data of algorithm
4164 aSize[0] = strlen( hypdata.in() ) + 1;
4165 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4166 aDataset->CreateOnDisk();
4167 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4168 aDataset->CloseOnDisk();
4169 // close algorithm HDF group
4170 aGroup->CloseOnDisk();
4175 // close algorithms root HDF group
4176 aTopGroup->CloseOnDisk();
4178 // --> mesh objects roots branches
4179 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4180 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4181 if ( !CORBA::is_nil( anObject ) ) {
4182 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4183 if ( !myMesh->_is_nil() ) {
4184 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4186 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4187 int id = myStudyContext->findId( string( objStr.in() ) );
4188 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4189 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4190 bool hasShape = myLocMesh.HasShapeToMesh();
4192 // for each mesh open the HDF group basing on its id
4193 char meshGrpName[ 30 ];
4194 sprintf( meshGrpName, "Mesh %d", id );
4195 aTopGroup = new HDFgroup( meshGrpName, aFile );
4196 aTopGroup->CreateOnDisk();
4198 // --> put dataset to hdf file which is a flag that mesh has data
4199 string strHasData = "0";
4200 // check if the mesh is not empty
4201 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4202 // write mesh data to med file
4203 myWriter.SetMesh( mySMESHDSMesh );
4204 myWriter.SetMeshId( id );
4207 aSize[ 0 ] = strHasData.length() + 1;
4208 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4209 aDataset->CreateOnDisk();
4210 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4211 aDataset->CloseOnDisk();
4214 // for each mesh open the HDF group basing on its auto color parameter
4215 char meshAutoColorName[ 30 ];
4216 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4218 anAutoColor[0] = myImpl->GetAutoColor();
4220 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4221 aDataset->CreateOnDisk();
4222 aDataset->WriteOnDisk( anAutoColor );
4223 aDataset->CloseOnDisk();
4225 // issue 0020693. Store _isModified flag
4226 int isModified = myLocMesh.GetIsModified();
4228 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4229 aDataset->CreateOnDisk();
4230 aDataset->WriteOnDisk( &isModified );
4231 aDataset->CloseOnDisk();
4233 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4234 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4236 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4237 aDataset->CreateOnDisk();
4238 aDataset->WriteOnDisk( &meshPersistentId );
4239 aDataset->CloseOnDisk();
4241 // write reference on a shape if exists
4242 SALOMEDS::SObject_wrap myRef;
4243 bool shapeRefFound = false;
4244 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4246 SALOMEDS::SObject_wrap myShape;
4247 bool ok = myRef->ReferencedObject( myShape.inout() );
4249 CORBA::Object_var shapeObj = myShape->GetObject();
4250 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4251 CORBA::String_var myRefOnObject = myShape->GetID();
4252 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4253 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4254 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4255 aDataset->CreateOnDisk();
4256 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4257 aDataset->CloseOnDisk();
4263 std::string info = myImpl->FileInfoToString();
4264 if ( !info.empty() )
4266 aSize[ 0 ] = info.size();
4267 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4268 aDataset->CreateOnDisk();
4269 aDataset->WriteOnDisk( (char*) info.data() );
4270 aDataset->CloseOnDisk();
4273 // write applied hypotheses if exist
4274 SALOMEDS::SObject_wrap myHypBranch;
4275 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4276 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4277 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4279 if ( found && (shapeRefFound || !hasShape) ) {
4280 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4281 aGroup->CreateOnDisk();
4283 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4285 for ( ; it->More(); it->Next() ) {
4286 SALOMEDS::SObject_wrap mySObject = it->Value();
4287 SALOMEDS::SObject_wrap myRefOnHyp;
4288 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4290 // san - it is impossible to recover applied hypotheses
4291 // using their entries within Load() method,
4292 // for there are no AttributeIORs in the study when Load() is working.
4293 // Hence, it is better to store persistent IDs of hypotheses as references to them
4295 //string myRefOnObject = myRefOnHyp->GetID();
4296 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4297 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4298 int id = myStudyContext->findId( string( objStr.in() ) );
4299 //if ( myRefOnObject.length() > 0 ) {
4300 //aSize[ 0 ] = myRefOnObject.length() + 1;
4301 char hypName[ 30 ], hypId[ 30 ];
4302 sprintf( hypName, "Hyp %d", ++hypNb );
4303 sprintf( hypId, "%d", id );
4304 aSize[ 0 ] = strlen( hypId ) + 1;
4305 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4306 aDataset->CreateOnDisk();
4307 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4308 aDataset->WriteOnDisk( hypId );
4309 aDataset->CloseOnDisk();
4313 aGroup->CloseOnDisk();
4316 // write applied algorithms if exist
4317 SALOMEDS::SObject_wrap myAlgoBranch;
4318 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4319 myAlgoBranch.inout() );
4320 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4321 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4323 if ( found && (shapeRefFound || !hasShape)) {
4324 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4325 aGroup->CreateOnDisk();
4327 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4329 for ( ; it->More(); it->Next() ) {
4330 SALOMEDS::SObject_wrap mySObject = it->Value();
4331 SALOMEDS::SObject_wrap myRefOnAlgo;
4332 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4334 // san - it is impossible to recover applied algorithms
4335 // using their entries within Load() method,
4336 // for there are no AttributeIORs in the study when Load() is working.
4337 // Hence, it is better to store persistent IDs of algorithms as references to them
4339 //string myRefOnObject = myRefOnAlgo->GetID();
4340 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4341 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4342 int id = myStudyContext->findId( string( objStr.in() ) );
4343 //if ( myRefOnObject.length() > 0 ) {
4344 //aSize[ 0 ] = myRefOnObject.length() + 1;
4345 char algoName[ 30 ], algoId[ 30 ];
4346 sprintf( algoName, "Algo %d", ++algoNb );
4347 sprintf( algoId, "%d", id );
4348 aSize[ 0 ] = strlen( algoId ) + 1;
4349 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4350 aDataset->CreateOnDisk();
4351 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4352 aDataset->WriteOnDisk( algoId );
4353 aDataset->CloseOnDisk();
4357 aGroup->CloseOnDisk();
4360 // --> submesh objects sub-branches
4362 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4363 SALOMEDS::SObject_wrap mySubmeshBranch;
4364 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4366 if ( found ) // check if there is shape reference in submeshes
4368 bool hasShapeRef = false;
4369 SALOMEDS::ChildIterator_wrap itSM =
4370 aStudy->NewChildIterator( mySubmeshBranch );
4371 for ( ; itSM->More(); itSM->Next() ) {
4372 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4373 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4374 mySubRef->ReferencedObject( myShape.inout() );
4375 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4378 { // remove one submesh
4379 if ( shapeRefFound )
4380 { // unassign hypothesis
4381 SMESH::SMESH_subMesh_var mySubMesh =
4382 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4383 if ( !mySubMesh->_is_nil() ) {
4384 int shapeID = mySubMesh->GetId();
4385 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4386 const list<const SMESHDS_Hypothesis*>& hypList =
4387 mySMESHDSMesh->GetHypothesis( S );
4388 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4389 while ( hyp != hypList.end() ) {
4390 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4391 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4395 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4397 } // loop on submeshes of a type
4398 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4399 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4402 } // end check if there is shape reference in submeshes
4404 char name_meshgroup[ 30 ];
4405 if ( i == GetSubMeshOnVertexTag() )
4406 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4407 else if ( i == GetSubMeshOnEdgeTag() )
4408 strcpy( name_meshgroup, "SubMeshes On Edge" );
4409 else if ( i == GetSubMeshOnWireTag() )
4410 strcpy( name_meshgroup, "SubMeshes On Wire" );
4411 else if ( i == GetSubMeshOnFaceTag() )
4412 strcpy( name_meshgroup, "SubMeshes On Face" );
4413 else if ( i == GetSubMeshOnShellTag() )
4414 strcpy( name_meshgroup, "SubMeshes On Shell" );
4415 else if ( i == GetSubMeshOnSolidTag() )
4416 strcpy( name_meshgroup, "SubMeshes On Solid" );
4417 else if ( i == GetSubMeshOnCompoundTag() )
4418 strcpy( name_meshgroup, "SubMeshes On Compound" );
4420 // for each type of submeshes create container HDF group
4421 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4422 aGroup->CreateOnDisk();
4424 // iterator for all submeshes of given type
4425 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4426 for ( ; itSM->More(); itSM->Next() ) {
4427 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4428 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4429 if ( !CORBA::is_nil( anSubObject ))
4431 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4432 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4433 int subid = myStudyContext->findId( string( objStr.in() ) );
4435 // for each mesh open the HDF group basing on its id
4436 char submeshGrpName[ 30 ];
4437 sprintf( submeshGrpName, "SubMesh %d", subid );
4438 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4439 aSubGroup->CreateOnDisk();
4441 // write reference on a shape, already checked if it exists
4442 SALOMEDS::SObject_wrap mySubRef, myShape;
4443 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4444 mySubRef->ReferencedObject( myShape.inout() );
4445 string myRefOnObject = myShape->GetID();
4446 if ( myRefOnObject.length() > 0 ) {
4447 aSize[ 0 ] = myRefOnObject.length() + 1;
4448 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4449 aDataset->CreateOnDisk();
4450 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4451 aDataset->CloseOnDisk();
4454 // write applied hypotheses if exist
4455 SALOMEDS::SObject_wrap mySubHypBranch;
4456 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4457 mySubHypBranch.inout() );
4459 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4460 aSubSubGroup->CreateOnDisk();
4462 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4464 for ( ; it->More(); it->Next() ) {
4465 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4466 SALOMEDS::SObject_wrap myRefOnHyp;
4467 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4469 //string myRefOnObject = myRefOnHyp->GetID();
4470 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4471 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4472 int id = myStudyContext->findId( string( objStr.in() ) );
4473 //if ( myRefOnObject.length() > 0 ) {
4474 //aSize[ 0 ] = myRefOnObject.length() + 1;
4475 char hypName[ 30 ], hypId[ 30 ];
4476 sprintf( hypName, "Hyp %d", ++hypNb );
4477 sprintf( hypId, "%d", id );
4478 aSize[ 0 ] = strlen( hypId ) + 1;
4479 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4480 aDataset->CreateOnDisk();
4481 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4482 aDataset->WriteOnDisk( hypId );
4483 aDataset->CloseOnDisk();
4487 aSubSubGroup->CloseOnDisk();
4490 // write applied algorithms if exist
4491 SALOMEDS::SObject_wrap mySubAlgoBranch;
4492 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4493 mySubAlgoBranch.inout() );
4495 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4496 aSubSubGroup->CreateOnDisk();
4498 SALOMEDS::ChildIterator_wrap it =
4499 aStudy->NewChildIterator( mySubAlgoBranch );
4501 for ( ; it->More(); it->Next() ) {
4502 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4503 SALOMEDS::SObject_wrap myRefOnAlgo;
4504 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4506 //string myRefOnObject = myRefOnAlgo->GetID();
4507 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4508 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4509 int id = myStudyContext->findId( string( objStr.in() ) );
4510 //if ( myRefOnObject.length() > 0 ) {
4511 //aSize[ 0 ] = myRefOnObject.length() + 1;
4512 char algoName[ 30 ], algoId[ 30 ];
4513 sprintf( algoName, "Algo %d", ++algoNb );
4514 sprintf( algoId, "%d", id );
4515 aSize[ 0 ] = strlen( algoId ) + 1;
4516 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4517 aDataset->CreateOnDisk();
4518 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4519 aDataset->WriteOnDisk( algoId );
4520 aDataset->CloseOnDisk();
4524 aSubSubGroup->CloseOnDisk();
4526 // close submesh HDF group
4527 aSubGroup->CloseOnDisk();
4530 // close container of submeshes by type HDF group
4531 aGroup->CloseOnDisk();
4534 // All sub-meshes will be stored in MED file
4535 // .. will NOT (PAL 12992)
4536 //if ( shapeRefFound )
4537 //myWriter.AddAllSubMeshes();
4539 // store submesh order if any
4540 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4541 if ( theOrderIds.size() ) {
4542 char order_list[ 30 ];
4543 strcpy( order_list, "Mesh Order" );
4544 // count number of submesh ids
4546 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4547 for ( ; idIt != theOrderIds.end(); idIt++ )
4548 nbIDs += (*idIt).size();
4549 // number of values = number of IDs +
4550 // number of lists (for separators) - 1
4551 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4552 idIt = theOrderIds.begin();
4553 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4554 const TListOfInt& idList = *idIt;
4555 if (idIt != theOrderIds.begin()) // not first list
4556 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4557 // dump submesh ids from current list
4558 TListOfInt::const_iterator id_smId = idList.begin();
4559 for( ; id_smId != idList.end(); id_smId++ )
4560 smIDs[ i++ ] = *id_smId;
4563 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4565 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4566 aDataset->CreateOnDisk();
4567 aDataset->WriteOnDisk( smIDs );
4568 aDataset->CloseOnDisk();
4573 // groups root sub-branch
4574 SALOMEDS::SObject_wrap myGroupsBranch;
4575 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4576 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4578 char name_group[ 30 ];
4579 if ( i == GetNodeGroupsTag() )
4580 strcpy( name_group, "Groups of Nodes" );
4581 else if ( i == GetEdgeGroupsTag() )
4582 strcpy( name_group, "Groups of Edges" );
4583 else if ( i == GetFaceGroupsTag() )
4584 strcpy( name_group, "Groups of Faces" );
4585 else if ( i == GetVolumeGroupsTag() )
4586 strcpy( name_group, "Groups of Volumes" );
4587 else if ( i == Get0DElementsGroupsTag() )
4588 strcpy( name_group, "Groups of 0D Elements" );
4589 else if ( i == GetBallElementsGroupsTag() )
4590 strcpy( name_group, "Groups of Balls" );
4592 aGroup = new HDFgroup( name_group, aTopGroup );
4593 aGroup->CreateOnDisk();
4595 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4596 for ( ; it->More(); it->Next() ) {
4597 SALOMEDS::SObject_wrap mySObject = it->Value();
4598 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4599 if ( !CORBA::is_nil( aSubObject ) ) {
4600 SMESH_GroupBase_i* myGroupImpl =
4601 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4604 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4608 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4609 int anId = myStudyContext->findId( string( objStr.in() ) );
4611 // For each group, create a dataset named "Group <group_persistent_id>"
4612 // and store the group's user name into it
4613 const char* grpName = aGrpBaseDS->GetStoreName();
4614 CORBA::String_var aUserName = myGroupImpl->GetName();
4615 aSize[ 0 ] = strlen( aUserName ) + 1;
4617 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4618 aDataset->CreateOnDisk();
4619 aDataset->WriteOnDisk( aUserName );
4620 aDataset->CloseOnDisk();
4623 // For each group, create a dataset named "Group <group_persistent_id> Color"
4624 // and store the group's color into it
4625 char grpColorName[ 30 ];
4626 sprintf( grpColorName, "ColorGroup %d", anId );
4627 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4629 anRGB[ 0 ] = aColor.R;
4630 anRGB[ 1 ] = aColor.G;
4631 anRGB[ 2 ] = aColor.B;
4633 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4634 aDataset->CreateOnDisk();
4635 aDataset->WriteOnDisk( anRGB );
4636 aDataset->CloseOnDisk();
4638 // Pass SMESHDS_Group to MED writer
4639 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4641 myWriter.AddGroup( aGrpDS );
4643 // write reference on a shape if exists
4644 SMESHDS_GroupOnGeom* aGeomGrp =
4645 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4647 SALOMEDS::SObject_wrap mySubRef, myShape;
4648 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4649 mySubRef->ReferencedObject( myShape.inout() ) &&
4650 !CORBA::is_nil( myShape->GetObject() ))
4652 CORBA::String_var myRefOnObject = myShape->GetID();
4653 if ( myRefOnObject.in()[0] ) {
4654 char aRefName[ 30 ];
4655 sprintf( aRefName, "Ref on shape %d", anId);
4656 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4657 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4658 aDataset->CreateOnDisk();
4659 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4660 aDataset->CloseOnDisk();
4663 else // shape ref is invalid:
4665 // save a group on geometry as ordinary group
4666 myWriter.AddGroup( aGeomGrp );
4669 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4670 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4672 std::string str = aFilterGrp_i->FilterToString();
4673 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4674 aSize[ 0 ] = str.length() + 1;
4675 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4676 aDataset->CreateOnDisk();
4677 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4678 aDataset->CloseOnDisk();
4682 aGroup->CloseOnDisk();
4686 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4688 // Flush current mesh information into MED file
4691 // save info on nb of elements
4692 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4694 // maybe a shape was deleted in the study
4695 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4696 TopoDS_Shape nullShape;
4697 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4700 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4705 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4706 aGroup->CreateOnDisk();
4708 // each element belongs to one or none submesh,
4709 // so for each node/element, we store a submesh ID
4711 // Store submesh IDs
4712 for ( int isNode = 0; isNode < 2; ++isNode )
4714 SMDS_ElemIteratorPtr eIt =
4715 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4716 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4719 std::vector<int> smIDs; smIDs.reserve( nbElems );
4720 while ( eIt->more() )
4721 if ( const SMDS_MeshElement* e = eIt->next())
4722 smIDs.push_back( e->getshapeId() );
4724 aSize[ 0 ] = nbElems;
4725 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4726 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4727 aDataset->CreateOnDisk();
4728 aDataset->WriteOnDisk( & smIDs[0] );
4729 aDataset->CloseOnDisk();
4732 aGroup->CloseOnDisk();
4734 // Store node positions on sub-shapes (SMDS_Position):
4735 // ----------------------------------------------------
4737 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4738 aGroup->CreateOnDisk();
4740 // in aGroup, create 5 datasets to contain:
4741 // "Nodes on Edges" - ID of node on edge
4742 // "Edge positions" - U parameter on node on edge
4743 // "Nodes on Faces" - ID of node on face
4744 // "Face U positions" - U parameter of node on face
4745 // "Face V positions" - V parameter of node on face
4747 // Find out nb of nodes on edges and faces
4748 // Collect corresponding sub-meshes
4749 int nbEdgeNodes = 0, nbFaceNodes = 0;
4750 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4751 // loop on SMESHDS_SubMesh'es
4752 while ( smIt->more() )
4754 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4755 if ( aSubMesh->IsComplexSubmesh() )
4756 continue; // submesh containing other submeshs
4757 int nbNodes = aSubMesh->NbNodes();
4758 if ( nbNodes == 0 ) continue;
4760 int aShapeID = aSubMesh->GetID();
4761 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4763 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4764 // write only SMDS_FacePosition and SMDS_EdgePosition
4765 switch ( aShapeType ) {
4767 nbFaceNodes += nbNodes;
4768 aFaceSM.push_back( aSubMesh );
4771 nbEdgeNodes += nbNodes;
4772 aEdgeSM.push_back( aSubMesh );
4778 // Treat positions on edges or faces
4779 for ( int onFace = 0; onFace < 2; onFace++ )
4781 // Create arrays to store in datasets
4782 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4783 if (!nbNodes) continue;
4784 int* aNodeIDs = new int [ nbNodes ];
4785 double* aUPos = new double [ nbNodes ];
4786 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4789 // loop on sub-meshes
4790 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4791 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4792 for ( ; itSM != pListSM->end(); itSM++ )
4794 SMESHDS_SubMesh* aSubMesh = (*itSM);
4796 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4797 // loop on nodes in aSubMesh
4798 while ( itNode->more() )
4801 const SMDS_MeshNode* node = itNode->next();
4802 aNodeIDs [ iNode ] = node->GetID();
4805 const SMDS_PositionPtr pos = node->GetPosition();
4806 if ( onFace ) { // on FACE
4807 SMDS_FacePositionPtr fPos = pos;
4809 aUPos[ iNode ] = fPos->GetUParameter();
4810 aVPos[ iNode ] = fPos->GetVParameter();
4817 SMDS_EdgePositionPtr ePos = pos;
4819 aUPos[ iNode ] = ePos->GetUParameter();
4825 } // loop on nodes in aSubMesh
4826 } // loop on sub-meshes
4831 aSize[ 0 ] = nbNodes;
4833 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
4834 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4835 aDataset->CreateOnDisk();
4836 aDataset->WriteOnDisk( aNodeIDs );
4837 aDataset->CloseOnDisk();
4840 aDSName = ( onFace ? "Face U positions" : "Edge positions");
4841 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
4842 aDataset->CreateOnDisk();
4843 aDataset->WriteOnDisk( aUPos );
4844 aDataset->CloseOnDisk();
4847 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
4848 aDataset->CreateOnDisk();
4849 aDataset->WriteOnDisk( aVPos );
4850 aDataset->CloseOnDisk();
4855 if ( aVPos ) delete [] aVPos;
4857 } // treat positions on edges or faces
4859 // close "Node Positions" group
4860 aGroup->CloseOnDisk();
4862 } // if ( there are submeshes in SMESHDS_Mesh )
4865 // close mesh HDF group
4866 aTopGroup->CloseOnDisk();
4874 aFile->CloseOnDisk();
4877 // Convert temporary files to stream
4878 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
4880 // Remove temporary files and directory
4882 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
4884 return aStreamFile._retn();
4887 //=============================================================================
4889 * SMESH_Gen_i::SaveASCII
4891 * Save SMESH module's data in ASCII format
4893 //=============================================================================
4895 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
4897 bool isMultiFile ) {
4898 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
4899 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
4900 return aStreamFile._retn();
4902 //after usual saving needs to encipher binary to text string
4903 //Any binary symbol will be represent as "|xx" () hexadecimal format number
4904 int size = aStreamFile.in().length();
4905 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
4906 for ( int i = 0; i < size; i++ )
4907 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
4909 buffer[size * 3] = '\0';
4911 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
4913 return anAsciiStreamFile._retn();
4916 //=============================================================================
4918 * SMESH_Gen_i::loadGeomData
4920 * Load GEOM module data
4922 //=============================================================================
4924 void SMESH_Gen_i::loadGeomData( SALOMEDS::SComponent_ptr theCompRoot )
4926 if ( theCompRoot->_is_nil() )
4929 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
4930 aStudyBuilder->LoadWith( theCompRoot, GetGeomEngine() );
4933 //=============================================================================
4937 * Load SMESH module's data
4939 //=============================================================================
4941 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
4942 const SALOMEDS::TMPFile& theStream,
4946 //if (!myStudyContext)
4948 SALOMEDS::Study_var aStudy = getStudyServant();
4949 /* if( !theComponent->_is_nil() )
4951 if( !aStudy->FindComponent( "GEOM" )->_is_nil() )
4952 loadGeomData( aStudy->FindComponent( "GEOM" ) );
4955 // Get temporary files location
4956 TCollection_AsciiString tmpDir =
4957 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
4959 // Convert the stream into sequence of files to process
4960 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
4963 TCollection_AsciiString aStudyName( "" );
4964 if ( isMultiFile ) {
4965 CORBA::WString_var url = aStudy->URL();
4966 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
4968 // Set names of temporary files
4969 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
4970 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
4974 HDFdataset* aDataset;
4975 HDFgroup* aTopGroup;
4977 HDFgroup* aSubGroup;
4978 HDFgroup* aSubSubGroup;
4981 // ---> open HDF file
4982 aFile = new HDFfile( (char*) filename.ToCString() );
4984 aFile->OpenOnDisk( HDF_RDONLY );
4986 catch ( HDFexception ) {
4987 INFOS( "Load(): " << filename << " not found!" );
4991 TPythonDump pd; // prevent dump during loading
4993 // DriverMED_R_SMESHDS_Mesh myReader;
4994 // myReader.SetFile( meshfile.ToCString() );
4996 // For PAL13473 ("Repetitive mesh") implementation.
4997 // New dependencies between SMESH objects are established:
4998 // now hypotheses can refer to meshes, shapes and other hypotheses.
4999 // To keep data consistent, the following order of data restoration
5001 // 1. Create hypotheses
5002 // 2. Create all meshes
5003 // 3. Load hypotheses' data
5006 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5007 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5008 list< SMESH::Filter_var > filters;
5010 // get total number of top-level groups
5011 int aNbGroups = aFile->nInternalObjects();
5012 if ( aNbGroups > 0 ) {
5013 // --> in first turn we should read&create hypotheses
5014 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5015 // open hypotheses root HDF group
5016 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5017 aTopGroup->OpenOnDisk();
5019 // get number of hypotheses
5020 int aNbObjects = aTopGroup->nInternalObjects();
5021 for ( int j = 0; j < aNbObjects; j++ ) {
5022 // try to identify hypothesis
5023 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5024 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5026 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5027 // open hypothesis group
5028 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5029 aGroup->OpenOnDisk();
5031 // --> get hypothesis id
5032 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5037 // get number of datasets
5038 int aNbSubObjects = aGroup->nInternalObjects();
5039 for ( int k = 0; k < aNbSubObjects; k++ ) {
5041 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5042 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5043 // --> get hypothesis name
5044 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5045 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5046 aDataset->OpenOnDisk();
5047 size = aDataset->GetSize();
5048 char* hypname_str = new char[ size ];
5049 aDataset->ReadFromDisk( hypname_str );
5050 hypname = string( hypname_str );
5051 delete [] hypname_str;
5052 aDataset->CloseOnDisk();
5054 // --> get hypothesis plugin library name
5055 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5056 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5057 aDataset->OpenOnDisk();
5058 size = aDataset->GetSize();
5059 char* libname_str = new char[ size ];
5060 aDataset->ReadFromDisk( libname_str );
5061 if(MYDEBUG) SCRUTE( libname_str );
5062 libname = string( libname_str );
5063 delete [] libname_str;
5064 aDataset->CloseOnDisk();
5066 // --> get hypothesis data
5067 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5068 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5069 aDataset->OpenOnDisk();
5070 size = aDataset->GetSize();
5071 char* hypdata_str = new char[ size ];
5072 aDataset->ReadFromDisk( hypdata_str );
5073 hypdata = string( hypdata_str );
5074 delete [] hypdata_str;
5075 aDataset->CloseOnDisk();
5078 // close hypothesis HDF group
5079 aGroup->CloseOnDisk();
5081 // --> restore hypothesis from data
5082 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5083 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5084 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5085 SMESH::SMESH_Hypothesis_var myHyp;
5087 try { // protect persistence mechanism against exceptions
5088 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5091 INFOS( "Exception during hypothesis creation" );
5094 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5096 // myImpl->LoadFrom( hypdata.c_str() );
5097 hypDataList.push_back( make_pair( myImpl, hypdata ));
5098 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5099 int newId = myStudyContext->findId( iorString.in() );
5100 myStudyContext->mapOldToNew( id, newId );
5103 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5107 // close hypotheses root HDF group
5108 aTopGroup->CloseOnDisk();
5112 // --> then we should read&create algorithms
5113 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5114 // open algorithms root HDF group
5115 aTopGroup = new HDFgroup( "Algorithms", aFile );
5116 aTopGroup->OpenOnDisk();
5118 // get number of algorithms
5119 int aNbObjects = aTopGroup->nInternalObjects();
5120 for ( int j = 0; j < aNbObjects; j++ ) {
5121 // try to identify algorithm
5122 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5123 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5125 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5126 // open algorithm group
5127 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5128 aGroup->OpenOnDisk();
5130 // --> get algorithm id
5131 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5136 // get number of datasets
5137 int aNbSubObjects = aGroup->nInternalObjects();
5138 for ( int k = 0; k < aNbSubObjects; k++ ) {
5140 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5141 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5142 // --> get algorithm name
5143 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5144 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5145 aDataset->OpenOnDisk();
5146 size = aDataset->GetSize();
5147 char* hypname_str = new char[ size ];
5148 aDataset->ReadFromDisk( hypname_str );
5149 hypname = string( hypname_str );
5150 delete [] hypname_str;
5151 aDataset->CloseOnDisk();
5153 // --> get algorithm plugin library name
5154 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5155 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5156 aDataset->OpenOnDisk();
5157 size = aDataset->GetSize();
5158 char* libname_str = new char[ size ];
5159 aDataset->ReadFromDisk( libname_str );
5160 if(MYDEBUG) SCRUTE( libname_str );
5161 libname = string( libname_str );
5162 delete [] libname_str;
5163 aDataset->CloseOnDisk();
5165 // --> get algorithm data
5166 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5167 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5168 aDataset->OpenOnDisk();
5169 size = aDataset->GetSize();
5170 char* hypdata_str = new char[ size ];
5171 aDataset->ReadFromDisk( hypdata_str );
5172 if(MYDEBUG) SCRUTE( hypdata_str );
5173 hypdata = string( hypdata_str );
5174 delete [] hypdata_str;
5175 aDataset->CloseOnDisk();
5178 // close algorithm HDF group
5179 aGroup->CloseOnDisk();
5181 // --> restore algorithm from data
5182 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5183 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5184 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5185 SMESH::SMESH_Hypothesis_var myHyp;
5187 try { // protect persistence mechanism against exceptions
5188 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5191 INFOS( "Exception during hypothesis creation" );
5194 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5196 //myImpl->LoadFrom( hypdata.c_str() );
5197 hypDataList.push_back( make_pair( myImpl, hypdata ));
5198 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5199 int newId = myStudyContext->findId( iorString.in() );
5200 myStudyContext->mapOldToNew( id, newId );
5203 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5207 // close algorithms root HDF group
5208 aTopGroup->CloseOnDisk();
5212 // --> the rest groups should be meshes
5213 for ( int i = 0; i < aNbGroups; i++ ) {
5214 // identify next group
5215 char meshName[ HDF_NAME_MAX_LEN+1 ];
5216 aFile->InternalObjectIndentify( i, meshName );
5218 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5220 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5224 // open mesh HDF group
5225 aTopGroup = new HDFgroup( meshName, aFile );
5226 aTopGroup->OpenOnDisk();
5228 // get number of child HDF objects
5229 int aNbObjects = aTopGroup->nInternalObjects();
5230 if ( aNbObjects > 0 ) {
5232 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5233 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5234 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5235 if ( !myNewMeshImpl )
5237 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5239 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5240 int newId = myStudyContext->findId( iorString.in() );
5241 myStudyContext->mapOldToNew( id, newId );
5244 // try to read and set auto color flag
5245 char aMeshAutoColorName[ 30 ];
5246 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5247 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5249 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5250 aDataset->OpenOnDisk();
5251 size = aDataset->GetSize();
5252 int* anAutoColor = new int[ size ];
5253 aDataset->ReadFromDisk( anAutoColor );
5254 aDataset->CloseOnDisk();
5255 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5256 delete [] anAutoColor;
5259 // try to read and set reference to shape
5260 GEOM::GEOM_Object_var aShapeObject;
5261 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5262 // load mesh "Ref on shape" - it's an entry to SObject
5263 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5264 aDataset->OpenOnDisk();
5265 size = aDataset->GetSize();
5266 char* refFromFile = new char[ size ];
5267 aDataset->ReadFromDisk( refFromFile );
5268 aDataset->CloseOnDisk();
5269 if ( strlen( refFromFile ) > 0 ) {
5270 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5272 // Make sure GEOM data are loaded first
5273 //loadGeomData( shapeSO->GetFatherComponent() );
5275 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5276 if ( !CORBA::is_nil( shapeObject ) ) {
5277 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5278 if ( !aShapeObject->_is_nil() )
5279 myNewMeshImpl->SetShape( aShapeObject );
5282 delete [] refFromFile;
5285 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5286 if( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5288 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5289 aDataset->OpenOnDisk();
5290 size = aDataset->GetSize();
5291 int* meshPersistentId = new int[ size ];
5292 aDataset->ReadFromDisk( meshPersistentId );
5293 aDataset->CloseOnDisk();
5294 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5295 delete [] meshPersistentId;
5298 // Restore file info
5299 if ( aTopGroup->ExistInternalObject( "file info" ))
5301 aDataset = new HDFdataset( "file info", aTopGroup );
5302 aDataset->OpenOnDisk();
5303 size = aDataset->GetSize();
5304 std::string info( size, ' ');
5305 aDataset->ReadFromDisk( (char*) info.data() );
5306 aDataset->CloseOnDisk();
5307 myNewMeshImpl->FileInfoFromString( info );
5313 // As all object that can be referred by hypothesis are created,
5314 // we can restore hypothesis data
5316 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5317 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5319 SMESH_Hypothesis_i* hyp = hyp_data->first;
5320 string & data = hyp_data->second;
5321 hyp->LoadFrom( data.c_str() );
5324 // Restore the rest mesh data
5326 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5327 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5329 aTopGroup = meshi_group->second;
5330 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5331 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5332 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5334 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5335 bool hasData = false;
5338 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5339 int newId = myStudyContext->findId( iorString.in() );
5340 int id = myStudyContext->getOldId( newId );
5342 // try to find mesh data dataset
5343 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5344 // load mesh "has data" flag
5345 aDataset = new HDFdataset( "Has data", aTopGroup );
5346 aDataset->OpenOnDisk();
5347 size = aDataset->GetSize();
5348 char* strHasData = new char[ size ];
5349 aDataset->ReadFromDisk( strHasData );
5350 aDataset->CloseOnDisk();
5351 if ( strcmp( strHasData, "1") == 0 ) {
5352 // read mesh data from MED file
5353 // myReader.SetMesh( mySMESHDSMesh );
5354 // myReader.SetMeshId( id );
5355 // myReader.Perform();
5358 delete [] strHasData;
5361 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5362 // nodes and elements are not yet put into sub-meshes)
5363 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5364 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5365 aGroup->OpenOnDisk();
5366 // get number of applied algorithms
5367 int aNbSubObjects = aGroup->nInternalObjects();
5368 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5369 for ( int j = 0; j < aNbSubObjects; j++ ) {
5370 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5371 aGroup->InternalObjectIndentify( j, name_dataset );
5372 // check if it is an algorithm
5373 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5374 aDataset = new HDFdataset( name_dataset, aGroup );
5375 aDataset->OpenOnDisk();
5376 size = aDataset->GetSize();
5377 char* refFromFile = new char[ size ];
5378 aDataset->ReadFromDisk( refFromFile );
5379 aDataset->CloseOnDisk();
5380 // san - it is impossible to recover applied algorithms using their entries within Load() method
5381 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5382 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5383 int id = atoi( refFromFile );
5384 delete [] refFromFile;
5385 string anIOR = myStudyContext->getIORbyOldId( id );
5386 if ( !anIOR.empty() ) {
5387 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5388 if ( !CORBA::is_nil( hypObject ) ) {
5389 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5390 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5391 || !myNewMeshImpl->HasShapeToMesh()) )
5392 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5397 aGroup->CloseOnDisk();
5400 // try to get applied hypotheses
5401 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5402 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5403 aGroup->OpenOnDisk();
5404 // get number of applied hypotheses
5405 int aNbSubObjects = aGroup->nInternalObjects();
5406 for ( int j = 0; j < aNbSubObjects; j++ ) {
5407 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5408 aGroup->InternalObjectIndentify( j, name_dataset );
5409 // check if it is a hypothesis
5410 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5411 aDataset = new HDFdataset( name_dataset, aGroup );
5412 aDataset->OpenOnDisk();
5413 size = aDataset->GetSize();
5414 char* refFromFile = new char[ size ];
5415 aDataset->ReadFromDisk( refFromFile );
5416 aDataset->CloseOnDisk();
5417 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5418 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5419 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5420 int id = atoi( refFromFile );
5421 delete [] refFromFile;
5422 string anIOR = myStudyContext->getIORbyOldId( id );
5423 if ( !anIOR.empty() ) {
5424 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5425 if ( !CORBA::is_nil( hypObject ) ) {
5426 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5427 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5428 || !myNewMeshImpl->HasShapeToMesh()) )
5429 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5434 aGroup->CloseOnDisk();
5437 // --> try to find SUB-MESHES containers for each type of submesh
5438 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5439 const char* name_meshgroup = 0;
5440 if ( j == GetSubMeshOnVertexTag() )
5441 name_meshgroup = "SubMeshes On Vertex";
5442 else if ( j == GetSubMeshOnEdgeTag() )
5443 name_meshgroup = "SubMeshes On Edge";
5444 else if ( j == GetSubMeshOnWireTag() )
5445 name_meshgroup = "SubMeshes On Wire";
5446 else if ( j == GetSubMeshOnFaceTag() )
5447 name_meshgroup = "SubMeshes On Face";
5448 else if ( j == GetSubMeshOnShellTag() )
5449 name_meshgroup = "SubMeshes On Shell";
5450 else if ( j == GetSubMeshOnSolidTag() )
5451 name_meshgroup = "SubMeshes On Solid";
5452 else if ( j == GetSubMeshOnCompoundTag() )
5453 name_meshgroup = "SubMeshes On Compound";
5455 // try to get submeshes container HDF group
5456 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5457 // open submeshes containers HDF group
5458 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5459 aGroup->OpenOnDisk();
5461 // get number of submeshes
5462 int aNbSubMeshes = aGroup->nInternalObjects();
5463 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5465 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5466 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5467 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5468 // --> get submesh id
5469 int subid = atoi( name_submeshgroup + 7 );
5472 // open submesh HDF group
5473 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5474 aSubGroup->OpenOnDisk();
5476 // try to read and set reference to subshape
5477 GEOM::GEOM_Object_var aSubShapeObject;
5478 SMESH::SMESH_subMesh_var aSubMesh;
5480 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5481 // load submesh "Ref on shape" - it's an entry to SObject
5482 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5483 aDataset->OpenOnDisk();
5484 size = aDataset->GetSize();
5485 char* refFromFile = new char[ size ];
5486 aDataset->ReadFromDisk( refFromFile );
5487 aDataset->CloseOnDisk();
5488 if ( strlen( refFromFile ) > 0 ) {
5489 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5490 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5491 if ( !CORBA::is_nil( subShapeObject ) ) {
5492 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5493 if ( !aSubShapeObject->_is_nil() )
5494 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5495 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5496 if ( aSubMesh->_is_nil() )
5498 string iorSubString = GetORB()->object_to_string( aSubMesh );
5499 int newSubId = myStudyContext->findId( iorSubString );
5500 myStudyContext->mapOldToNew( subid, newSubId );
5503 delete [] refFromFile;
5506 if ( aSubMesh->_is_nil() )
5509 // try to get applied algorithms
5510 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5511 // open "applied algorithms" HDF group
5512 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5513 aSubSubGroup->OpenOnDisk();
5514 // get number of applied algorithms
5515 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5516 for ( int l = 0; l < aNbSubObjects; l++ ) {
5517 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5518 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5519 // check if it is an algorithm
5520 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5521 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5522 aDataset->OpenOnDisk();
5523 size = aDataset->GetSize();
5524 char* refFromFile = new char[ size ];
5525 aDataset->ReadFromDisk( refFromFile );
5526 aDataset->CloseOnDisk();
5528 int id = atoi( refFromFile );
5529 string anIOR = myStudyContext->getIORbyOldId( id );
5530 if ( !anIOR.empty() ) {
5531 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5532 if ( !CORBA::is_nil( hypObject ) ) {
5533 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5534 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5535 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5538 delete [] refFromFile;
5541 // close "applied algorithms" HDF group
5542 aSubSubGroup->CloseOnDisk();
5545 // try to get applied hypotheses
5546 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5547 // open "applied hypotheses" HDF group
5548 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5549 aSubSubGroup->OpenOnDisk();
5550 // get number of applied hypotheses
5551 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5552 for ( int l = 0; l < aNbSubObjects; l++ ) {
5553 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5554 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5555 // check if it is a hypothesis
5556 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5557 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5558 aDataset->OpenOnDisk();
5559 size = aDataset->GetSize();
5560 char* refFromFile = new char[ size ];
5561 aDataset->ReadFromDisk( refFromFile );
5562 aDataset->CloseOnDisk();
5564 int id = atoi( refFromFile );
5565 string anIOR = myStudyContext->getIORbyOldId( id );
5566 if ( !anIOR.empty() ) {
5567 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5568 if ( !CORBA::is_nil( hypObject ) ) {
5569 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5570 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5571 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5574 delete [] refFromFile;
5577 // close "APPLIED HYPOTHESES" hdf group
5578 aSubSubGroup->CloseOnDisk();
5581 // close SUB-MESH hdf group
5582 aSubGroup->CloseOnDisk();
5585 // close SUB-MESHES containers hdf group
5586 aGroup->CloseOnDisk();
5590 // try to get GROUPS
5591 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5592 char name_group[ 30 ];
5593 if ( ii == GetNodeGroupsTag() )
5594 strcpy( name_group, "Groups of Nodes" );
5595 else if ( ii == GetEdgeGroupsTag() )
5596 strcpy( name_group, "Groups of Edges" );
5597 else if ( ii == GetFaceGroupsTag() )
5598 strcpy( name_group, "Groups of Faces" );
5599 else if ( ii == GetVolumeGroupsTag() )
5600 strcpy( name_group, "Groups of Volumes" );
5601 else if ( ii == Get0DElementsGroupsTag() )
5602 strcpy( name_group, "Groups of 0D Elements" );
5603 else if ( ii == GetBallElementsGroupsTag() )
5604 strcpy( name_group, "Groups of Balls" );
5606 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5607 aGroup = new HDFgroup( name_group, aTopGroup );
5608 aGroup->OpenOnDisk();
5609 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5610 // within aGroup->ExistInternalObject( name )
5611 std::vector< std::string > subNames;
5612 TColStd_MapOfAsciiString mapOfNames;
5613 aGroup->GetAllObjects( subNames );
5614 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5615 mapOfNames.Add( subNames[ iN ].c_str() );
5617 for ( size_t j = 0; j < subNames.size(); j++ ) {
5618 const std::string& name_dataset = subNames[ j ];
5619 // check if it is a group
5620 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5622 int subid = atoi( name_dataset.substr( 5 ).c_str() );
5625 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5626 aDataset->OpenOnDisk();
5628 // Retrieve actual group name
5629 size = aDataset->GetSize();
5630 char* nameFromFile = new char[ size ];
5631 aDataset->ReadFromDisk( nameFromFile );
5632 aDataset->CloseOnDisk();
5634 // Try to find a shape reference
5635 TopoDS_Shape aShape;
5636 char aRefName[ 30 ];
5637 sprintf( aRefName, "Ref on shape %d", subid);
5638 if ( mapOfNames.Contains( aRefName ))
5640 // load mesh "Ref on shape" - it's an entry to SObject
5641 aDataset = new HDFdataset( aRefName, aGroup );
5642 aDataset->OpenOnDisk();
5643 size = aDataset->GetSize();
5644 char* refFromFile = new char[ size ];
5645 aDataset->ReadFromDisk( refFromFile );
5646 aDataset->CloseOnDisk();
5647 if ( strlen( refFromFile ) > 0 ) {
5648 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5649 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5650 if ( !CORBA::is_nil( shapeObject ) ) {
5651 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5652 if ( !aShapeObject->_is_nil() )
5653 aShape = GeomObjectToShape( aShapeObject );
5656 delete [] refFromFile;
5658 // Try to read a filter of SMESH_GroupOnFilter
5659 SMESH::Filter_var filter;
5660 SMESH_PredicatePtr predicate;
5661 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5662 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5664 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5665 aDataset->OpenOnDisk();
5666 size = aDataset->GetSize();
5667 char* persistStr = new char[ size ];
5668 aDataset->ReadFromDisk( persistStr );
5669 aDataset->CloseOnDisk();
5670 if ( strlen( persistStr ) > 0 ) {
5671 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5672 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5673 filters.push_back( filter );
5675 delete [] persistStr;
5678 // Create group servant
5679 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5680 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5681 ( myNewMeshImpl->createGroup( type, nameFromFile, aShape, predicate ) );
5682 delete [] nameFromFile;
5683 // Obtain a SMESHDS_Group object
5684 if ( aNewGroup->_is_nil() )
5687 string iorSubString = GetORB()->object_to_string( aNewGroup );
5688 int newSubId = myStudyContext->findId( iorSubString );
5689 myStudyContext->mapOldToNew( subid, newSubId );
5691 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5695 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5696 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5698 aFilterGroup->SetFilter( filter );
5699 filter->UnRegister();
5701 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5702 if ( !aGroupBaseDS )
5705 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5708 // Read color of the group
5709 char aGroupColorName[ 30 ];
5710 sprintf( aGroupColorName, "ColorGroup %d", subid);
5711 if ( mapOfNames.Contains( aGroupColorName ))
5713 aDataset = new HDFdataset( aGroupColorName, aGroup );
5714 aDataset->OpenOnDisk();
5715 size = aDataset->GetSize();
5716 double* anRGB = new double[ size ];
5717 aDataset->ReadFromDisk( anRGB );
5718 aDataset->CloseOnDisk();
5719 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5720 aGroupBaseDS->SetColor( aColor );
5725 aGroup->CloseOnDisk();
5729 // instead of reading mesh data, we read only brief information of all
5730 // objects: mesh, groups, sub-meshes (issue 0021208 )
5733 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, id,
5734 meshfile.ToCString(), filename.ToCString(),
5738 // read Sub-Mesh ORDER if any
5739 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5740 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5741 aDataset->OpenOnDisk();
5742 size = aDataset->GetSize();
5743 int* smIDs = new int[ size ];
5744 aDataset->ReadFromDisk( smIDs );
5745 aDataset->CloseOnDisk();
5746 TListOfListOfInt anOrderIds;
5747 anOrderIds.push_back( TListOfInt() );
5748 for ( int i = 0; i < size; i++ )
5749 if ( smIDs[ i ] < 0 ) // is separator
5750 anOrderIds.push_back( TListOfInt() );
5752 anOrderIds.back().push_back(smIDs[ i ]);
5754 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5759 // update hyps needing full mesh data restored (issue 20918)
5760 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5762 SMESH_Hypothesis_i* hyp = hyp_data->first;
5763 hyp->UpdateAsMeshesRestored();
5766 // notify algos on completed restoration to set sub-mesh event listeners
5767 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5769 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5770 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5772 TopoDS_Shape myLocShape;
5773 if(myLocMesh.HasShapeToMesh())
5774 myLocShape = myLocMesh.GetShapeToMesh();
5776 myLocShape = SMESH_Mesh::PseudoShape();
5778 myLocMesh.GetSubMesh(myLocShape)->
5779 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5782 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5783 list< SMESH::Filter_var >::iterator f = filters.begin();
5784 for ( ; f != filters.end(); ++f )
5785 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5786 fi->FindBaseObjects();
5791 aTopGroup->CloseOnDisk();
5794 aFile->CloseOnDisk();
5797 // Remove temporary files created from the stream
5800 SMESH_File meshFile( meshfile.ToCString() );
5801 if ( !meshFile ) // no meshfile exists
5803 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5807 Engines::Container_var container = GetContainerRef();
5808 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5810 container_i->registerTemporaryFile( filename.ToCString() );
5811 container_i->registerTemporaryFile( meshfile.ToCString() );
5812 container_i->registerTemporaryFile( tmpDir.ToCString() );
5816 pd << ""; // prevent optimizing pd out
5818 // creation of tree nodes for all data objects in the study
5819 // to support tree representation customization and drag-n-drop:
5820 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
5821 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5822 useCaseBuilder->SetRootCurrent();
5823 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
5824 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
5825 for (it->InitEx(true); it->More(); it->Next()) {
5826 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
5833 //=============================================================================
5835 * SMESH_Gen_i::LoadASCII
5837 * Load SMESH module's data in ASCII format
5839 //=============================================================================
5841 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
5842 const SALOMEDS::TMPFile& theStream,
5844 bool isMultiFile ) {
5845 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
5846 return Load( theComponent, theStream, theURL, isMultiFile );
5848 //before call main ::Load method it's need for decipher text format to
5849 //binary ( "|xx" => x' )
5850 int size = theStream.length();
5851 if ( int((size / 3 )*3) != size ) //error size of buffer
5854 int real_size = int(size / 3);
5856 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
5859 unsigned int c = -1;
5860 for ( int i = 0; i < real_size; i++ )
5862 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
5863 sscanf( tmp, "%x", &c );
5864 sprintf( (char*)&(buffer[i]), "%c", (char)c );
5867 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
5869 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
5872 //=============================================================================
5874 * SMESH_Gen_i::Close
5876 * Clears study-connected data when it is closed
5878 //=============================================================================
5880 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
5882 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
5884 // Clear study contexts data
5885 myStudyContext->Clear();
5887 // remove the tmp files meshes are loaded from
5888 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
5890 // Clean trace of API methods calls
5896 //=============================================================================
5898 * SMESH_Gen_i::ComponentDataType
5900 * Get component data type
5902 //=============================================================================
5904 char* SMESH_Gen_i::ComponentDataType()
5906 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
5907 return CORBA::string_dup( "SMESH" );
5911 //=============================================================================
5913 * SMESH_Gen_i::IORToLocalPersistentID
5915 * Transform data from transient form to persistent
5917 //=============================================================================
5919 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
5920 const char* IORString,
5921 CORBA::Boolean /*isMultiFile*/,
5922 CORBA::Boolean /*isASCII*/ )
5924 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
5926 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
5927 int anId = myStudyContext->findId( IORString );
5929 if(MYDEBUG) MESSAGE( "VSR " << anId )
5931 sprintf( strId, "%d", anId );
5932 return CORBA::string_dup( strId );
5935 return CORBA::string_dup( "" );
5938 //=============================================================================
5940 * SMESH_Gen_i::LocalPersistentIDToIOR
5942 * Transform data from persistent form to transient
5944 //=============================================================================
5946 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
5947 const char* aLocalPersistentID,
5948 CORBA::Boolean /*isMultiFile*/,
5949 CORBA::Boolean /*isASCII*/ )
5951 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
5953 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
5954 int anId = atoi( aLocalPersistentID );
5955 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
5957 return CORBA::string_dup( "" );
5960 //=======================================================================
5961 //function : RegisterObject
5963 //=======================================================================
5965 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
5967 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5968 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
5969 return myStudyContext->addObject( string( iorString.in() ) );
5974 //================================================================================
5976 * \brief Return id of registered object
5977 * \param theObject - the Object
5978 * \retval int - Object id
5980 //================================================================================
5982 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
5984 if ( myStudyContext && !CORBA::is_nil( theObject )) {
5985 string iorString = GetORB()->object_to_string( theObject );
5986 return myStudyContext->findId( iorString );
5991 //=============================================================================
5993 * SMESH_Gen_i::SetName
5995 * Set a new object name
5997 //=============================================================================
5998 void SMESH_Gen_i::SetName(const char* theIOR,
5999 const char* theName)
6001 if ( theIOR && strcmp( theIOR, "" ) ) {
6002 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6003 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6004 if ( !aSO->_is_nil() ) {
6005 SetName( aSO, theName );
6010 // Version information
6011 char* SMESH_Gen_i::getVersion()
6013 #if SMESH_DEVELOPMENT
6014 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6016 return CORBA::string_dup(SMESH_VERSION_STR);
6020 //=================================================================================
6021 // function : Move()
6022 // purpose : Moves objects to the specified position.
6023 // Is used in the drag-n-drop functionality.
6024 //=================================================================================
6025 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6026 SALOMEDS::SObject_ptr where,
6029 if ( CORBA::is_nil( where ) ) return;
6031 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6032 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6033 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6034 std::string dataType = father->ComponentDataType();
6035 if ( dataType != "SMESH" ) return; // not a SMESH component
6037 SALOMEDS::SObject_var objAfter;
6038 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6039 // insert at given row -> find insertion position
6040 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6042 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6043 if ( i == row && useCaseIt->More() ) {
6044 objAfter = useCaseIt->Value();
6048 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6049 SALOMEDS::SObject_var sobj = what[i];
6050 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6051 // insert the object to the use case tree
6052 if ( !CORBA::is_nil( objAfter ) )
6053 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6055 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6058 //================================================================================
6060 * \brief Returns true if algorithm can be used to mesh a given geometry
6061 * \param [in] theAlgoType - the algorithm type
6062 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6063 * \param [in] theGeomObject - the geometry to mesh
6064 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6065 * else, returns \c True if at least one shape is meshable
6066 * \return CORBA::Boolean - can or can't
6068 //================================================================================
6070 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6071 const char* theLibName,
6072 GEOM::GEOM_Object_ptr theGeomObject,
6073 CORBA::Boolean toCheckAll)
6077 std::string aPlatformLibName;
6078 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6079 GenericHypothesisCreator_i* aCreator =
6080 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6083 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6084 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll );
6091 SMESH_CATCH( SMESH::doNothing );
6094 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6099 //=================================================================================
6100 // function : GetInsideSphere
6101 // purpose : Collect indices of elements, which are located inside the sphere
6102 //=================================================================================
6103 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6104 SMESH::ElementType theElemType,
6110 SMESH::long_array_var aResult = new SMESH::long_array();
6111 if ( meshPart->_is_nil() )
6112 return aResult._retn();
6114 // 1. Create geometrical object
6115 gp_Pnt aP( theX, theY, theZ );
6116 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6118 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6120 if ( lst.size() > 0 ) {
6121 aResult->length( lst.size() );
6122 for ( size_t i = 0; i < lst.size(); i++ ) {
6123 aResult[i] = lst[i];
6126 return aResult._retn();
6129 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6130 SMESH::ElementType theElemType,
6131 CORBA::Double theX1,
6132 CORBA::Double theY1,
6133 CORBA::Double theZ1,
6134 CORBA::Double theX2,
6135 CORBA::Double theY2,
6136 CORBA::Double theZ2) {
6137 SMESH::long_array_var aResult = new SMESH::long_array();
6138 if( meshPart->_is_nil() )
6139 return aResult._retn();
6141 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6143 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6145 if( lst.size() > 0 ) {
6146 aResult->length( lst.size() );
6147 for ( size_t i = 0; i < lst.size(); i++ ) {
6148 aResult[i] = lst[i];
6151 return aResult._retn();
6154 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6155 SMESH::ElementType theElemType,
6159 CORBA::Double theDX,
6160 CORBA::Double theDY,
6161 CORBA::Double theDZ,
6163 CORBA::Double theR ){
6164 SMESH::long_array_var aResult = new SMESH::long_array();
6165 if( meshPart->_is_nil() )
6166 return aResult._retn();
6168 gp_Pnt aP( theX, theY, theZ );
6169 gp_Vec aV( theDX, theDY, theDZ );
6170 gp_Ax2 anAxes (aP, aV);
6172 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6174 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6176 if( lst.size() > 0 ) {
6177 aResult->length( lst.size() );
6178 for ( size_t i = 0; i < lst.size(); i++ ) {
6179 aResult[i] = lst[i];
6182 return aResult._retn();
6185 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6186 SMESH::ElementType theElemType,
6187 GEOM::GEOM_Object_ptr theGeom,
6188 CORBA::Double theTolerance ) {
6189 SMESH::long_array_var aResult = new SMESH::long_array();
6190 if( meshPart->_is_nil() || theGeom->_is_nil() )
6191 return aResult._retn();
6193 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6195 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6197 if( lst.size() > 0 ) {
6198 aResult->length( lst.size() );
6199 for ( size_t i = 0; i < lst.size(); i++ ) {
6200 aResult[i] = lst[i];
6203 return aResult._retn();
6208 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6209 SMESH::ElementType theElemType,
6210 TopoDS_Shape& aShape,
6211 double* theTolerance) {
6213 std::vector<long> res;
6214 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6216 if ( mesh->_is_nil() )
6219 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6223 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6228 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6229 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6230 anElementsOnShape->SetAllNodes( true );
6231 anElementsOnShape->SetMesh( meshDS );
6232 anElementsOnShape->SetShape( aShape, aType );
6235 anElementsOnShape->SetTolerance(*theTolerance);
6237 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6238 if ( !msource->_is_nil() ) { // Mesh case
6239 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6241 while ( elemIt->more() ) {
6242 const SMDS_MeshElement* anElem = elemIt->next();
6243 long anId = anElem->GetID();
6244 if ( anElementsOnShape->IsSatisfy( anId ) )
6245 res.push_back( anId );
6249 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6250 if ( !gsource->_is_nil() ) {
6251 if(theElemType == SMESH::NODE) {
6252 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6253 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6254 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6255 long anId = node->GetID();
6256 if ( anElementsOnShape->IsSatisfy( anId ) )
6257 res.push_back( anId );
6260 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6261 SMESH::long_array_var elems = gsource->GetListOfID();
6262 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6263 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6264 long anId = elem->GetID();
6265 if ( anElementsOnShape->IsSatisfy( anId ) )
6266 res.push_back( anId );
6271 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6272 if ( !smsource->_is_nil() ) {
6273 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6274 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6275 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6277 long anId = elem->GetID();
6278 if ( anElementsOnShape->IsSatisfy( anId ) )
6279 res.push_back( anId );
6287 //=============================================================================
6289 * SMESHEngine_factory
6291 * C factory, accessible with dlsym, after dlopen
6293 //=============================================================================
6297 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6298 PortableServer::POA_ptr poa,
6299 PortableServer::ObjectId* contId,
6300 const char* instanceName,
6301 const char* interfaceName )
6303 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6304 if(MYDEBUG) SCRUTE(interfaceName);
6305 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6306 return aSMESHGen->getId() ;