1 // Copyright (C) 2007-2020 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>
147 #include <boost/archive/text_oarchive.hpp>
148 #include <boost/archive/text_iarchive.hpp>
149 #include <boost/serialization/list.hpp>
150 #include <boost/serialization/string.hpp>
153 using SMESH::TPythonDump;
156 #define NUM_TMP_FILES 2
159 static int MYDEBUG = 0;
161 static int MYDEBUG = 0;
164 // Static variables definition
165 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
166 CORBA::ORB_var SMESH_Gen_i::myOrb;
167 PortableServer::POA_var SMESH_Gen_i::myPoa;
168 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
169 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
170 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
173 const int nbElemPerDiagonal = 10;
175 //=============================================================================
177 * GetServant [ static ]
179 * Get servant of the CORBA object
181 //=============================================================================
183 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
185 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
188 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
191 catch (PortableServer::POA::ObjectNotActive &ex)
193 INFOS("GetServant: ObjectNotActive");
196 catch (PortableServer::POA::WrongAdapter &ex)
198 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
201 catch (PortableServer::POA::WrongPolicy &ex)
203 INFOS("GetServant: WrongPolicy");
208 INFOS( "GetServant - Unknown exception was caught!!!" );
213 //=============================================================================
215 * SObjectToObject [ static ]
217 * Get CORBA object corresponding to the SALOMEDS::SObject
219 //=============================================================================
221 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
223 SALOMEDS::GenericAttribute_wrap anAttr;
224 CORBA::Object_var anObj;
225 if ( !theSObject->_is_nil() ) {
227 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
228 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
229 CORBA::String_var aValue = anIOR->Value();
230 if( strcmp( aValue, "" ) != 0 )
231 anObj = GetORB()->string_to_object( aValue );
235 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
241 //=============================================================================
245 * Get SALOME_NamingService object
247 //=============================================================================
249 SALOME_NamingService* SMESH_Gen_i::GetNS()
251 if ( myNS == NULL ) {
252 myNS = SINGLETON_<SALOME_NamingService>::Instance();
253 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
254 myNS->init_orb( GetORB() );
259 //=============================================================================
263 * Get SALOME_LifeCycleCORBA object
265 //=============================================================================
267 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
269 if ( myLCC == NULL ) {
270 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
275 //=============================================================================
277 * GetGeomEngine [ static ]
279 * Get GEOM::GEOM_Gen reference
281 //=============================================================================
283 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( bool isShaper )
285 Engines::EngineComponent_ptr temp =
286 GetLCC()->FindOrLoad_Component( isShaper ? "FactoryServer" : "FactoryServer",
287 isShaper ? "SHAPERSTUDY" : "GEOM" );
288 myGeomGen = GEOM::GEOM_Gen::_narrow( temp );
293 //=============================================================================
295 * GetGeomEngine [ static ]
297 * Get GEOM::GEOM_Gen reference
299 //=============================================================================
301 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
303 GEOM::GEOM_Gen_ptr gen = GEOM::GEOM_Gen::_nil();
304 if ( !CORBA::is_nil( go ))
309 //=============================================================================
311 * SMESH_Gen_i::SMESH_Gen_i
313 * Default constructor: not for use
315 //=============================================================================
317 SMESH_Gen_i::SMESH_Gen_i()
321 //=============================================================================
323 * SMESH_Gen_i::SMESH_Gen_i
325 * Standard constructor, used with Container
327 //=============================================================================
329 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
330 PortableServer::POA_ptr poa,
331 PortableServer::ObjectId* contId,
332 const char* instanceName,
333 const char* interfaceName )
334 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
337 myOrb = CORBA::ORB::_duplicate(orb);
338 myPoa = PortableServer::POA::_duplicate(poa);
341 _id = myPoa->activate_object( _thisObj );
343 myStudyContext = new StudyContext;
345 myIsEmbeddedMode = false;
346 myIsEnablePublish = true;
347 myShapeReader = NULL; // shape reader
349 myIsHistoricalPythonDump = true;
350 myToForgetMeshDataOnHypModif = false;
352 // set it in standalone mode only
353 //OSD::SetSignal( true );
355 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
356 // find out mode (embedded or standalone) here else
357 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
358 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
359 if ( SALOME_NamingService* ns = GetNS() )
361 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
362 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
363 if ( !session->_is_nil() )
365 CORBA::String_var str_host = session->getHostname();
366 CORBA::Long s_pid = session->getPID();
367 string my_host = Kernel_Utils::GetHostname();
369 long my_pid = (long)_getpid();
371 long my_pid = (long) getpid();
373 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
378 //=============================================================================
380 * SMESH_Gen_i::~SMESH_Gen_i
384 //=============================================================================
386 SMESH_Gen_i::~SMESH_Gen_i()
388 // delete hypothesis creators
389 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
390 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
392 // same creator can be mapped under different names
393 GenericHypothesisCreator_i* creator = (*itHyp).second;
397 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
398 if ( creator == (*itHyp2).second )
399 (*itHyp2).second = 0;
401 myHypCreatorMap.clear();
403 // Clear study contexts data
404 delete myStudyContext;
406 // delete shape reader
408 delete myShapeReader;
411 //=============================================================================
413 * SMESH_Gen_i::getHypothesisCreator
415 * Get hypothesis creator
417 //=============================================================================
419 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
420 const char* theLibName,
421 std::string& thePlatformLibName)
423 std::string aPlatformLibName;
424 /* It's Need to translate lib name for WIN32 or X platform */
425 if ( theLibName && theLibName[0] != '\0' )
427 int libNameLen = strlen(theLibName);
428 //check for old format "libXXXXXXX.so"
429 if (libNameLen > 7 &&
430 !strncmp( theLibName, "lib", 3 ) &&
431 !strcmp( theLibName+libNameLen-3, ".so" ))
435 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
436 #elif defined(__APPLE__)
437 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
439 aPlatformLibName = theLibName;
444 //try to use new format
446 aPlatformLibName = theLibName;
447 aPlatformLibName += ".dll";
448 #elif defined(__APPLE__)
449 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
451 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
455 thePlatformLibName = aPlatformLibName;
457 Unexpect aCatch(SALOME_SalomeException);
458 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
460 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
461 GenericHypothesisCreator_i* aCreator;
464 // check, if creator for this hypothesis type already exists
465 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
467 // load plugin library
468 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
471 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
473 const char* path = aPlatformLibName.c_str();
476 const char* path = aPlatformLibName.c_str();
478 LibHandle libHandle = LoadLib( path );
479 #if defined(WIN32) && defined(UNICODE)
484 // report any error, if occurred
486 const char* anError = dlerror();
487 throw(SALOME_Exception( anError ));
489 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
490 << aPlatformLibName));
494 // get method, returning hypothesis creator
495 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
496 GetHypothesisCreator procHandle =
497 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
500 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
501 << aPlatformLibName ));
502 UnLoadLib(libHandle);
505 // get hypothesis creator
506 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
507 aCreator = procHandle(theHypName);
510 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
511 << aPlatformLibName));
513 // map hypothesis creator to a hypothesis name
514 myHypCreatorMap[string(theHypName)] = aCreator;
519 return myHypCreatorMap[string(theHypName)];
522 catch (SALOME_Exception& S_ex)
524 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
529 //=============================================================================
531 * SMESH_Gen_i::createHypothesis
533 * Create hypothesis of given type
535 //=============================================================================
537 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
538 const char* theLibName)
540 SMESH_Hypothesis_i* myHypothesis_i = 0;
541 SMESH::SMESH_Hypothesis_var hypothesis_i;
542 std::string aPlatformLibName;
543 GenericHypothesisCreator_i* aCreator =
544 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
546 // create a new hypothesis object, store its ref. in studyContext
547 myHypothesis_i = aCreator->Create(myPoa, &myGen);
550 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
551 CORBA::String_var hypName = myHypothesis_i->GetName();
552 myHypCreatorMap[ hypName.in() ] = aCreator;
554 // activate the CORBA servant of hypothesis
555 hypothesis_i = myHypothesis_i->_this();
556 int nextId = RegisterObject( hypothesis_i );
557 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
558 else { (void)nextId; } // avoid "unused variable" warning in release mode
560 return hypothesis_i._retn();
563 //=============================================================================
565 * SMESH_Gen_i::createMesh
567 * Create empty mesh on shape
569 //=============================================================================
571 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
573 Unexpect aCatch(SALOME_SalomeException);
574 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
576 // Get or create the GEOM_Client instance
578 // create a new mesh object servant, store it in a map in study context
579 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
580 // create a new mesh object
581 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
582 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
584 // activate the CORBA servant of Mesh
585 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
586 int nextId = RegisterObject( mesh );
587 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
588 else { (void)nextId; } // avoid "unused variable" warning in release mode
591 catch (SALOME_Exception& S_ex) {
592 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
594 return SMESH::SMESH_Mesh::_nil();
597 //=============================================================================
599 * SMESH_Gen_i::GetShapeReader
603 //=============================================================================
605 GEOM_Client* SMESH_Gen_i::GetShapeReader()
607 // create shape reader if necessary
608 if ( !myShapeReader )
609 myShapeReader = new GEOM_Client(GetContainerRef());
610 ASSERT( myShapeReader );
611 return myShapeReader;
614 //=============================================================================
616 * SMESH_Gen_i::SetGeomEngine
618 * Set GEOM::GEOM_Gen reference
620 //=============================================================================
622 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
624 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
627 //=============================================================================
629 * SMESH_Gen_i::SetEmbeddedMode
633 //=============================================================================
635 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
637 myIsEmbeddedMode = theMode;
639 if ( !myIsEmbeddedMode ) {
640 //PAL10867: disable signals catching with "noexcepthandler" option
641 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
642 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
647 char* envDisableFPE = getenv("DISABLE_FPE");
648 if (envDisableFPE && atoi(envDisableFPE))
653 OSD::SetSignal( raiseFPE );
655 // else OSD::SetSignal() is called in GUI
659 //=============================================================================
661 * SMESH_Gen_i::IsEmbeddedMode
665 //=============================================================================
667 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
669 return myIsEmbeddedMode;
672 //=============================================================================
674 * SMESH_Gen_i::SetEnablePublish
676 * Set enable publishing in the study
678 //=============================================================================
680 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
682 myIsEnablePublish = theIsEnablePublish;
685 //=============================================================================
687 * SMESH_Gen_i::IsEnablePublish
689 * Check enable publishing
691 //=============================================================================
693 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
695 return myIsEnablePublish;
698 //=============================================================================
700 * SMESH_Gen_i::UpdateStudy
702 * Update study (needed at switching GEOM->SMESH)
704 //=============================================================================
706 void SMESH_Gen_i::UpdateStudy()
708 if ( !myStudyContext )
709 myStudyContext = new StudyContext;
711 SALOMEDS::Study_var aStudy = getStudyServant();
712 if ( !CORBA::is_nil( aStudy ) )
714 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
716 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
717 if( !GEOM_var->_is_nil() )
718 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
720 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
721 if( !GEOM_var->_is_nil() )
722 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
724 // NPAL16168, issue 0020210
725 // Let meshes update their data depending on GEOM groups that could change
726 CORBA::String_var compDataType = ComponentDataType();
727 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
728 if ( !me->_is_nil() ) {
729 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
730 for ( ; anIter->More(); anIter->Next() ) {
731 SALOMEDS::SObject_wrap so = anIter->Value();
732 CORBA::Object_var ior = SObjectToObject( so );
733 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
734 mesh->CheckGeomModif();
740 //================================================================================
742 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
744 //================================================================================
746 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
748 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
749 SALOMEDS::GenericAttribute_wrap attr;
750 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
752 SALOMEDS::AttributePixMap_wrap pm = attr;
753 CORBA::String_var ico = pm->GetPixMap();
754 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
759 //=================================================================================
760 // function : hasObjectInfo()
761 // purpose : shows if module provides information for its objects
762 //=================================================================================
764 bool SMESH_Gen_i::hasObjectInfo()
769 //=================================================================================
770 // function : getObjectInfo()
771 // purpose : returns an information for a given object by its entry
772 //=================================================================================
774 char* SMESH_Gen_i::getObjectInfo( const char* entry )
776 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
777 // for the rest, "module 'SMESH', ID=0:1:2:*"
781 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
782 CORBA::Object_var obj = SObjectToObject( so );
783 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
784 if ( isGeomModifIcon( mesh ))
786 txt << "The geometry was changed and the mesh needs to be recomputed";
791 CORBA::String_var compType = ComponentDataType();
792 txt << "module '" << compType << "', ID=" << entry;
794 return CORBA::string_dup( txt );
797 //=============================================================================
799 * SMESH_Gen_i::GetStudyContext
803 //=============================================================================
805 StudyContext* SMESH_Gen_i::GetStudyContext()
807 return myStudyContext;
810 //=============================================================================
812 * SMESH_Gen_i::CreateHypothesis
814 * Create hypothesis/algorithm of given type and publish it in the study
816 //=============================================================================
818 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
819 const char* theLibName )
821 Unexpect aCatch(SALOME_SalomeException);
822 // Create hypothesis/algorithm
823 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
825 // Publish hypothesis/algorithm in the study
826 if ( CanPublishInStudy( hyp ) ) {
827 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
828 if ( !aSO->_is_nil() ) {
829 // Update Python script
830 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
831 << theHypName << "', '" << theLibName << "')";
838 //================================================================================
840 * \brief Return a hypothesis initialized by given average length.
841 * \param theHypType - hypothesis type name
842 * \param theLibName - plugin library name
843 * \param theAverageLength - average length
844 * \param theQuadDominated - is quad-dominated flag
845 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
847 //================================================================================
849 SMESH::SMESH_Hypothesis_ptr
850 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
851 const char* theLibName,
852 CORBA::Double theAverageLength,
853 CORBA::Boolean theQuadDominated)
855 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
856 theAverageLength, theQuadDominated };
858 SMESH::SMESH_Hypothesis_var hyp =
859 GetHypothesisParameterValues( theHypType, theLibName,
860 SMESH::SMESH_Mesh::_nil(),
861 GEOM::GEOM_Object::_nil(),
863 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
865 TPythonDump() << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
866 << theHypType << "', '"
867 << theLibName << "', "
868 << theAverageLength << ", "
869 << theQuadDominated << " )";
874 //================================================================================
876 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
877 * existing on the given geometry or to size of the geometry.
878 * \param theHypType - hypothesis type name
879 * \param theLibName - plugin library name
880 * \param theMesh - The mesh of interest
881 * \param theGeom - The shape to get parameter values from
882 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
883 * in a study and used to compute the mesh, or a temporary one created just to pass
886 //================================================================================
888 SMESH::SMESH_Hypothesis_ptr
889 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
890 const char* theLibName,
891 SMESH::SMESH_Mesh_ptr theMesh,
892 GEOM::GEOM_Object_ptr theGeom,
893 const SMESH::HypInitParams& theParams)
895 Unexpect aCatch(SALOME_SalomeException);
897 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
898 if ( byMesh && CORBA::is_nil( theMesh ) )
899 return SMESH::SMESH_Hypothesis::_nil();
900 if ( byMesh && CORBA::is_nil( theGeom ) )
901 return SMESH::SMESH_Hypothesis::_nil();
903 // -----------------------------------------------
904 // find hypothesis used to mesh theGeom
905 // -----------------------------------------------
907 // get mesh and shape
908 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
909 TopoDS_Shape shape = GeomObjectToShape( theGeom );
910 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
911 return SMESH::SMESH_Hypothesis::_nil();
912 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
914 // create a temporary hypothesis to know its dimension
915 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
916 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
918 return SMESH::SMESH_Hypothesis::_nil();
919 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
922 // look for a hypothesis of theHypType used to mesh the shape
923 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
926 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
927 int nbLocalHyps = aHypList->length();
928 for ( int i = 0; i < nbLocalHyps; i++ ) {
929 CORBA::String_var hypName = aHypList[i]->GetName();
930 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
931 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
933 // check super shapes
934 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
935 while ( nbLocalHyps == 0 && itShape.More() ) {
936 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
937 if ( ! CORBA::is_nil( geomObj )) {
938 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
939 nbLocalHyps = aHypList->length();
940 for ( int i = 0; i < nbLocalHyps; i++ )
941 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
942 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
948 // let the temporary hypothesis find out somehow parameter values by mesh
949 if ( hyp->SetParametersByMesh( mesh, shape ))
950 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
954 ::SMESH_Hypothesis::TDefaults dflts;
955 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
956 dflts._nbSegments = myGen.GetDefaultNbSegments();
957 dflts._elemLength = theParams.averageLength;
958 dflts._quadDominated = theParams.quadDominated;
959 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
962 dflts._diagonal = mesh->GetShapeDiagonalSize();
964 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
965 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
966 dflts._shape = &shape;
969 // let the hypothesis initialize it's values
970 if ( hyp->SetParametersByDefaults( dflts, mesh ))
971 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
974 return SMESH::SMESH_Hypothesis::_nil();
977 //=============================================================================
979 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
980 * \param [in] theHyp - the hypothesis of interest
981 * \param [out] theMesh - the sole mesh using \a theHyp
982 * \param [out] theShape - the sole geometry \a theHyp is assigned to
983 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
985 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
986 * considered as SAME sub-mesh => result is \c true.
987 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
988 * a shape to which an hyp being edited is assigned.
990 //=============================================================================
992 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
993 SMESH::SMESH_Mesh_out theMesh,
994 GEOM::GEOM_Object_out theShape)
996 if ( CORBA::is_nil( theHyp ))
999 // get Mesh component SO
1000 CORBA::String_var compDataType = ComponentDataType();
1001 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
1002 if ( CORBA::is_nil( comp ))
1005 // look for child SO of meshes
1006 SMESH::SMESH_Mesh_var foundMesh;
1007 TopoDS_Shape foundShape;
1009 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1010 for ( ; meshIter->More() && isSole; meshIter->Next() )
1012 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1013 CORBA::Object_var obj = SObjectToObject( curSO );
1014 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1018 // look for a sole shape where theHyp is assigned
1019 bool isHypFound = false;
1020 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1021 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1022 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1024 const THypList& hyps = s2hypsIt.Value();
1025 THypList::const_iterator h = hyps.begin();
1026 for ( ; h != hyps.end(); ++h )
1027 if ( (*h)->GetID() == theHyp->GetId() )
1029 if ( h != hyps.end()) // theHyp found
1032 if ( ! foundShape.IsNull() &&
1033 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1035 foundShape.Nullify();
1039 foundShape = s2hypsIt.Key();
1041 } // loop on assigned hyps
1043 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1045 if ( !foundMesh->_is_nil() ) // not a sole mesh
1047 if ( !foundMesh->HasShapeToMesh() ||
1048 !mesh_i ->HasShapeToMesh() )
1050 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1054 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1055 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1056 isSole = s1->IsSame( s2 );
1059 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1065 ! foundMesh->_is_nil() &&
1066 ! foundShape.IsNull() )
1068 theMesh = foundMesh._retn();
1069 theShape = ShapeToGeomObject( foundShape );
1070 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1075 //=============================================================================
1077 * Set number of segments per diagonal of boundary box of geometry by which
1078 * default segment length of appropriate 1D hypotheses is defined
1080 //=============================================================================
1082 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1084 if ( theNbSegments > 0 )
1085 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1087 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1090 //=============================================================================
1092 * \brief Set default number of segments per edge
1094 //=============================================================================
1096 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1098 if ( theNbSegments > 0 )
1099 myGen.SetDefaultNbSegments( int(theNbSegments) );
1101 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1104 //=============================================================================
1106 * Set an option value
1108 //=============================================================================
1110 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1112 if ( name && value && strlen( value ) > 0 )
1115 if ( strcmp(name, "historical_python_dump") == 0 )
1117 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1118 msgToGUI = "preferences/SMESH/historical_python_dump/";
1119 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1121 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1123 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1124 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1125 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1127 else if ( strcmp(name, "default_grp_color") == 0 )
1131 // color must be presented as a string of following form:
1132 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1133 str = str.substr(1);
1134 for ( size_t i = 0; i < str.length()/2; i++ )
1135 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1136 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1138 else if ( value ) { // rgb color ("255,170,0", for example)
1139 string tempValue( value );
1140 char* colorValue = strtok( &tempValue[0], "," );
1141 while ( colorValue != NULL ) {
1142 int c_value = atoi( colorValue );
1143 if ( c_value >= 0 && c_value <= 255 )
1144 color.push_back( c_value );
1145 colorValue = strtok( NULL, "," );
1148 if ( color.size() == 3 ) { // color must have three valid component
1149 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1150 myDefaultGroupColor = value;
1151 msgToGUI = "preferences/SMESH/default_grp_color/";
1156 // update preferences in case if SetOption() is invoked from python console
1157 if ( !msgToGUI.empty() )
1159 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1160 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1161 if ( !CORBA::is_nil( session ) )
1162 session->emitMessageOneWay(msgToGUI.c_str());
1167 //=============================================================================
1169 * Return an option value
1171 //=============================================================================
1173 char* SMESH_Gen_i::GetOption(const char* name)
1177 if ( strcmp(name, "historical_python_dump") == 0 )
1179 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1181 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1183 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1185 if ( strcmp(name, "default_grp_color") == 0 )
1187 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1190 return CORBA::string_dup( "" );
1193 //=============================================================================
1195 * SMESH_Gen_i::CreateMesh
1197 * Create empty mesh on a shape and publish it in the study
1199 //=============================================================================
1201 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1203 Unexpect aCatch(SALOME_SalomeException);
1204 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1206 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1208 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1209 ASSERT( meshServant );
1210 meshServant->SetShape( theShapeObject );
1212 // publish mesh in the study
1213 if ( CanPublishInStudy( mesh ) ) {
1214 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1215 aStudyBuilder->NewCommand(); // There is a transaction
1216 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1217 aStudyBuilder->CommitCommand();
1218 if ( !aSO->_is_nil() ) {
1219 // Update Python script
1220 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1224 return mesh._retn();
1227 //=============================================================================
1229 * SMESH_Gen_i::CreateEmptyMesh
1233 //=============================================================================
1235 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1237 Unexpect aCatch(SALOME_SalomeException);
1238 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1240 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1242 // publish mesh in the study
1243 if ( CanPublishInStudy( mesh ) ) {
1244 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1245 aStudyBuilder->NewCommand(); // There is a transaction
1246 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1247 aStudyBuilder->CommitCommand();
1248 if ( !aSO->_is_nil() ) {
1249 // Update Python script
1250 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1254 return mesh._retn();
1259 //================================================================================
1261 * \brief Throw an exception in case if the file can't be read
1263 //================================================================================
1265 void checkFileReadable( const char* theFileName )
1267 SMESH_File f ( theFileName );
1270 if ( !f.error().empty() )
1271 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1273 THROW_SALOME_CORBA_EXCEPTION
1274 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1275 SALOME::BAD_PARAM );
1280 //=============================================================================
1282 * SMESH_Gen_i::CreateMeshFromUNV
1284 * Create mesh and import data from UNV file
1286 //=============================================================================
1288 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1290 Unexpect aCatch(SALOME_SalomeException);
1292 checkFileReadable( theFileName );
1294 SMESH::SMESH_Mesh_var aMesh = createMesh();
1296 // publish mesh in the study
1297 if ( CanPublishInStudy( aMesh ) ) {
1298 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1299 aStudyBuilder->NewCommand(); // There is a transaction
1300 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1301 aStudyBuilder->CommitCommand();
1302 if ( !aSO->_is_nil() ) {
1303 // Update Python script
1304 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1308 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1310 aServant->ImportUNVFile( theFileName );
1312 // Dump creation of groups
1313 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1315 aServant->GetImpl().GetMeshDS()->Modified();
1316 return aMesh._retn();
1319 //=============================================================================
1321 * SMESH_Gen_i::CreateMeshFromMED
1323 * Create mesh and import data from MED file
1325 //=============================================================================
1327 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1328 SMESH::DriverMED_ReadStatus& theStatus,
1329 const char* theCommandNameForPython,
1330 const char* theFileNameForPython)
1333 char bname[ _MAX_FNAME ];
1334 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1335 string aFileName = bname;
1337 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1339 // Retrieve mesh names from the file
1340 DriverMED_R_SMESHDS_Mesh myReader;
1341 myReader.SetFile( theFileName );
1342 myReader.SetMeshId( -1 );
1343 Driver_Mesh::Status aStatus;
1344 list<string> aNames = myReader.GetMeshNames(aStatus);
1345 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1346 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1348 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1351 TPythonDump aPythonDump;
1352 aPythonDump << "([";
1354 if (theStatus == SMESH::DRS_OK) {
1355 SALOMEDS::StudyBuilder_var aStudyBuilder;
1356 aStudyBuilder = getStudyServant()->NewBuilder();
1357 aStudyBuilder->NewCommand(); // There is a transaction
1359 aResult->length( aNames.size() );
1362 // Iterate through all meshes and create mesh objects
1363 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1366 if (i > 0) aPythonDump << ", ";
1369 SMESH::SMESH_Mesh_var mesh = createMesh();
1371 // publish mesh in the study
1372 SALOMEDS::SObject_wrap aSO;
1373 if ( CanPublishInStudy( mesh ) )
1374 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1375 // - as names of meshes are stored in MED file, we use them for data publishing
1376 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1377 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1380 if ( !aSO->_is_nil() ) {
1383 aPythonDump << "mesh_" << i;
1386 // Read mesh data (groups are published automatically by ImportMEDFile())
1387 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1388 ASSERT( meshServant );
1389 SMESH::DriverMED_ReadStatus status1 =
1390 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1391 if (status1 > theStatus)
1392 theStatus = status1;
1394 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1395 meshServant->GetImpl().GetMeshDS()->Modified();
1397 if ( !aStudyBuilder->_is_nil() )
1398 aStudyBuilder->CommitCommand();
1401 // Update Python script
1402 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1404 // Dump creation of groups
1405 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1406 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1408 return aResult._retn();
1411 //================================================================================
1413 * \brief Create meshes by reading a MED file
1415 //================================================================================
1417 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1418 SMESH::DriverMED_ReadStatus& theStatus)
1420 Unexpect aCatch(SALOME_SalomeException);
1421 checkFileReadable( theFileName );
1423 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus,
1424 "CreateMeshesFromMED", theFileName);
1428 //=============================================================================
1430 * SMESH_Gen_i::CreateMeshFromSAUV
1432 * Create mesh and import data from SAUV file
1434 //=============================================================================
1436 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1437 SMESH::DriverMED_ReadStatus& theStatus)
1439 Unexpect aCatch(SALOME_SalomeException);
1440 checkFileReadable( theFileName );
1442 std::string sauvfilename(theFileName);
1443 std::string medfilename(theFileName);
1444 medfilename += ".med";
1447 cmd = "%PYTHONBIN% ";
1452 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1454 system(cmd.c_str());
1455 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(),
1457 "CreateMeshesFromSAUV",
1458 sauvfilename.c_str());
1460 cmd = "%PYTHONBIN% ";
1465 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1467 system(cmd.c_str());
1471 //=============================================================================
1473 * SMESH_Gen_i::CreateMeshFromSTL
1475 * Create mesh and import data from STL file
1477 //=============================================================================
1479 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1481 Unexpect aCatch(SALOME_SalomeException);
1482 checkFileReadable( theFileName );
1484 SMESH::SMESH_Mesh_var aMesh = createMesh();
1487 char bname[ _MAX_FNAME ];
1488 _splitpath( theFileName, NULL, NULL, bname, NULL );
1489 string aFileName = bname;
1491 string aFileName = basename( const_cast<char *>(theFileName) );
1493 // publish mesh in the study
1494 if ( CanPublishInStudy( aMesh ) ) {
1495 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1496 aStudyBuilder->NewCommand(); // There is a transaction
1497 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1498 aStudyBuilder->CommitCommand();
1499 if ( !aSO->_is_nil() ) {
1500 // Update Python script
1501 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1505 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1507 aServant->ImportSTLFile( theFileName );
1508 aServant->GetImpl().GetMeshDS()->Modified();
1509 return aMesh._retn();
1512 //================================================================================
1514 * \brief Create meshes and import data from the CGSN file
1516 //================================================================================
1518 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1519 SMESH::DriverMED_ReadStatus& theStatus)
1521 Unexpect aCatch(SALOME_SalomeException);
1522 checkFileReadable( theFileName );
1524 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1527 // Retrieve nb meshes from the file
1528 DriverCGNS_Read myReader;
1529 myReader.SetFile( theFileName );
1530 Driver_Mesh::Status aStatus;
1531 int nbMeshes = myReader.GetNbMeshes(aStatus);
1532 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1534 aResult->length( nbMeshes );
1536 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1539 TPythonDump aPythonDump;
1540 aPythonDump << "([";
1542 if (theStatus == SMESH::DRS_OK)
1544 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1545 aStudyBuilder->NewCommand(); // There is a transaction
1549 // Iterate through all meshes and create mesh objects
1550 for ( ; i < nbMeshes; ++i )
1553 if (i > 0) aPythonDump << ", ";
1556 SMESH::SMESH_Mesh_var mesh = createMesh();
1557 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1559 // Read mesh data (groups are published automatically by ImportMEDFile())
1560 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1561 ASSERT( meshServant );
1563 SMESH::DriverMED_ReadStatus status1 =
1564 meshServant->ImportCGNSFile( theFileName, i, meshName );
1565 if (status1 > theStatus)
1566 theStatus = status1;
1568 meshServant->GetImpl().GetMeshDS()->Modified();
1569 // publish mesh in the study
1570 SALOMEDS::SObject_wrap aSO;
1571 if ( CanPublishInStudy( mesh ) )
1572 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1575 if ( !aSO->_is_nil() ) {
1579 aPythonDump << "mesh_" << i;
1582 aStudyBuilder->CommitCommand();
1585 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1587 // Dump creation of groups
1588 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1589 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1591 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1594 return aResult._retn();
1597 //================================================================================
1599 * \brief Create a mesh and import data from a GMF file
1601 //================================================================================
1603 SMESH::SMESH_Mesh_ptr
1604 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1605 CORBA::Boolean theMakeRequiredGroups,
1606 SMESH::ComputeError_out theError)
1608 Unexpect aCatch(SALOME_SalomeException);
1609 checkFileReadable( theFileName );
1611 SMESH::SMESH_Mesh_var aMesh = createMesh();
1613 char bname[ _MAX_FNAME ];
1614 _splitpath( theFileName, NULL, NULL, bname, NULL );
1615 string aFileName = bname;
1617 string aFileName = basename( const_cast<char *>(theFileName) );
1619 // publish mesh in the study
1620 if ( CanPublishInStudy( aMesh ) ) {
1621 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1622 aStudyBuilder->NewCommand(); // There is a transaction
1623 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1624 aStudyBuilder->CommitCommand();
1625 if ( !aSO->_is_nil() ) {
1626 // Update Python script
1627 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1628 << theFileName << "', "
1629 << theMakeRequiredGroups << " )";
1632 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1634 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1635 aServant->GetImpl().GetMeshDS()->Modified();
1636 return aMesh._retn();
1640 //=============================================================================
1642 * SMESH_Gen_i::IsReadyToCompute
1644 * Return true if mesh contains enough data to be computed
1646 //=============================================================================
1648 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1649 GEOM::GEOM_Object_ptr theShapeObject )
1651 Unexpect aCatch(SALOME_SalomeException);
1652 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1654 if ( CORBA::is_nil( theShapeObject ) )
1655 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1656 SALOME::BAD_PARAM );
1657 if ( CORBA::is_nil( theMesh ) )
1658 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1659 SALOME::BAD_PARAM );
1662 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1663 ASSERT( meshServant );
1664 if ( meshServant ) {
1665 // get local TopoDS_Shape
1666 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1667 // call implementation
1668 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1669 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1672 catch ( SALOME_Exception& S_ex ) {
1673 INFOS( "catch exception "<< S_ex.what() );
1678 //================================================================================
1680 * \brief Find SObject for an algo
1682 //================================================================================
1684 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1687 SALOMEDS::Study_var aStudy = getStudyServant();
1688 if ( !aStudy->_is_nil() ) {
1689 // find algo in the study
1690 CORBA::String_var compDataType = ComponentDataType();
1691 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1692 if ( !father->_is_nil() ) {
1693 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1694 for ( ; itBig->More(); itBig->Next() ) {
1695 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1696 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1697 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1698 for ( ; algoIt->More(); algoIt->Next() ) {
1699 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1700 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1701 if ( !CORBA::is_nil( algoIOR )) {
1702 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1703 if ( impl && impl->GetImpl() == algo )
1704 return algoSO._retn();
1706 } // loop on algo SO's
1709 } // SMESH component iterator
1713 return SALOMEDS::SObject::_nil();
1716 //================================================================================
1718 * \brief Return errors of mesh computation
1720 //================================================================================
1722 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1723 GEOM::GEOM_Object_ptr theSubObject )
1725 Unexpect aCatch(SALOME_SalomeException);
1726 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1728 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1729 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1731 if ( CORBA::is_nil( theMesh ) )
1732 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1734 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1736 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1739 if(theMesh->HasShapeToMesh())
1740 shape = GeomObjectToShape( theSubObject );
1742 shape = SMESH_Mesh::PseudoShape();
1744 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1746 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1749 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1750 const bool includeSelf = true, complexShapeFirst = true;
1751 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1753 while ( smIt->more() )
1756 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1758 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1759 if ( error && !error->IsOK() )
1761 if ( !( error->myAlgo ) &&
1762 !( error->myAlgo = sm->GetAlgo() ))
1764 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1765 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1766 errStruct.comment = error->myComment.c_str();
1767 errStruct.subShapeID = sm->GetId();
1768 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1769 if ( !algoSO->_is_nil() ) {
1770 CORBA::String_var algoName = algoSO->GetName();
1771 errStruct.algoName = algoName;
1774 errStruct.algoName = error->myAlgo->GetName();
1776 errStruct.hasBadMesh = error->HasBadElems();
1779 error_array->length( nbErr );
1782 catch ( SALOME_Exception& S_ex ) {
1783 INFOS( "catch exception "<< S_ex.what() );
1786 return error_array._retn();
1789 //================================================================================
1791 * \brief Return mesh elements preventing computation of a subshape
1793 //================================================================================
1795 SMESH::MeshPreviewStruct*
1796 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1797 CORBA::Short theSubShapeID )
1799 Unexpect aCatch(SALOME_SalomeException);
1800 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1802 if ( CORBA::is_nil( theMesh ) )
1803 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1805 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1808 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1810 // mesh implementation
1811 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1812 // submesh by subshape id
1813 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1816 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1817 if ( error && error->HasBadElems() )
1819 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1820 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1822 // get nodes of elements and count elements
1823 TNode2LocalIDMap mapNode2LocalID;
1824 list< TNodeLocalID > connectivity;
1825 int i, nbElements = 0, nbConnNodes = 0;
1827 const list<const SMDS_MeshElement*>& badElems =
1828 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1829 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1830 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1831 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1833 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1834 while ( nIt->more() )
1835 connectivity.push_back
1836 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1838 // fill node coords and assign local ids to the nodes
1839 int nbNodes = mapNode2LocalID.size();
1840 result->nodesXYZ.length( nbNodes );
1841 TNodeLocalID node2ID = mapNode2LocalID.begin();
1842 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1843 node2ID->second = i;
1844 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1845 result->nodesXYZ[i].x = node->X();
1846 result->nodesXYZ[i].y = node->Y();
1847 result->nodesXYZ[i].z = node->Z();
1849 // fill connectivity
1850 result->elementConnectivities.length( nbConnNodes );
1851 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1852 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1853 result->elementConnectivities[i] = (*connIt)->second;
1855 // fill element types
1856 result->elementTypes.length( nbElements );
1857 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1859 const SMDS_MeshElement* elem = *elemIt;
1860 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1861 result->elementTypes[i].isPoly = elem->IsPoly();
1862 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1868 catch ( SALOME_Exception& S_ex ) {
1869 INFOS( "catch exception "<< S_ex.what() );
1872 return result._retn();
1875 //================================================================================
1877 * \brief Create a group of elements preventing computation of a sub-shape
1879 //================================================================================
1881 SMESH::ListOfGroups*
1882 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1883 CORBA::Short theSubShapeID,
1884 const char* theGroupName )
1886 Unexpect aCatch(SALOME_SalomeException);
1888 SMESH::ListOfGroups_var groups;
1890 if ( CORBA::is_nil( theMesh ) )
1891 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1894 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1896 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1897 TPythonDump() << groups << " = " << this
1898 << ".MakeGroupsOfBadInputElements( "
1899 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1902 catch ( SALOME_Exception& S_ex ) {
1903 INFOS( "catch exception "<< S_ex.what() );
1905 return groups._retn();
1908 //================================================================================
1910 * \brief Returns errors of hypotheses definition
1911 * \param theMesh - the mesh
1912 * \param theSubObject - the main or sub- shape
1913 * \retval SMESH::algo_error_array* - sequence of errors
1915 //================================================================================
1917 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1918 GEOM::GEOM_Object_ptr theSubObject )
1920 Unexpect aCatch(SALOME_SalomeException);
1921 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1923 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1924 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1926 if ( CORBA::is_nil( theMesh ) )
1927 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1929 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1931 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1932 ASSERT( meshServant );
1933 if ( meshServant ) {
1934 TopoDS_Shape myLocShape;
1935 if(theMesh->HasShapeToMesh())
1936 myLocShape = GeomObjectToShape( theSubObject );
1938 myLocShape = SMESH_Mesh::PseudoShape();
1940 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1941 list< ::SMESH_Gen::TAlgoStateError > error_list;
1942 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1943 // call ::SMESH_Gen::GetAlgoState()
1944 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1945 error_array->length( error_list.size() );
1947 for ( error = error_list.begin(); error != error_list.end(); ++error )
1949 // fill AlgoStateError structure
1950 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1951 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1952 errStruct.algoDim = error->_algoDim;
1953 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1954 errStruct.algoName = "";
1955 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1956 if ( !algoSO->_is_nil() ) {
1957 CORBA::String_var algoName = algoSO->GetName();
1958 errStruct.algoName = algoName.in();
1963 catch ( SALOME_Exception& S_ex ) {
1964 INFOS( "catch exception "<< S_ex.what() );
1966 return error_array._retn();
1969 //=============================================================================
1971 * SMESH_Gen_i::GetSubShapesId
1973 * Get sub-shapes unique ID's list
1975 //=============================================================================
1978 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1979 const SMESH::object_array& theListOfSubShapeObject )
1981 Unexpect aCatch(SALOME_SalomeException);
1982 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1984 SMESH::long_array_var shapesId = new SMESH::long_array;
1987 if ( CORBA::is_nil( theMainShapeObject ) )
1988 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1992 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1993 TopTools_IndexedMapOfShape myIndexToShape;
1994 TopExp::MapShapes(myMainShape,myIndexToShape);
1996 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1998 GEOM::GEOM_Object_var aShapeObject
1999 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
2000 if ( CORBA::is_nil( aShapeObject ) )
2001 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
2002 SALOME::BAD_PARAM );
2004 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
2005 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
2007 const TopoDS_Face& F = TopoDS::Face(exp.Current());
2008 setId.insert(myIndexToShape.FindIndex(F));
2009 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
2011 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
2013 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
2014 setId.insert(myIndexToShape.FindIndex(E));
2015 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
2017 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
2019 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
2020 setId.insert(myIndexToShape.FindIndex(V));
2021 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
2024 shapesId->length(setId.size());
2025 set<int>::iterator iind;
2027 for (iind = setId.begin(); iind != setId.end(); iind++)
2029 if(MYDEBUG) SCRUTE((*iind));
2030 shapesId[i] = (*iind);
2031 if(MYDEBUG) SCRUTE(shapesId[i]);
2035 catch (SALOME_Exception& S_ex)
2037 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2040 return shapesId._retn();
2043 //=============================================================================
2045 * SMESH_Gen_i::Compute
2047 * Compute mesh on a shape
2049 //=============================================================================
2051 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2052 GEOM::GEOM_Object_ptr theShapeObject )
2055 Unexpect aCatch(SALOME_SalomeException);
2056 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2058 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2059 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2060 SALOME::BAD_PARAM );
2062 if ( CORBA::is_nil( theMesh ) )
2063 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2064 SALOME::BAD_PARAM );
2066 // Update Python script
2067 TPythonDump() << "isDone = " << this << ".Compute( "
2068 << theMesh << ", " << theShapeObject << ")";
2072 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2073 ASSERT( meshServant );
2074 if ( meshServant ) {
2075 if ( isGeomModifIcon( theMesh ))
2076 meshServant->Clear();
2078 meshServant->Load();
2079 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2080 meshServant->CheckGeomModif();
2081 // get local TopoDS_Shape
2082 TopoDS_Shape myLocShape;
2083 if(theMesh->HasShapeToMesh())
2084 myLocShape = GeomObjectToShape( theShapeObject );
2086 myLocShape = SMESH_Mesh::PseudoShape();
2087 // call implementation compute
2088 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2089 myGen.PrepareCompute( myLocMesh, myLocShape );
2090 int how = ::SMESH_Gen::COMPACT_MESH;
2091 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2092 how |= ::SMESH_Gen::SHAPE_ONLY;
2093 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2094 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2095 myLocMesh.GetMeshDS()->Modified();
2096 UpdateIcons( theMesh );
2098 HighLightInvalid( theMesh, /*isInvalid=*/false );
2102 catch ( std::bad_alloc& ) {
2103 INFOS( "Compute(): lack of memory" );
2105 catch ( SALOME_Exception& S_ex ) {
2106 INFOS( "Compute(): catch exception "<< S_ex.what() );
2109 INFOS( "Compute(): unknown exception " );
2114 //=============================================================================
2116 * SMESH_Gen_i::CancelCompute
2118 * Cancel Compute mesh on a shape
2120 //=============================================================================
2122 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2123 GEOM::GEOM_Object_ptr theShapeObject )
2125 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2127 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2128 TopoDS_Shape myLocShape;
2129 if(theMesh->HasShapeToMesh())
2130 myLocShape = GeomObjectToShape( theShapeObject );
2132 myLocShape = SMESH_Mesh::PseudoShape();
2133 myGen.CancelCompute( myLocMesh, myLocShape);
2137 //=============================================================================
2139 * SMESH_Gen_i::Precompute
2141 * Compute mesh as preview till indicated dimension on shape
2143 //=============================================================================
2145 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2146 GEOM::GEOM_Object_ptr theShapeObject,
2147 SMESH::Dimension theDimension,
2148 SMESH::long_array& theShapesId)
2150 Unexpect aCatch(SALOME_SalomeException);
2151 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2153 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2154 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2155 SALOME::BAD_PARAM );
2157 if ( CORBA::is_nil( theMesh ) )
2158 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2159 SALOME::BAD_PARAM );
2161 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2164 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2165 meshServant->Load();
2166 ASSERT( meshServant );
2167 if ( meshServant ) {
2168 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2169 meshServant->CheckGeomModif();
2170 // get local TopoDS_Shape
2171 TopoDS_Shape myLocShape;
2172 if(theMesh->HasShapeToMesh())
2173 myLocShape = GeomObjectToShape( theShapeObject );
2175 return result._retn();
2177 // call implementation compute
2178 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2180 ::MeshDimension aDim = (MeshDimension)theDimension;
2181 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2183 int nbShapeId = shapeIds.size();
2184 theShapesId.length( nbShapeId );
2185 // iterates on shapes and collect mesh entities into mesh preview
2186 TSetOfInt::const_iterator idIt = shapeIds.begin();
2187 TSetOfInt::const_iterator idEnd = shapeIds.end();
2188 std::map< int, int > mapOfShIdNb;
2189 std::set< SMESH_TLink > setOfEdge;
2190 std::list< SMDSAbs_ElementType > listOfElemType;
2191 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2192 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2193 TNode2LocalIDMap mapNode2LocalID;
2194 list< TNodeLocalID > connectivity;
2195 int i, nbConnNodes = 0;
2196 std::set< const SMESH_subMesh* > setOfVSubMesh;
2197 // iterates on shapes
2198 for ( ; idIt != idEnd; idIt++ )
2200 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2202 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2203 if ( !sm || !sm->IsMeshComputed() )
2206 const TopoDS_Shape& aSh = sm->GetSubShape();
2207 const int shDim = myGen.GetShapeDim( aSh );
2208 if ( shDim < 1 || shDim > theDimension )
2211 mapOfShIdNb[ *idIt ] = 0;
2212 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2214 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2215 if ( !smDS ) continue;
2217 if ( theDimension == SMESH::DIM_2D )
2219 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2220 while ( faceIt->more() )
2222 const SMDS_MeshElement* face = faceIt->next();
2223 int aNbNode = face->NbNodes();
2225 aNbNode /= 2; // do not take into account additional middle nodes
2227 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2228 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2230 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2231 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2233 listOfElemType.push_back( SMDSAbs_Edge );
2234 connectivity.push_back
2235 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2236 connectivity.push_back
2237 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2243 else if ( theDimension == SMESH::DIM_1D )
2245 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2246 while ( nodeIt->more() )
2248 listOfElemType.push_back( SMDSAbs_Node );
2249 connectivity.push_back
2250 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2252 // add corner nodes by first vertex from edge
2253 SMESH_subMeshIteratorPtr edgeSmIt =
2254 sm->getDependsOnIterator(/*includeSelf*/false,
2255 /*complexShapeFirst*/false);
2256 while ( edgeSmIt->more() )
2258 SMESH_subMesh* vertexSM = edgeSmIt->next();
2259 // check that vertex is not already treated
2260 if ( !setOfVSubMesh.insert( vertexSM ).second )
2262 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2265 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2266 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2267 while ( nodeIt->more() )
2269 listOfElemType.push_back( SMDSAbs_Node );
2270 connectivity.push_back
2271 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2277 // fill node coords and assign local ids to the nodes
2278 int nbNodes = mapNode2LocalID.size();
2279 result->nodesXYZ.length( nbNodes );
2280 TNodeLocalID node2ID = mapNode2LocalID.begin();
2281 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2282 node2ID->second = i;
2283 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2284 result->nodesXYZ[i].x = node->X();
2285 result->nodesXYZ[i].y = node->Y();
2286 result->nodesXYZ[i].z = node->Z();
2288 // fill connectivity
2289 result->elementConnectivities.length( nbConnNodes );
2290 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2291 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2292 result->elementConnectivities[i] = (*connIt)->second;
2295 // fill element types
2296 result->elementTypes.length( listOfElemType.size() );
2297 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2298 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2299 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2301 SMDSAbs_ElementType elemType = *typeIt;
2302 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2303 result->elementTypes[i].isPoly = false;
2304 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2307 // correct number of shapes
2308 theShapesId.length( mapOfShIdNb.size() );
2312 catch ( std::bad_alloc& ) {
2313 INFOS( "Precompute(): lack of memory" );
2315 catch ( SALOME_Exception& S_ex ) {
2316 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2319 INFOS( "Precompute(): unknown exception " );
2321 return result._retn();
2325 //=============================================================================
2327 * SMESH_Gen_i::Evaluate
2329 * Evaluate mesh on a shape
2331 //=============================================================================
2333 SMESH::smIdType_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2334 GEOM::GEOM_Object_ptr theShapeObject)
2336 Unexpect aCatch(SALOME_SalomeException);
2337 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2339 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2340 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2342 if ( CORBA::is_nil( theMesh ) )
2343 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2345 SMESH::smIdType_array_var nbels = new SMESH::smIdType_array;
2346 nbels->length(SMESH::Entity_Last);
2347 int i = SMESH::Entity_Node;
2348 for (; i < SMESH::Entity_Last; i++)
2351 // Update Python script
2352 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2353 << theMesh << ", " << theShapeObject << ")";
2357 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2358 ASSERT( meshServant );
2359 if ( meshServant ) {
2360 meshServant->Load();
2361 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2362 meshServant->CheckGeomModif();
2363 // get local TopoDS_Shape
2364 TopoDS_Shape myLocShape;
2365 if(theMesh->HasShapeToMesh())
2366 myLocShape = GeomObjectToShape( theShapeObject );
2368 myLocShape = SMESH_Mesh::PseudoShape();
2369 // call implementation compute
2370 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2371 MapShapeNbElems aResMap;
2372 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2373 MapShapeNbElemsItr anIt = aResMap.begin();
2374 for(; anIt!=aResMap.end(); anIt++) {
2375 const vector<smIdType>& aVec = (*anIt).second;
2376 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2377 smIdType nbElem = aVec[i];
2378 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2380 SMESH_subMesh* sm = anIt->first;
2381 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2382 const SMESH_Algo* algo = sm->GetAlgo();
2383 if ( (algo && !error.get()) || error->IsOK() )
2384 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2388 nbels[i] += aVec[i];
2392 return nbels._retn();
2395 catch ( std::bad_alloc& ) {
2396 INFOS( "Evaluate(): lack of memory" );
2398 catch ( SALOME_Exception& S_ex ) {
2399 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2402 INFOS( "Evaluate(): unknown exception " );
2405 return nbels._retn();
2408 //================================================================================
2410 * \brief Return geometrical object the given element is built on
2411 * \param theMesh - the mesh the element is in
2412 * \param theElementID - the element ID
2413 * \param theGeomName - the name of the result geom object if it is not yet published
2414 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2416 //================================================================================
2418 GEOM::GEOM_Object_ptr
2419 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2420 SMESH::smIdType theElementID,
2421 const char* theGeomName)
2423 Unexpect aCatch(SALOME_SalomeException);
2425 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2426 if ( !geom->_is_nil() ) {
2427 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2428 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2430 // try to find the corresponding SObject
2431 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2432 if ( SObj->_is_nil() ) // submesh can be not found even if published
2434 // try to find published submesh
2435 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2436 if ( !geom->IsMainShape() && list->length() == 1 ) {
2437 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2438 SALOMEDS::ChildIterator_wrap it;
2439 if ( !mainSO->_is_nil() ) {
2440 it = getStudyServant()->NewChildIterator( mainSO );
2442 if ( !it->_is_nil() ) {
2443 for ( it->InitEx(true); it->More(); it->Next() ) {
2444 SALOMEDS::SObject_wrap so = it->Value();
2445 CORBA::Object_var obj = SObjectToObject( so );
2446 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2447 if ( !subGeom->_is_nil() ) {
2448 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2449 if ( subList->length() == 1 && list[0] == subList[0] ) {
2459 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2460 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2462 // return only published geometry
2463 if ( !SObj->_is_nil() ) {
2464 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2465 CORBA::Object_var obj = SObjectToObject( SObj );
2466 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2470 return GEOM::GEOM_Object::_nil();
2473 //================================================================================
2475 * \brief Return geometrical object the given element is built on.
2476 * \param theMesh - the mesh the element is in
2477 * \param theElementID - the element ID
2478 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2480 //================================================================================
2482 GEOM::GEOM_Object_ptr
2483 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2484 SMESH::smIdType theElementID)
2486 Unexpect aCatch(SALOME_SalomeException);
2487 if ( CORBA::is_nil( theMesh ) )
2488 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2490 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2491 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2493 // get a core mesh DS
2494 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2495 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2497 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2498 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2499 // find the element in mesh
2500 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2501 // find a shape id by the element
2502 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2503 // get a geom object by the shape id
2504 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2505 if ( geom->_is_nil() ) {
2506 // try to find a published sub-shape
2507 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2508 SALOMEDS::ChildIterator_wrap it;
2509 if ( !mainSO->_is_nil() ) {
2510 it = getStudyServant()->NewChildIterator( mainSO );
2512 if ( !it->_is_nil() ) {
2513 for ( it->InitEx(true); it->More(); it->Next() ) {
2514 SALOMEDS::SObject_wrap so = it->Value();
2515 CORBA::Object_var obj = SObjectToObject( so );
2516 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2517 if ( !subGeom->_is_nil() ) {
2518 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2519 if ( subList->length() == 1 && shapeID == subList[0] ) {
2527 if ( geom->_is_nil() ) {
2529 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2530 if ( !op->_is_nil() )
2531 geom = op->GetSubShape( mainShape, shapeID );
2536 if ( !geom->_is_nil() ) {
2537 GeomObjectToShape( geom ); // let geom client remember the found shape
2538 return geom._retn();
2543 return GEOM::GEOM_Object::_nil();
2546 //================================================================================
2548 * SMESH_Gen_i::Concatenate
2550 * Concatenate the given meshes into one mesh
2552 //================================================================================
2554 SMESH::SMESH_Mesh_ptr
2555 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2556 CORBA::Boolean theUniteIdenticalGroups,
2557 CORBA::Boolean theMergeNodesAndElements,
2558 CORBA::Double theMergeTolerance,
2559 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2561 return ConcatenateCommon(theMeshesArray,
2562 theUniteIdenticalGroups,
2563 theMergeNodesAndElements,
2569 //================================================================================
2571 * SMESH_Gen_i::ConcatenateWithGroups
2573 * Concatenate the given meshes into one mesh
2574 * Create the groups of all elements from initial meshes
2576 //================================================================================
2578 SMESH::SMESH_Mesh_ptr
2579 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2580 CORBA::Boolean theUniteIdenticalGroups,
2581 CORBA::Boolean theMergeNodesAndElements,
2582 CORBA::Double theMergeTolerance,
2583 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2585 return ConcatenateCommon(theMeshesArray,
2586 theUniteIdenticalGroups,
2587 theMergeNodesAndElements,
2593 //================================================================================
2595 * SMESH_Gen_i::ConcatenateCommon
2597 * Concatenate the given meshes into one mesh
2599 //================================================================================
2601 SMESH::SMESH_Mesh_ptr
2602 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2603 CORBA::Boolean theUniteIdenticalGroups,
2604 CORBA::Boolean theMergeNodesAndElements,
2605 CORBA::Double theMergeTolerance,
2606 CORBA::Boolean theCommonGroups,
2607 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2609 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2610 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2612 // create mesh if theMeshToAppendTo not provided
2613 SMESH::SMESH_Mesh_var newMesh;
2614 if ( CORBA::is_nil( theMeshToAppendTo ))
2615 newMesh = CreateEmptyMesh();
2617 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2618 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2619 if ( !newImpl ) return newMesh._retn();
2622 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2623 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2625 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2626 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2627 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2628 TGroupsMap groupsMap;
2629 TListOfNewGroups listOfNewGroups;
2631 if ( !CORBA::is_nil( theMeshToAppendTo ))
2633 // fill groupsMap with existing groups
2634 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2635 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2637 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2638 if ( !group->_is_nil() )
2640 CORBA::String_var name = group->GetName();
2641 SMESH::ElementType type = group->GetType();
2642 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2647 ::SMESH_MeshEditor newEditor( &locMesh );
2648 ::SMESH_MeshEditor::ElemFeatures elemType;
2650 // loop on sub-meshes
2651 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2653 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2654 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2655 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2656 if ( !initImpl ) continue;
2657 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2661 // assure that IDs increment by one during iteration
2662 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2663 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2664 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2665 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2667 initMeshDS->Modified();
2668 initMeshDS->CompactMesh();
2671 // remember nb of elements before filling in
2672 SMESH::smIdType_array_var prevState = newMesh->GetNbElementsByType();
2676 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2677 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2678 while ( elemIt->more() )
2680 SMESH_NodeXYZ node = elemIt->next();
2681 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2686 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2687 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2689 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2690 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2691 while ( elemIt->more() )
2693 const SMDS_MeshElement* elem = elemIt->next();
2694 elemType.myNodes.resize( elem->NbNodes() );
2696 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2697 for ( int k = 0; itNodes->more(); k++)
2699 const SMDS_MeshNode* node = itNodes->next();
2700 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2703 // creates a corresponding element on existent nodes in new mesh
2704 newElems[ elem->GetID() ] =
2705 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2707 newEditor.ClearLastCreated(); // forget the history
2710 // create groups of just added elements
2711 SMESH::SMESH_Group_var newGroup;
2712 SMESH::ElementType groupType;
2713 if ( theCommonGroups )
2716 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2717 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2718 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2719 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2722 SMESH::smIdType_array_var curState = newMesh->GetNbElementsByType();
2724 for( groupType = SMESH::NODE;
2725 groupType < SMESH::NB_ELEMENT_TYPES;
2726 groupType = (SMESH::ElementType)( groupType + 1 ))
2728 if ( curState[ groupType ] <= prevState[ groupType ])
2729 continue; // no elements of groupType added from the i-th mesh
2731 // make a group name
2732 std::string groupName = "Gr";
2733 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2735 CORBA::String_var name = meshSO->GetName();
2739 groupName += typeNames[ groupType ];
2741 // make and fill a group
2742 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2743 std::vector< const SMDS_MeshElement* > & elemVec =
2744 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2745 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2747 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2749 for ( size_t j = 0; j < elemVec.size(); ++j )
2751 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2752 grpDS->Add( elemVec[j] );
2756 listOfNewGroups.clear();
2757 listOfNewGroups.push_back( newGroup );
2758 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2763 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2767 SMESH::SMESH_GroupBase_ptr group;
2768 CORBA::String_var groupName;
2769 SMESH::smIdType_array_var newIDs = new SMESH::smIdType_array();
2771 // loop on groups of a source mesh
2772 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2773 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2775 group = listOfGroups[iG];
2776 groupType = group->GetType();
2777 groupName = group->GetName();
2778 std::string name = groupName.in();
2780 // convert a list of IDs
2781 newIDs->length( group->Size() );
2782 std::vector< const SMDS_MeshElement* > & elemVec =
2783 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2784 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2786 while ( itGrElems->more() )
2788 const SMDS_MeshElement* elem = itGrElems->next();
2789 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2791 newIDs[ nbElems++ ] = newElem->GetID();
2793 newIDs->length( nbElems );
2795 // check that a current group name and type don't have identical ones in final mesh
2796 listOfNewGroups.clear();
2797 TNameAndType nameAndType( name, groupType );
2798 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2799 if ( anIter == groupsMap.end() )
2801 // add a new group in the mesh
2802 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2803 newGroup->Add( newIDs );
2805 listOfNewGroups.push_back( newGroup );
2806 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2808 else if ( theUniteIdenticalGroups )
2810 // unite identical groups
2811 TListOfNewGroups& aNewGroups = anIter->second;
2812 aNewGroups.front()->Add( newIDs );
2816 // rename identical groups
2817 newGroup = newImpl->CreateGroup( groupType, groupName );
2818 newGroup->Add( newIDs );
2820 TListOfNewGroups& newGroups = anIter->second;
2821 std::string newGroupName;
2822 if ( newGroups.size() == 1 )
2824 newGroupName = name + "_1";
2825 newGroups.front()->SetName( newGroupName.c_str() );
2827 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2828 newGroup->SetName( newGroupName.c_str() );
2829 newGroups.push_back( newGroup );
2832 } // if an IDSource is a mesh
2835 if ( theMergeNodesAndElements ) // merge nodes
2837 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2838 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2839 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2840 /*SeparateCornersAndMedium=*/ false );
2841 newEditor.MergeNodes( groupsOfNodes );
2843 newEditor.MergeEqualElements();
2846 // Update Python script
2847 pythonDump << newMesh << " = " << this
2848 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2849 << theMeshesArray << ", "
2850 << theUniteIdenticalGroups << ", "
2851 << theMergeNodesAndElements << ", "
2852 << TVar( theMergeTolerance ) << ", "
2853 << theMeshToAppendTo << " )";
2855 pPythonDump.reset(); // enable python dump from GetGroups()
2857 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2858 if ( !newMesh->_is_nil() )
2860 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2863 // IPAL21468 Change icon of compound because it need not be computed.
2864 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2865 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2867 newMeshDS->Modified();
2869 return newMesh._retn();
2872 //================================================================================
2874 * \brief Create a mesh by copying a part of another mesh
2875 * \param meshPart - a part of mesh to copy
2876 * \param toCopyGroups - to create in the new mesh groups
2877 * the copied elements belongs to
2878 * \param toKeepIDs - to preserve IDs of the copied elements or not
2879 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2881 //================================================================================
2883 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2884 const char* meshName,
2885 CORBA::Boolean toCopyGroups,
2886 CORBA::Boolean toKeepIDs)
2888 Unexpect aCatch(SALOME_SalomeException);
2890 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2891 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2893 // 1. Get source mesh
2895 if ( CORBA::is_nil( meshPart ))
2896 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2898 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2899 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2901 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2903 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2905 // 2. Make a new mesh
2907 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2908 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2910 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2911 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2912 if ( !meshSO->_is_nil() )
2914 SetName( meshSO, meshName, "Mesh" );
2915 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2917 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2918 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2919 ::SMESH_MeshEditor::ElemFeatures elemType;
2921 // 3. Get elements to copy
2923 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2924 TIDSortedElemSet srcElems;
2925 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2926 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2929 srcElemIt = srcMeshDS->elementsIterator();
2930 srcNodeIt = srcMeshDS->nodesIterator();
2934 SMESH::smIdType_array_var ids = meshPart->GetIDs();
2935 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2937 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2938 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2939 srcElems.insert( elem );
2943 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2944 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2945 srcElems.insert( elem );
2947 if ( srcElems.empty() )
2948 return newMesh._retn();
2950 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2951 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2956 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2957 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2958 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2960 const SMDS_MeshNode *nSrc, *nTgt;
2961 vector< const SMDS_MeshNode* > nodes;
2962 while ( srcElemIt->more() )
2964 const SMDS_MeshElement * elem = srcElemIt->next();
2966 nodes.resize( elem->NbNodes());
2967 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2969 for ( iN = 0; nIt->more(); ++iN )
2971 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2972 nTgt = newMeshDS->FindNode( nSrc->GetID());
2974 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2979 for ( iN = 0; nIt->more(); ++iN )
2981 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2982 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2984 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2985 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2989 if ( elem->GetType() != SMDSAbs_Node )
2991 elemType.Init( elem, /*basicOnly=*/false );
2992 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2994 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2995 if ( toCopyGroups && !toKeepIDs )
2996 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2998 } // while ( srcElemIt->more() )
3000 // 4(b). Copy free nodes
3002 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3004 while ( srcNodeIt->more() )
3006 nSrc = srcNodeIt->next();
3007 if ( nSrc->NbInverseElements() == 0 )
3010 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3012 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3019 int nbNewGroups = 0;
3022 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3023 while ( gIt->more() )
3025 SMESH_Group* group = gIt->next();
3026 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3028 // Check group type. We copy nodal groups containing nodes of copied element
3029 SMDSAbs_ElementType groupType = groupDS->GetType();
3030 if ( groupType != SMDSAbs_Node &&
3031 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3032 continue; // group type differs from types of meshPart
3034 // Find copied elements in the group
3035 vector< const SMDS_MeshElement* > groupElems;
3036 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3039 const SMDS_MeshElement* foundElem;
3040 if ( groupType == SMDSAbs_Node )
3042 while ( eIt->more() )
3043 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3044 groupElems.push_back( foundElem );
3048 while ( eIt->more() )
3049 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3050 groupElems.push_back( foundElem );
3055 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3056 if ( e2eMap.empty() ) continue;
3057 smIdType minID = e2eMap.begin()->first->GetID();
3058 smIdType maxID = e2eMap.rbegin()->first->GetID();
3059 TE2EMap::iterator e2e;
3060 while ( eIt->more() && groupElems.size() < e2eMap.size())
3062 const SMDS_MeshElement* e = eIt->next();
3063 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3064 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3065 groupElems.push_back( e2e->second );
3069 if ( !groupElems.empty() )
3071 SMESH::SMESH_Group_var newGroupObj =
3072 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3073 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3075 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3076 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3077 for ( unsigned i = 0; i < groupElems.size(); ++i )
3078 smdsGroup.Add( groupElems[i] );
3086 newMeshDS->Modified();
3088 *pyDump << newMesh << " = " << this
3089 << ".CopyMesh( " << meshPart << ", "
3090 << "'" << meshName << "', "
3091 << toCopyGroups << ", "
3092 << toKeepIDs << ")";
3094 pyDumpDeleter.reset(); // allow dump in GetGroups()
3096 if ( nbNewGroups > 0 ) // dump created groups
3097 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3099 return newMesh._retn();
3103 namespace // utils for CopyMeshWithGeom()
3105 typedef std::map< std::string, std::string > TStr2StrMap;
3106 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3107 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3108 typedef std::map< std::string, int > TName2IndexMap;
3110 //================================================================================
3112 * \brief Return a new sub-shape corresponding to an old one
3114 //================================================================================
3118 SMESH_Mesh_i* mySrcMesh_i;
3119 SMESH_Mesh_i* myNewMesh_i;
3120 SMESH_Gen_i* myGen_i;
3124 TStr2StrMap myOld2NewEntryMap; // map of study entries
3126 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3127 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3128 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3131 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3133 // not directly relating to shape search
3134 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3136 //================================================================================
3138 * \brief Constructor
3140 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3141 SMESH_Mesh_i* newMesh_i,
3142 SMESH_Gen_i* smeshGen_i )
3143 : mySrcMesh_i( srcMesh_i ),
3144 myNewMesh_i( newMesh_i ),
3145 myGen_i ( smeshGen_i ),
3146 myToPublish( smeshGen_i->IsEnablePublish() ),
3147 myGIPMapDone( false )
3149 // retrieve from the study shape mapping made thanks to
3150 // "Set presentation parameters and sub-shapes from arguments" option
3152 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3153 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3154 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3155 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3156 if ( newSO->_is_nil() )
3158 myToPublish = false;
3161 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3163 CORBA::String_var oldEntry = oldSO->GetID();
3164 CORBA::String_var newEntry = newSO->GetID();
3165 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3166 std::string( newEntry.in() )));
3167 std::string newMainEntry = newEntry.in();
3169 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3170 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3171 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3172 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3173 /*groupsOnly=*/false );
3174 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3176 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3177 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3178 bool refFound = false;
3179 for ( ; anIter->More(); anIter->Next() )
3181 SALOMEDS::SObject_wrap so = anIter->Value();
3182 if ( so->ReferencedObject( oldSO.inout() ))
3184 oldEntry = oldSO->GetID();
3185 newEntry = newSO->GetID();
3186 if (( refFound = ( newMainEntry != oldEntry.in() )))
3187 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3188 std::string( newEntry.in() )));
3193 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3194 if ( father->_is_equivalent( mainShapeNew ))
3196 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3197 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3198 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3199 CORBA::String_var name = newSO->GetName();
3201 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3207 //================================================================================
3209 * \brief Find a new sub-shape corresponding to an old one
3211 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3214 return GEOM::GEOM_Object::_duplicate( oldShape );
3216 GEOM::GEOM_Object_var newShape;
3218 if ( CORBA::is_nil( oldShape ))
3219 return newShape._retn();
3221 if ( !isChildOfOld( oldShape ))
3222 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3224 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3225 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3227 // try to find by entry or name
3230 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3231 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3232 if ( o2nID != myOld2NewEntryMap.end() )
3234 newShape = getShapeByEntry( o2nID->second );
3236 if ( newShape->_is_nil() )
3238 CORBA::String_var name = oldShape->GetName();
3239 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3240 if ( n2ind != myName2SubshapeIndex.end() )
3242 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3243 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3244 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3245 if ( oldIndices->length() == 0 ||
3246 newIndices->length() == 0 ||
3247 getShapeType( myNewMesh_i, newIndices[0] ) !=
3248 getShapeType( mySrcMesh_i, oldIndices[0] ))
3249 newShape = GEOM::GEOM_Object::_nil();
3254 if ( newShape->_is_nil() )
3256 // try to construct a new sub-shape using myGIPMap
3258 std::vector< int > newIndices;
3259 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3260 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3262 findNewIDs( oldIndices[i], newIndices );
3264 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3267 newShape = getInPlace( oldShape );
3269 if ( !newIndices.empty() && newShape->_is_nil() )
3271 // search for a sub-shape with same ids
3272 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3273 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3274 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3275 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3277 if ( newShape->_is_nil() )
3280 // create a new shape
3281 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3283 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3285 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3286 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3288 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3289 newIndicesList->length( newIndices.size() );
3290 for ( size_t i = 0; i < newIndices.size(); ++i )
3291 newIndicesList[ i ] = newIndices[ i ];
3292 grOp->UnionIDs( newShape, newIndicesList );
3296 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3297 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3306 if ( !newShape->_is_nil() && myToPublish )
3308 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3309 if ( !newEntry.in() || !newEntry.in()[0] )
3311 CORBA::String_var name = oldShape->GetName();
3312 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3313 newEntry = newShape->GetStudyEntry();
3314 oldEntry = oldShape->GetStudyEntry();
3315 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3316 std::string( newEntry.in() )));
3320 return newShape._retn();
3323 //================================================================================
3325 * \brief Return a study entry of a new shape by study entry of the old one
3327 std::string FindNew( const std::string & oldEntry )
3332 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3333 if ( o2nID != myOld2NewEntryMap.end() )
3334 return o2nID->second;
3336 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3337 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3340 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3341 if ( newShape->_is_nil() )
3342 return std::string();
3344 CORBA::String_var newEntry = newShape->GetStudyEntry();
3345 return newEntry.in();
3348 //================================================================================
3350 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3351 * Return zero if not found or there are more than one new ID
3353 int FindNew( int oldID )
3362 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3364 if ( myGIPMap[ oldID ].length() == 1 )
3366 newID = myGIPMap[ oldID ][ 0 ];
3368 else if ( myGIPMap[ oldID ].length() > 1 &&
3369 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3371 // select a meshed VERTEX
3372 SMESH_subMesh* newSM;
3373 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3374 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3375 ( !newSM->IsEmpty() ))
3376 newID = myGIPMap[ oldID ][ i ];
3382 //================================================================================
3384 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3385 * Return zero if the old shape is not kept as is in the new shape.
3387 int FindNewNotChanged( SMESH_subMesh* oldSM )
3390 return oldSM->GetId();
3392 int newID = FindNew( oldSM->GetId() );
3396 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3400 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3401 // one new sub-shape of the same type.
3403 if ( oldSM->DependsOn().size() !=
3404 newSM->DependsOn().size() )
3407 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3408 while ( srcSMIt->more() )
3410 oldSM = srcSMIt->next();
3411 int newSubID = FindNew( oldSM->GetId() );
3412 if ( getShapeType( myNewMesh_i, newSubID ) !=
3413 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3419 //================================================================================
3421 * \brief Return shape by study entry
3423 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3425 GEOM::GEOM_Object_var shape;
3426 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3427 if ( !so->_is_nil() )
3429 CORBA::Object_var obj = so->GetObject();
3430 shape = GEOM::GEOM_Object::_narrow( obj );
3432 return shape._retn();
3435 //================================================================================
3437 * \brief Fill myGIPMap by calling GetInPlaceMap()
3441 if ( !myGIPMapDone )
3443 myGIPMapDone = true;
3445 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3446 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3447 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3448 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3451 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3455 myGIPMap = new GEOM::ListOfListOfLong();
3460 //================================================================================
3462 * \brief Get new sub-shape by calling GetInPlace()
3464 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3466 GEOM::GEOM_Object_var newShape;
3468 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3469 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3470 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3473 newShape = op->GetInPlace( mainShapeNew, oldShape );
3478 return newShape._retn();
3481 //================================================================================
3483 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3484 * number of found IDs
3486 int findNewIDs( int oldID, std::vector< int >& newIDs )
3488 size_t prevNbIDs = newIDs.size();
3490 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3492 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3493 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3495 return newIDs.size() - prevNbIDs;
3498 //================================================================================
3500 * \brief Check if an object relates to the old shape
3502 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3504 if ( CORBA::is_nil( oldShape ))
3506 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3507 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3508 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3509 mainShapeOld1->_is_equivalent( oldShape ));
3512 //================================================================================
3514 * \brief Return shape type by shape ID
3516 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3518 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3519 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3520 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3523 //================================================================================
3525 * \brief Store a source sub-shape for which a counterpart not found and
3526 * a smesh object invalid due to that
3528 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3529 SALOMEDS::SObject_wrap smeshSO )
3531 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3532 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3534 CORBA::String_var smeshEntry = smeshSO->GetID();
3535 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3539 //================================================================================
3541 * \brief Store a source sub-shape for which a counterpart not found and
3542 * a smesh object invalid due to that
3544 void AddInvalid( std::string geomEntry,
3545 SALOMEDS::SObject_wrap smeshSO )
3547 if ( !geomEntry.empty() )
3549 CORBA::String_var smeshEntry = smeshSO->GetID();
3550 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3554 //================================================================================
3556 * \brief Store a source sub-shape for which a counterpart not found and
3557 * a smesh object invalid due to that
3559 void AddInvalid( int oldGeomID,
3560 SALOMEDS::SObject_wrap smeshSO )
3562 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3563 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3566 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3567 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3569 SMESH_Comment geomName( typeName[ shapeType ]);
3570 geomName << " #" << oldGeomID;
3572 CORBA::String_var smeshEntry = smeshSO->GetID();
3573 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3576 //================================================================================
3578 * \brief Return entries of a source sub-shape for which a counterpart not found and
3579 * of smesh objects invalid due to that
3581 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3582 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3585 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3586 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3588 nbSO += 1 + entry2entrySet->second.size();
3590 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3591 theInvalidEntries->length ( nbSO );
3592 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3594 entry2entrySet = myInvalidMap.begin();
3595 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3597 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3599 std::set< std::string > & entrySet = entry2entrySet->second;
3600 std::set< std::string >::iterator entry = entrySet.begin();
3601 for ( ; entry != entrySet.end(); ++entry )
3603 theInvalidEntries[ iEntry++ ] = entry->c_str();
3605 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3606 if ( !so->_is_nil() )
3607 theInvalidMeshSObjects[ iSO++ ] = so;
3612 }; // struct ShapeMapper
3614 //================================================================================
3616 * \brief Append an item to a CORBA sequence
3618 template < class CORBA_seq, class ITEM >
3619 void append( CORBA_seq& seq, ITEM item )
3621 if ( !CORBA::is_nil( item ))
3623 seq->length( 1 + seq->length() );
3624 seq[ seq->length() - 1 ] = item;
3627 } // namespace // utils for CopyMeshWithGeom()
3629 //================================================================================
3631 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3632 * \param [in] sourceMesh - a mesh to copy
3633 * \param [in] newGeometry - a new geometry
3634 * \param [in] toCopyGroups - to create groups in the new mesh
3635 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3636 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3637 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3638 * \param [out] newMesh - return a new mesh
3639 * \param [out] newGroups - return new groups
3640 * \param [out] newSubmeshes - return new sub-meshes
3641 * \param [out] newHypotheses - return new algorithms and hypotheses
3642 * \param [out] invalidEntries - return study entries of objects whose
3643 * counterparts are not found in the newGeometry, followed by entries
3644 * of mesh sub-objects that are invalid because they depend on a not found
3645 * preceding sub-shape
3646 * \return CORBA::Boolean - is a success
3648 //================================================================================
3650 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3651 GEOM::GEOM_Object_ptr theNewGeometry,
3652 const char* theMeshName,
3653 CORBA::Boolean theToCopyGroups,
3654 CORBA::Boolean theToReuseHypotheses,
3655 CORBA::Boolean theToCopyElements,
3656 SMESH::SMESH_Mesh_out theNewMesh,
3657 SMESH::ListOfGroups_out theNewGroups,
3658 SMESH::submesh_array_out theNewSubmeshes,
3659 SMESH::ListOfHypothesis_out theNewHypotheses,
3660 SMESH::string_array_out theInvalidEntries)
3662 if ( CORBA::is_nil( theSourceMesh ) ||
3663 CORBA::is_nil( theNewGeometry ))
3664 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3666 if ( !theSourceMesh->HasShapeToMesh() )
3667 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3672 TPythonDump pyDump; // prevent dump from CreateMesh()
3674 theNewMesh = CreateMesh( theNewGeometry );
3675 theNewGroups = new SMESH::ListOfGroups();
3676 theNewSubmeshes = new SMESH::submesh_array();
3677 theNewHypotheses = new SMESH::ListOfHypothesis();
3678 theInvalidEntries = new SMESH::string_array();
3680 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3682 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3683 GEOM::GEOM_Object_var geom, newGeom;
3684 SALOMEDS::SObject_wrap so;
3686 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3687 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3690 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3692 // treat hypotheses of mesh and sub-meshes
3693 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3694 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3696 bool isSubMesh = ( iSM < smList->length() );
3699 // create a new sub-mesh
3700 SMESH::SMESH_subMesh_var newSM;
3701 geom = smList[iSM]->GetSubShape();
3702 so = ObjectToSObject( smList[iSM] );
3703 CORBA::String_var name;
3704 if ( !so->_is_nil() )
3705 name = so->GetName();
3706 newGeom = shapeMapper.FindNew( geom );
3707 if ( newGeom->_is_nil() )
3709 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3710 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3715 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3717 append( theNewSubmeshes, newSM );
3719 if ( newGeom->_is_nil() )
3720 continue; // don't assign hypotheses
3724 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3726 so = ObjectToSObject( theNewMesh );
3727 SetName( so, theMeshName, "Mesh" );
3730 // assign hypotheses
3731 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3732 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3734 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3735 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3737 // get geometry hyp depends on
3738 std::vector< std::string > entryArray;
3739 std::vector< int > subIDArray;
3740 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3742 if ( !theToReuseHypotheses || dependsOnGeom )
3744 // create a new hypothesis
3745 CORBA::String_var type = hyp->GetName();
3746 CORBA::String_var lib = hyp->GetLibName();
3747 CORBA::String_var data = hyp_i->SaveTo();
3750 hyp = CreateHypothesis( type, lib );
3751 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3752 hyp_i->LoadFrom( data.in() );
3753 append( theNewHypotheses, hyp );
3757 // update geometry hyp depends on
3758 if ( dependsOnGeom )
3760 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3762 if ( !entryArray[ iGeo ].empty() )
3764 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3765 if ( newEntry.empty() )
3768 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3769 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3771 entryArray[ iGeo ] = newEntry;
3774 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3776 if ( subIDArray[ iGeo ] > 0 )
3778 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3782 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3783 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3785 subIDArray[ iGeo ] = newID;
3788 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3792 CORBA::String_var errorText;
3793 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3794 if ( errorText.in()[0] )
3797 } // loop on hypotheses
3798 } // loop on sub-meshes and mesh
3801 // copy mesh elements, keeping IDs
3802 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3803 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3805 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3806 ::SMESH_MeshEditor::ElemFeatures elemData;
3808 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3809 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3810 /*vertexLast=*/false);
3811 while ( srcSMIt->more() )
3813 SMESH_subMesh* srcSM = srcSMIt->next();
3814 if ( srcSM->IsEmpty() )
3815 continue; // not yet computed
3816 int newID = shapeMapper.FindNewNotChanged( srcSM );
3820 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3821 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3822 while ( nIt->more() )
3824 SMESH_NodeXYZ node( nIt->next() );
3825 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3827 const SMDS_PositionPtr pos = node->GetPosition();
3828 const double* uv = pos->GetParameters();
3829 switch ( pos->GetTypeOfPosition() )
3831 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3832 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3833 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3834 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3838 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3839 while( eIt->more() )
3841 const SMDS_MeshElement* e = eIt->next();
3842 elemData.Init( e, /*basicOnly=*/false );
3843 elemData.SetID( e->GetID() );
3844 elemData.myNodes.resize( e->NbNodes() );
3845 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3847 for ( iN = 0; nnIt->more(); ++iN )
3849 const SMDS_MeshNode* srcNode = nnIt->next();
3850 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3851 if ( !elemData.myNodes[ iN ])
3854 if ( iN == elemData.myNodes.size() )
3855 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3856 newMeshDS->SetMeshElementOnShape( newElem, newID );
3858 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3859 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3862 newMeshDS->Modified();
3868 TStr2StrMap old2newGroupMap;
3870 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3872 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3873 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3874 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3876 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3877 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3878 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3880 CORBA::String_var name = groups[ i ]->GetName();
3881 SMESH::ElementType elemType = groups[ i ]->GetType();
3883 SMESH::SMESH_GroupBase_var newGroup;
3885 if ( !stdlGroup->_is_nil() )
3887 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3889 SMESH::smIdType_array_var elemIDs = stdlGroup->GetIDs();
3890 const bool isElem = ( elemType != SMESH::NODE );
3891 CORBA::ULong iE = 0;
3892 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3893 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3895 if ( iE < elemIDs->length() )
3897 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3898 stdlGroup->Add( elemIDs );
3899 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3903 else if ( !geomGroup->_is_nil() )
3905 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3906 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3907 if ( newGeom->_is_nil() )
3909 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3910 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3915 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3918 else if ( !fltrGroup->_is_nil() )
3920 // replace geometry in a filter
3921 SMESH::Filter_var filter = fltrGroup->GetFilter();
3922 SMESH::Filter::Criteria_var criteria;
3923 filter->GetCriteria( criteria.out() );
3925 bool isMissingGroup = false;
3926 std::vector< std::string > badEntries;
3928 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3930 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3931 switch ( criteria[ iCr ].Type )
3933 case SMESH::FT_BelongToMeshGroup:
3935 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3936 btgg->SetGroupID( thresholdID );
3937 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3938 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3939 if ( refGroupSO->_is_nil() )
3941 CORBA::String_var refID = refGroupSO->GetID();
3942 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3943 if ( o2nID == old2newGroupMap.end() )
3945 isMissingGroup = true; // corresponding new group not yet created
3948 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3950 if ( o2nID->second.empty() ) // new referred group is invalid
3951 badEntries.push_back( refID.in() );
3954 case SMESH::FT_BelongToGeom:
3955 case SMESH::FT_BelongToPlane:
3956 case SMESH::FT_BelongToCylinder:
3957 case SMESH::FT_BelongToGenSurface:
3958 case SMESH::FT_LyingOnGeom:
3960 std::string newID = shapeMapper.FindNew( thresholdID );
3961 criteria[ iCr ].ThresholdID = newID.c_str();
3962 if ( newID.empty() )
3963 badEntries.push_back( thresholdID );
3966 case SMESH::FT_ConnectedElements:
3968 if ( thresholdID && thresholdID[0] )
3970 std::string newID = shapeMapper.FindNew( thresholdID );
3971 criteria[ iCr ].ThresholdID = newID.c_str();
3972 if ( newID.empty() )
3973 badEntries.push_back( thresholdID );
3979 } // loop on criteria
3981 if ( isMissingGroup && i < nbGroups )
3983 // to treat the group again
3984 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3988 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3989 newFilter->SetCriteria( criteria );
3991 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3992 newFilter->UnRegister();
3994 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3995 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3996 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3998 if ( isMissingGroup ) // all groups treated but a referred groups still not found
4000 invalidSObjects.push_back( ObjectToSObject( newGroup ));
4003 if ( !badEntries.empty() )
4006 } // treat a group on filter
4008 append( theNewGroups, newGroup );
4010 // fill old2newGroupMap
4011 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4012 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4013 if ( !srcSO->_is_nil() )
4015 CORBA::String_var srcID, newID("");
4016 srcID = srcSO->GetID();
4017 if ( !newSO->_is_nil() )
4018 newID = newSO->GetID();
4019 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4020 std::string( newID.in() )));
4023 if ( newGroup->_is_nil() )
4028 newMeshDS->CompactMesh();
4031 if ( !theMeshName || !theMeshName[0] )
4033 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4034 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4035 CORBA::String_var oldName = soOld->GetName();
4036 SetName( soNew, oldName.in(), "Mesh" );
4038 // mark invalid objects
4039 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4041 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4042 highLightInvalid( invalidSObjects[i].in(), true );
4045 << theNewMesh << ", "
4046 << theNewGroups << ", "
4047 << *theNewSubmeshes.ptr() << ", "
4048 << *theNewHypotheses.ptr() << ", "
4049 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4050 << theSourceMesh << ", "
4051 << theNewGeometry << ", "
4052 << "'" << theMeshName << "', "
4053 << theToCopyGroups << ", "
4054 << theToReuseHypotheses << ", "
4055 << theToCopyElements << " )";
4057 SMESH_CATCH( SMESH::throwCorbaException );
4062 //================================================================================
4064 * \brief Get version of MED format being used.
4066 //================================================================================
4068 char* SMESH_Gen_i::GetMEDFileVersion()
4070 MED::TInt majeur, mineur, release;
4071 majeur = mineur = release = 0;
4072 MED::GetVersionRelease(majeur, mineur, release);
4073 std::ostringstream version;
4074 version << majeur << "." << mineur << "." << release;
4075 return CORBA::string_dup( version.str().c_str() );
4078 //================================================================================
4080 * SMESH_Gen_i::GetMEDVersion
4082 * Get MED version of the file by its name
4084 //================================================================================
4086 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4088 std::string version = MED::GetMEDVersion( theFileName );
4089 return CORBA::string_dup( version.c_str() );
4092 //================================================================================
4094 * SMESH_Gen_i::CheckCompatibility
4096 * Check compatibility of file with MED format being used, read only.
4098 //================================================================================
4100 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4102 return MED::CheckCompatibility( theFileName );
4105 //================================================================================
4107 * SMESH_Gen_i::CheckWriteCompatibility
4109 * Check compatibility of file with MED format being used, for append on write.
4111 //================================================================================
4113 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4115 return MED::CheckCompatibility( theFileName, true );
4118 //================================================================================
4120 * SMESH_Gen_i::GetMeshNames
4122 * Get names of meshes defined in file with the specified name
4124 //================================================================================
4125 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4128 SMESH::string_array_var aResult = new SMESH::string_array();
4129 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4131 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4133 aResult->length( aNbMeshes );
4134 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4135 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4136 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4139 return aResult._retn();
4142 //=============================================================================
4146 * Save SMESH module's data
4148 //=============================================================================
4150 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4155 Kernel_Utils::Localizer loc;
4157 if (!myStudyContext)
4160 // Store study contents as a set of python commands
4163 SALOMEDS::Study_var aStudy = getStudyServant();
4165 // Declare a byte stream
4166 SALOMEDS::TMPFile_var aStreamFile;
4168 // Obtain a temporary dir
4169 TCollection_AsciiString tmpDir =
4170 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4172 // Create a sequence of files processed
4173 SALOMEDS_Tool::ListOfFiles aFileSeq;
4174 aFileSeq.reserve( NUM_TMP_FILES );
4176 TCollection_AsciiString aStudyName( "" );
4178 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4180 // Set names of temporary files
4181 TCollection_AsciiString filename =
4182 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4183 TCollection_AsciiString meshfile =
4184 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4185 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4186 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4187 filename = tmpDir + filename;
4188 meshfile = tmpDir + meshfile;
4191 HDFdataset* aDataset;
4192 HDFgroup* aTopGroup;
4194 HDFgroup* aSubGroup;
4195 HDFgroup* aSubSubGroup;
4196 hdf_size aSize[ 1 ];
4199 //Remove the files if they exist: BugID: 11225
4200 #ifndef WIN32 /* unix functionality */
4201 TCollection_AsciiString cmd("rm -f \"");
4203 TCollection_AsciiString cmd("del /F \"");
4213 system(cmd.ToCString());
4215 // MED writer to be used by storage process
4216 DriverMED_W_SMESHDS_Mesh myWriter;
4217 myWriter.SetFile( meshfile.ToCString() );
4220 // SetStoreName() to groups before storing hypotheses to let them refer to
4221 // groups using "store name", which is "Group <group_persistent_id>"
4223 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4224 for ( ; itBig->More(); itBig->Next() ) {
4225 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4226 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4227 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4228 if ( !CORBA::is_nil( anObject ) ) {
4229 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4230 if ( !myMesh->_is_nil() ) {
4231 myMesh->Load(); // load from study file if not yet done
4232 TPythonDump pd; // not to dump GetGroups()
4233 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4234 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4236 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4239 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4240 int anId = myStudyContext->findId( string( objStr.in() ) );
4242 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4243 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4244 aGrpBaseDS->SetStoreName( grpName );
4254 // ---> create HDF file
4255 aFile = new HDFfile( (char*) filename.ToCString() );
4256 aFile->CreateOnDisk();
4258 // --> iterator for top-level objects
4259 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4260 for ( ; itBig->More(); itBig->Next() ) {
4261 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4263 // --> hypotheses root branch (only one for the study)
4264 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4265 // create hypotheses root HDF group
4266 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4267 aTopGroup->CreateOnDisk();
4269 // iterator for all hypotheses
4270 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4271 for ( ; it->More(); it->Next() ) {
4272 SALOMEDS::SObject_wrap mySObject = it->Value();
4273 CORBA::Object_var anObject = SObjectToObject( mySObject );
4274 if ( !CORBA::is_nil( anObject ) ) {
4275 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4276 if ( !myHyp->_is_nil() ) {
4277 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4279 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4280 std::string hypname = hn.in();
4281 std::string libname = ln.in();
4283 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4284 // WIN32 and ".so" for X-system) must be deleted
4285 int libname_len = libname.length();
4287 if( libname_len > 4 )
4288 libname.resize( libname_len - 4 );
4290 // PAL17753 (Regression: missing hypothesis in restored study)
4291 // "lib" also should be removed from the beginning
4292 if( libname_len > 6 )
4293 libname = libname.substr( 3, libname_len - 3 - 3 );
4295 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4296 CORBA::String_var hypdata = myImpl->SaveTo();
4297 int id = myStudyContext->findId( string( objStr.in() ));
4299 // for each hypothesis create HDF group basing on its id
4300 char hypGrpName[30];
4301 sprintf( hypGrpName, "Hypothesis %d", id );
4302 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4303 aGroup->CreateOnDisk();
4304 // --> type name of hypothesis
4305 aSize[ 0 ] = hypname.length() + 1;
4306 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4307 aDataset->CreateOnDisk();
4308 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4309 aDataset->CloseOnDisk();
4310 // --> server plugin library name of hypothesis
4311 aSize[ 0 ] = libname.length() + 1;
4312 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4313 aDataset->CreateOnDisk();
4314 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4315 aDataset->CloseOnDisk();
4316 // --> persistent data of hypothesis
4317 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4318 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4319 aDataset->CreateOnDisk();
4320 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4321 aDataset->CloseOnDisk();
4322 // close hypothesis HDF group
4323 aGroup->CloseOnDisk();
4328 // close hypotheses root HDF group
4329 aTopGroup->CloseOnDisk();
4331 // --> algorithms root branch (only one for the study)
4332 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4333 // create algorithms root HDF group
4334 aTopGroup = new HDFgroup( "Algorithms", aFile );
4335 aTopGroup->CreateOnDisk();
4337 // iterator for all algorithms
4338 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4339 for ( ; it->More(); it->Next() ) {
4340 SALOMEDS::SObject_wrap mySObject = it->Value();
4341 CORBA::Object_var anObject = SObjectToObject( mySObject );
4342 if ( !CORBA::is_nil( anObject ) ) {
4343 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4344 if ( !myHyp->_is_nil() ) {
4345 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4347 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4348 std::string hypname = hn.in();
4349 std::string libname = ln.in();
4351 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4352 // WIN32 and ".so" for X-system) must be deleted
4353 int libname_len = libname.length();
4355 if( libname_len > 4 )
4356 libname.resize( libname_len - 4 );
4358 // PAL17753 (Regression: missing hypothesis in restored study)
4359 // "lib" also should be removed from the beginning
4360 if( libname_len > 6 )
4361 libname = libname.substr( 3, libname_len - 3 - 3 );
4363 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4364 CORBA::String_var hypdata = myImpl->SaveTo();
4365 int id = myStudyContext->findId( string( objStr.in() ) );
4367 // for each algorithm create HDF group basing on its id
4368 char hypGrpName[30];
4369 sprintf( hypGrpName, "Algorithm %d", id );
4370 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4371 aGroup->CreateOnDisk();
4372 // --> type name of algorithm
4373 aSize[0] = hypname.length() + 1;
4374 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4375 aDataset->CreateOnDisk();
4376 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4377 aDataset->CloseOnDisk();
4378 // --> server plugin library name of hypothesis
4379 aSize[0] = libname.length() + 1;
4380 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4381 aDataset->CreateOnDisk();
4382 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4383 aDataset->CloseOnDisk();
4384 // --> persistent data of algorithm
4385 aSize[0] = strlen( hypdata.in() ) + 1;
4386 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4387 aDataset->CreateOnDisk();
4388 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4389 aDataset->CloseOnDisk();
4390 // close algorithm HDF group
4391 aGroup->CloseOnDisk();
4396 // close algorithms root HDF group
4397 aTopGroup->CloseOnDisk();
4399 // --> mesh objects roots branches
4400 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4401 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4402 if ( !CORBA::is_nil( anObject ) ) {
4403 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4404 if ( !myMesh->_is_nil() ) {
4405 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4407 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4408 int id = myStudyContext->findId( string( objStr.in() ) );
4409 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4410 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4411 bool hasShape = myLocMesh.HasShapeToMesh();
4413 // for each mesh open the HDF group basing on its id
4414 char meshGrpName[ 30 ];
4415 sprintf( meshGrpName, "Mesh %d", id );
4416 aTopGroup = new HDFgroup( meshGrpName, aFile );
4417 aTopGroup->CreateOnDisk();
4419 // --> put dataset to hdf file which is a flag that mesh has data
4420 string strHasData = "0";
4421 // check if the mesh is not empty
4422 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4423 // write mesh data to med file
4424 myWriter.SetMesh( mySMESHDSMesh );
4425 myWriter.SetMeshId( id );
4428 aSize[ 0 ] = strHasData.length() + 1;
4429 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4430 aDataset->CreateOnDisk();
4431 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4432 aDataset->CloseOnDisk();
4435 // for each mesh open the HDF group basing on its auto color parameter
4436 char meshAutoColorName[ 30 ];
4437 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4439 anAutoColor[0] = myImpl->GetAutoColor();
4441 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4442 aDataset->CreateOnDisk();
4443 aDataset->WriteOnDisk( anAutoColor );
4444 aDataset->CloseOnDisk();
4446 // issue 0020693. Store _isModified flag
4447 int isModified = myLocMesh.GetIsModified();
4449 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4450 aDataset->CreateOnDisk();
4451 aDataset->WriteOnDisk( &isModified );
4452 aDataset->CloseOnDisk();
4454 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4455 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4457 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4458 aDataset->CreateOnDisk();
4459 aDataset->WriteOnDisk( &meshPersistentId );
4460 aDataset->CloseOnDisk();
4462 // Store SMESH_Mesh_i::_mainShapeTick
4463 int shapeTick = myImpl->MainShapeTick();
4465 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4466 aDataset->CreateOnDisk();
4467 aDataset->WriteOnDisk( &shapeTick );
4468 aDataset->CloseOnDisk();
4470 // write reference on a shape if exists
4471 SALOMEDS::SObject_wrap myRef;
4472 bool shapeRefFound = false;
4473 bool found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnShapeTag(), myRef.inout() );
4475 SALOMEDS::SObject_wrap myShape;
4476 bool ok = myRef->ReferencedObject( myShape.inout() );
4478 CORBA::Object_var shapeObj = myShape->GetObject();
4479 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4480 CORBA::String_var myRefOnObject = myShape->GetID();
4481 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4482 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4483 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4484 aDataset->CreateOnDisk();
4485 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4486 aDataset->CloseOnDisk();
4492 std::string info = myImpl->FileInfoToString();
4493 if ( !info.empty() )
4495 aSize[ 0 ] = info.size();
4496 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4497 aDataset->CreateOnDisk();
4498 aDataset->WriteOnDisk( (char*) info.data() );
4499 aDataset->CloseOnDisk();
4502 // write applied hypotheses if exist
4503 SALOMEDS::SObject_wrap myHypBranch;
4504 found = gotBranch->FindSubObject( (CORBA::Long)GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4505 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4506 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4508 if ( found && (shapeRefFound || !hasShape) ) {
4509 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4510 aGroup->CreateOnDisk();
4512 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4514 for ( ; it->More(); it->Next() ) {
4515 SALOMEDS::SObject_wrap mySObject = it->Value();
4516 SALOMEDS::SObject_wrap myRefOnHyp;
4517 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4519 // san - it is impossible to recover applied hypotheses
4520 // using their entries within Load() method,
4521 // for there are no AttributeIORs in the study when Load() is working.
4522 // Hence, it is better to store persistent IDs of hypotheses as references to them
4524 //string myRefOnObject = myRefOnHyp->GetID();
4525 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4526 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4527 int id = myStudyContext->findId( string( objStr.in() ) );
4528 //if ( myRefOnObject.length() > 0 ) {
4529 //aSize[ 0 ] = myRefOnObject.length() + 1;
4530 char hypName[ 30 ], hypId[ 30 ];
4531 sprintf( hypName, "Hyp %d", ++hypNb );
4532 sprintf( hypId, "%d", id );
4533 aSize[ 0 ] = strlen( hypId ) + 1;
4534 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4535 aDataset->CreateOnDisk();
4536 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4537 aDataset->WriteOnDisk( hypId );
4538 aDataset->CloseOnDisk();
4542 aGroup->CloseOnDisk();
4545 // write applied algorithms if exist
4546 SALOMEDS::SObject_wrap myAlgoBranch;
4547 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4548 myAlgoBranch.inout() );
4549 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4550 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4552 if ( found && (shapeRefFound || !hasShape)) {
4553 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4554 aGroup->CreateOnDisk();
4556 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4558 for ( ; it->More(); it->Next() ) {
4559 SALOMEDS::SObject_wrap mySObject = it->Value();
4560 SALOMEDS::SObject_wrap myRefOnAlgo;
4561 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4563 // san - it is impossible to recover applied algorithms
4564 // using their entries within Load() method,
4565 // for there are no AttributeIORs in the study when Load() is working.
4566 // Hence, it is better to store persistent IDs of algorithms as references to them
4568 //string myRefOnObject = myRefOnAlgo->GetID();
4569 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4570 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4571 int id = myStudyContext->findId( string( objStr.in() ) );
4572 //if ( myRefOnObject.length() > 0 ) {
4573 //aSize[ 0 ] = myRefOnObject.length() + 1;
4574 char algoName[ 30 ], algoId[ 30 ];
4575 sprintf( algoName, "Algo %d", ++algoNb );
4576 sprintf( algoId, "%d", id );
4577 aSize[ 0 ] = strlen( algoId ) + 1;
4578 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4579 aDataset->CreateOnDisk();
4580 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4581 aDataset->WriteOnDisk( algoId );
4582 aDataset->CloseOnDisk();
4586 aGroup->CloseOnDisk();
4589 // --> submesh objects sub-branches
4591 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4592 SALOMEDS::SObject_wrap mySubmeshBranch;
4593 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4595 if ( found ) // check if there is shape reference in submeshes
4597 bool hasShapeRef = false;
4598 SALOMEDS::ChildIterator_wrap itSM =
4599 aStudy->NewChildIterator( mySubmeshBranch );
4600 for ( ; itSM->More(); itSM->Next() ) {
4601 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4602 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4603 mySubRef->ReferencedObject( myShape.inout() );
4604 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4607 { // remove one submesh
4608 if ( shapeRefFound )
4609 { // unassign hypothesis
4610 SMESH::SMESH_subMesh_var mySubMesh =
4611 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4612 if ( !mySubMesh->_is_nil() ) {
4613 int shapeID = mySubMesh->GetId();
4614 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4615 const list<const SMESHDS_Hypothesis*>& hypList =
4616 mySMESHDSMesh->GetHypothesis( S );
4617 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4618 while ( hyp != hypList.end() ) {
4619 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4620 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4624 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4626 } // loop on submeshes of a type
4627 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4628 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4631 } // end check if there is shape reference in submeshes
4633 char name_meshgroup[ 30 ];
4634 if ( i == GetSubMeshOnVertexTag() )
4635 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4636 else if ( i == GetSubMeshOnEdgeTag() )
4637 strcpy( name_meshgroup, "SubMeshes On Edge" );
4638 else if ( i == GetSubMeshOnWireTag() )
4639 strcpy( name_meshgroup, "SubMeshes On Wire" );
4640 else if ( i == GetSubMeshOnFaceTag() )
4641 strcpy( name_meshgroup, "SubMeshes On Face" );
4642 else if ( i == GetSubMeshOnShellTag() )
4643 strcpy( name_meshgroup, "SubMeshes On Shell" );
4644 else if ( i == GetSubMeshOnSolidTag() )
4645 strcpy( name_meshgroup, "SubMeshes On Solid" );
4646 else if ( i == GetSubMeshOnCompoundTag() )
4647 strcpy( name_meshgroup, "SubMeshes On Compound" );
4649 // for each type of submeshes create container HDF group
4650 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4651 aGroup->CreateOnDisk();
4653 // iterator for all submeshes of given type
4654 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4655 for ( ; itSM->More(); itSM->Next() ) {
4656 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4657 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4658 if ( !CORBA::is_nil( anSubObject ))
4660 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4661 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4662 int subid = myStudyContext->findId( string( objStr.in() ) );
4664 // for each mesh open the HDF group basing on its id
4665 char submeshGrpName[ 30 ];
4666 sprintf( submeshGrpName, "SubMesh %d", subid );
4667 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4668 aSubGroup->CreateOnDisk();
4670 // write reference on a shape, already checked if it exists
4671 SALOMEDS::SObject_wrap mySubRef, myShape;
4672 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4673 mySubRef->ReferencedObject( myShape.inout() );
4674 string myRefOnObject = myShape->GetID();
4675 if ( myRefOnObject.length() > 0 ) {
4676 aSize[ 0 ] = myRefOnObject.length() + 1;
4677 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4678 aDataset->CreateOnDisk();
4679 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4680 aDataset->CloseOnDisk();
4683 // write applied hypotheses if exist
4684 SALOMEDS::SObject_wrap mySubHypBranch;
4685 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4686 mySubHypBranch.inout() );
4688 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4689 aSubSubGroup->CreateOnDisk();
4691 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4693 for ( ; it->More(); it->Next() ) {
4694 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4695 SALOMEDS::SObject_wrap myRefOnHyp;
4696 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4698 //string myRefOnObject = myRefOnHyp->GetID();
4699 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4700 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4701 int id = myStudyContext->findId( string( objStr.in() ) );
4702 //if ( myRefOnObject.length() > 0 ) {
4703 //aSize[ 0 ] = myRefOnObject.length() + 1;
4704 char hypName[ 30 ], hypId[ 30 ];
4705 sprintf( hypName, "Hyp %d", ++hypNb );
4706 sprintf( hypId, "%d", id );
4707 aSize[ 0 ] = strlen( hypId ) + 1;
4708 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4709 aDataset->CreateOnDisk();
4710 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4711 aDataset->WriteOnDisk( hypId );
4712 aDataset->CloseOnDisk();
4716 aSubSubGroup->CloseOnDisk();
4719 // write applied algorithms if exist
4720 SALOMEDS::SObject_wrap mySubAlgoBranch;
4721 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4722 mySubAlgoBranch.inout() );
4724 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4725 aSubSubGroup->CreateOnDisk();
4727 SALOMEDS::ChildIterator_wrap it =
4728 aStudy->NewChildIterator( mySubAlgoBranch );
4730 for ( ; it->More(); it->Next() ) {
4731 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4732 SALOMEDS::SObject_wrap myRefOnAlgo;
4733 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4735 //string myRefOnObject = myRefOnAlgo->GetID();
4736 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4737 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4738 int id = myStudyContext->findId( string( objStr.in() ) );
4739 //if ( myRefOnObject.length() > 0 ) {
4740 //aSize[ 0 ] = myRefOnObject.length() + 1;
4741 char algoName[ 30 ], algoId[ 30 ];
4742 sprintf( algoName, "Algo %d", ++algoNb );
4743 sprintf( algoId, "%d", id );
4744 aSize[ 0 ] = strlen( algoId ) + 1;
4745 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4746 aDataset->CreateOnDisk();
4747 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4748 aDataset->WriteOnDisk( algoId );
4749 aDataset->CloseOnDisk();
4753 aSubSubGroup->CloseOnDisk();
4755 // close submesh HDF group
4756 aSubGroup->CloseOnDisk();
4759 // close container of submeshes by type HDF group
4760 aGroup->CloseOnDisk();
4764 // store submesh order if any
4765 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4766 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4767 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4768 char order_list[ 30 ];
4769 strcpy( order_list, "Mesh Order" );
4770 // count number of submesh ids
4772 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4773 for ( ; idIt != theOrderIds.end(); idIt++ )
4774 nbIDs += (*idIt).size();
4775 // number of values = number of IDs +
4776 // number of lists (for separators) - 1
4777 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4778 idIt = theOrderIds.begin();
4779 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4780 const TListOfInt& idList = *idIt;
4781 if (idIt != theOrderIds.begin()) // not first list
4782 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4783 // dump submesh ids from current list
4784 TListOfInt::const_iterator id_smId = idList.begin();
4785 for( ; id_smId != idList.end(); id_smId++ )
4786 smIDs[ i++ ] = *id_smId;
4789 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4791 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4792 aDataset->CreateOnDisk();
4793 aDataset->WriteOnDisk( smIDs );
4794 aDataset->CloseOnDisk();
4798 if ( !theOrderIds.empty() && isNewOrederVersion )
4800 // convert ids to entries
4801 std::list< std::list< std::string > > orderEntryLists;
4802 for ( const TListOfInt& idList : theOrderIds )
4804 orderEntryLists.emplace_back();
4805 std::list< std::string > & entryList = orderEntryLists.back();
4806 for ( const int& id : idList )
4808 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4809 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4810 SALOMEDS::SObject_var so = ObjectToSObject( go );
4811 if ( !so->_is_nil() )
4813 CORBA::String_var entry = so->GetID();
4814 entryList.emplace_back( entry.in() );
4818 // convert orderEntryLists to string
4819 std::ostringstream ostream;
4820 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4821 std::string orderEntryString = ostream.str();
4824 aSize[ 0 ] = orderEntryString.size() + 1;
4825 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4826 aDataset->CreateOnDisk();
4827 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4828 aDataset->CloseOnDisk();
4831 // groups root sub-branch
4832 SALOMEDS::SObject_wrap myGroupsBranch;
4833 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4834 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4836 char name_group[ 30 ];
4837 if ( i == GetNodeGroupsTag() )
4838 strcpy( name_group, "Groups of Nodes" );
4839 else if ( i == GetEdgeGroupsTag() )
4840 strcpy( name_group, "Groups of Edges" );
4841 else if ( i == GetFaceGroupsTag() )
4842 strcpy( name_group, "Groups of Faces" );
4843 else if ( i == GetVolumeGroupsTag() )
4844 strcpy( name_group, "Groups of Volumes" );
4845 else if ( i == Get0DElementsGroupsTag() )
4846 strcpy( name_group, "Groups of 0D Elements" );
4847 else if ( i == GetBallElementsGroupsTag() )
4848 strcpy( name_group, "Groups of Balls" );
4850 aGroup = new HDFgroup( name_group, aTopGroup );
4851 aGroup->CreateOnDisk();
4853 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4854 for ( ; it->More(); it->Next() ) {
4855 SALOMEDS::SObject_wrap mySObject = it->Value();
4856 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4857 if ( !CORBA::is_nil( aSubObject ) ) {
4858 SMESH_GroupBase_i* myGroupImpl =
4859 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4862 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4866 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4867 int anId = myStudyContext->findId( string( objStr.in() ) );
4869 // For each group, create a dataset named "Group <group_persistent_id>"
4870 // and store the group's user name into it
4871 const char* grpName = aGrpBaseDS->GetStoreName();
4872 CORBA::String_var aUserName = myGroupImpl->GetName();
4873 aSize[ 0 ] = strlen( aUserName ) + 1;
4875 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4876 aDataset->CreateOnDisk();
4877 aDataset->WriteOnDisk( aUserName );
4878 aDataset->CloseOnDisk();
4881 // For each group, create a dataset named "Group <group_persistent_id> Color"
4882 // and store the group's color into it
4883 char grpColorName[ 30 ];
4884 sprintf( grpColorName, "ColorGroup %d", anId );
4885 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4887 anRGB[ 0 ] = aColor.R;
4888 anRGB[ 1 ] = aColor.G;
4889 anRGB[ 2 ] = aColor.B;
4891 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4892 aDataset->CreateOnDisk();
4893 aDataset->WriteOnDisk( anRGB );
4894 aDataset->CloseOnDisk();
4896 // Pass SMESHDS_Group to MED writer
4897 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4899 myWriter.AddGroup( aGrpDS );
4901 // write reference on a shape if exists
4902 SMESHDS_GroupOnGeom* aGeomGrp =
4903 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4905 SALOMEDS::SObject_wrap mySubRef, myShape;
4906 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4907 mySubRef->ReferencedObject( myShape.inout() ) &&
4908 !CORBA::is_nil( myShape->GetObject() ))
4910 CORBA::String_var myRefOnObject = myShape->GetID();
4911 if ( myRefOnObject.in()[0] ) {
4912 char aRefName[ 30 ];
4913 sprintf( aRefName, "Ref on shape %d", anId);
4914 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4915 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4916 aDataset->CreateOnDisk();
4917 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4918 aDataset->CloseOnDisk();
4921 else // shape ref is invalid:
4923 // save a group on geometry as ordinary group
4924 myWriter.AddGroup( aGeomGrp );
4927 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4928 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4930 std::string str = aFilterGrp_i->FilterToString();
4931 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4932 aSize[ 0 ] = str.length() + 1;
4933 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4934 aDataset->CreateOnDisk();
4935 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4936 aDataset->CloseOnDisk();
4940 aGroup->CloseOnDisk();
4944 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4946 // Flush current mesh information into MED file
4949 // save info on nb of elements
4950 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4952 // maybe a shape was deleted in the study
4953 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4954 TopoDS_Shape nullShape;
4955 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4958 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4963 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4964 aGroup->CreateOnDisk();
4966 // each element belongs to one or none submesh,
4967 // so for each node/element, we store a submesh ID
4969 // Store submesh IDs
4970 for ( int isNode = 0; isNode < 2; ++isNode )
4972 SMDS_ElemIteratorPtr eIt =
4973 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4974 smIdType nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4977 std::vector<int> smIDs; smIDs.reserve( nbElems );
4978 while ( eIt->more() )
4979 if ( const SMDS_MeshElement* e = eIt->next())
4980 smIDs.push_back( e->getshapeId() );
4982 aSize[ 0 ] = nbElems;
4983 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4984 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4985 aDataset->CreateOnDisk();
4986 aDataset->WriteOnDisk( & smIDs[0] );
4987 aDataset->CloseOnDisk();
4990 aGroup->CloseOnDisk();
4992 // Store node positions on sub-shapes (SMDS_Position):
4993 // ----------------------------------------------------
4995 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4996 aGroup->CreateOnDisk();
4998 // in aGroup, create 5 datasets to contain:
4999 // "Nodes on Edges" - ID of node on edge
5000 // "Edge positions" - U parameter on node on edge
5001 // "Nodes on Faces" - ID of node on face
5002 // "Face U positions" - U parameter of node on face
5003 // "Face V positions" - V parameter of node on face
5005 // Find out nb of nodes on edges and faces
5006 // Collect corresponding sub-meshes
5007 int nbEdgeNodes = 0, nbFaceNodes = 0;
5008 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5009 // loop on SMESHDS_SubMesh'es
5010 while ( smIt->more() )
5012 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5013 if ( aSubMesh->IsComplexSubmesh() )
5014 continue; // submesh containing other submeshs
5015 smIdType nbNodes = aSubMesh->NbNodes();
5016 if ( nbNodes == 0 ) continue;
5018 int aShapeID = aSubMesh->GetID();
5019 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5021 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5022 // write only SMDS_FacePosition and SMDS_EdgePosition
5023 switch ( aShapeType ) {
5025 nbFaceNodes += nbNodes;
5026 aFaceSM.push_back( aSubMesh );
5029 nbEdgeNodes += nbNodes;
5030 aEdgeSM.push_back( aSubMesh );
5036 // Treat positions on edges or faces
5037 for ( int onFace = 0; onFace < 2; onFace++ )
5039 // Create arrays to store in datasets
5040 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5041 if (!nbNodes) continue;
5042 int* aNodeIDs = new int [ nbNodes ];
5043 double* aUPos = new double [ nbNodes ];
5044 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5047 // loop on sub-meshes
5048 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5049 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5050 for ( ; itSM != pListSM->end(); itSM++ )
5052 SMESHDS_SubMesh* aSubMesh = (*itSM);
5054 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5055 // loop on nodes in aSubMesh
5056 while ( itNode->more() )
5059 const SMDS_MeshNode* node = itNode->next();
5060 aNodeIDs [ iNode ] = node->GetID();
5063 const SMDS_PositionPtr pos = node->GetPosition();
5064 if ( onFace ) { // on FACE
5065 SMDS_FacePositionPtr fPos = pos;
5067 aUPos[ iNode ] = fPos->GetUParameter();
5068 aVPos[ iNode ] = fPos->GetVParameter();
5075 SMDS_EdgePositionPtr ePos = pos;
5077 aUPos[ iNode ] = ePos->GetUParameter();
5083 } // loop on nodes in aSubMesh
5084 } // loop on sub-meshes
5089 aSize[ 0 ] = nbNodes;
5091 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5092 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5093 aDataset->CreateOnDisk();
5094 aDataset->WriteOnDisk( aNodeIDs );
5095 aDataset->CloseOnDisk();
5098 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5099 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5100 aDataset->CreateOnDisk();
5101 aDataset->WriteOnDisk( aUPos );
5102 aDataset->CloseOnDisk();
5105 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5106 aDataset->CreateOnDisk();
5107 aDataset->WriteOnDisk( aVPos );
5108 aDataset->CloseOnDisk();
5113 if ( aVPos ) delete [] aVPos;
5115 } // treat positions on edges or faces
5117 // close "Node Positions" group
5118 aGroup->CloseOnDisk();
5120 } // if ( there are submeshes in SMESHDS_Mesh )
5123 // close mesh HDF group
5124 aTopGroup->CloseOnDisk();
5132 aFile->CloseOnDisk();
5135 // Convert temporary files to stream
5136 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5138 // Remove temporary files and directory
5140 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5142 return aStreamFile._retn();
5145 //=============================================================================
5147 * SMESH_Gen_i::SaveASCII
5149 * Save SMESH module's data in ASCII format
5151 //=============================================================================
5153 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5155 bool isMultiFile ) {
5156 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5157 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5158 return aStreamFile._retn();
5160 //after usual saving needs to encipher binary to text string
5161 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5162 int size = aStreamFile.in().length();
5163 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5164 for ( int i = 0; i < size; i++ )
5165 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5167 buffer[size * 3] = '\0';
5169 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5171 return anAsciiStreamFile._retn();
5174 //=============================================================================
5178 * Load SMESH module's data
5180 //=============================================================================
5182 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5183 const SALOMEDS::TMPFile& theStream,
5187 UpdateStudy(); // load geom data
5188 Kernel_Utils::Localizer loc;
5190 SALOMEDS::Study_var aStudy = getStudyServant();
5192 // Get temporary files location
5193 TCollection_AsciiString tmpDir =
5194 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5196 // Convert the stream into sequence of files to process
5197 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5200 TCollection_AsciiString aStudyName( "" );
5201 if ( isMultiFile ) {
5202 CORBA::WString_var url = aStudy->URL();
5203 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5205 // Set names of temporary files
5206 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5207 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5211 HDFdataset* aDataset;
5212 HDFgroup* aTopGroup;
5214 HDFgroup* aSubGroup;
5215 HDFgroup* aSubSubGroup;
5218 // ---> open HDF file
5219 aFile = new HDFfile( (char*) filename.ToCString() );
5221 aFile->OpenOnDisk( HDF_RDONLY );
5223 catch ( HDFexception ) {
5224 INFOS( "Load(): " << filename << " not found!" );
5228 TPythonDump pd; // prevent dump during loading
5230 // For PAL13473 ("Repetitive mesh") implementation.
5231 // New dependencies between SMESH objects are established:
5232 // now hypotheses can refer to meshes, shapes and other hypotheses.
5233 // To keep data consistent, the following order of data restoration
5235 // 1. Create hypotheses
5236 // 2. Create all meshes
5237 // 3. Load hypotheses' data
5240 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5241 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5242 list< SMESH::Filter_var > filters;
5244 // get total number of top-level groups
5245 int aNbGroups = aFile->nInternalObjects();
5246 if ( aNbGroups > 0 ) {
5247 // --> in first turn we should read&create hypotheses
5248 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5249 // open hypotheses root HDF group
5250 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5251 aTopGroup->OpenOnDisk();
5253 // get number of hypotheses
5254 int aNbObjects = aTopGroup->nInternalObjects();
5255 for ( int j = 0; j < aNbObjects; j++ ) {
5256 // try to identify hypothesis
5257 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5258 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5260 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5261 // open hypothesis group
5262 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5263 aGroup->OpenOnDisk();
5265 // --> get hypothesis id
5266 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5271 // get number of datasets
5272 int aNbSubObjects = aGroup->nInternalObjects();
5273 for ( int k = 0; k < aNbSubObjects; k++ ) {
5275 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5276 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5277 // --> get hypothesis name
5278 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5279 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5280 aDataset->OpenOnDisk();
5281 size = aDataset->GetSize();
5282 char* hypname_str = new char[ size ];
5283 aDataset->ReadFromDisk( hypname_str );
5284 hypname = string( hypname_str );
5285 delete [] hypname_str;
5286 aDataset->CloseOnDisk();
5288 // --> get hypothesis plugin library name
5289 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5290 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5291 aDataset->OpenOnDisk();
5292 size = aDataset->GetSize();
5293 char* libname_str = new char[ size ];
5294 aDataset->ReadFromDisk( libname_str );
5295 if(MYDEBUG) SCRUTE( libname_str );
5296 libname = string( libname_str );
5297 delete [] libname_str;
5298 aDataset->CloseOnDisk();
5300 // --> get hypothesis data
5301 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5302 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5303 aDataset->OpenOnDisk();
5304 size = aDataset->GetSize();
5305 char* hypdata_str = new char[ size ];
5306 aDataset->ReadFromDisk( hypdata_str );
5307 hypdata = string( hypdata_str );
5308 delete [] hypdata_str;
5309 aDataset->CloseOnDisk();
5312 // close hypothesis HDF group
5313 aGroup->CloseOnDisk();
5315 // --> restore hypothesis from data
5316 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5317 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5318 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5319 SMESH::SMESH_Hypothesis_var myHyp;
5321 try { // protect persistence mechanism against exceptions
5322 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5325 INFOS( "Exception during hypothesis creation" );
5328 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5330 // myImpl->LoadFrom( hypdata.c_str() );
5331 hypDataList.push_back( make_pair( myImpl, hypdata ));
5332 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5333 int newId = myStudyContext->findId( iorString.in() );
5334 myStudyContext->mapOldToNew( id, newId );
5337 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5341 // close hypotheses root HDF group
5342 aTopGroup->CloseOnDisk();
5346 // --> then we should read&create algorithms
5347 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5348 // open algorithms root HDF group
5349 aTopGroup = new HDFgroup( "Algorithms", aFile );
5350 aTopGroup->OpenOnDisk();
5352 // get number of algorithms
5353 int aNbObjects = aTopGroup->nInternalObjects();
5354 for ( int j = 0; j < aNbObjects; j++ ) {
5355 // try to identify algorithm
5356 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5357 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5359 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5360 // open algorithm group
5361 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5362 aGroup->OpenOnDisk();
5364 // --> get algorithm id
5365 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5370 // get number of datasets
5371 int aNbSubObjects = aGroup->nInternalObjects();
5372 for ( int k = 0; k < aNbSubObjects; k++ ) {
5374 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5375 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5376 // --> get algorithm name
5377 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5378 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5379 aDataset->OpenOnDisk();
5380 size = aDataset->GetSize();
5381 char* hypname_str = new char[ size ];
5382 aDataset->ReadFromDisk( hypname_str );
5383 hypname = string( hypname_str );
5384 delete [] hypname_str;
5385 aDataset->CloseOnDisk();
5387 // --> get algorithm plugin library name
5388 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5389 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5390 aDataset->OpenOnDisk();
5391 size = aDataset->GetSize();
5392 char* libname_str = new char[ size ];
5393 aDataset->ReadFromDisk( libname_str );
5394 if(MYDEBUG) SCRUTE( libname_str );
5395 libname = string( libname_str );
5396 delete [] libname_str;
5397 aDataset->CloseOnDisk();
5399 // --> get algorithm data
5400 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5401 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5402 aDataset->OpenOnDisk();
5403 size = aDataset->GetSize();
5404 char* hypdata_str = new char[ size ];
5405 aDataset->ReadFromDisk( hypdata_str );
5406 if(MYDEBUG) SCRUTE( hypdata_str );
5407 hypdata = string( hypdata_str );
5408 delete [] hypdata_str;
5409 aDataset->CloseOnDisk();
5412 // close algorithm HDF group
5413 aGroup->CloseOnDisk();
5415 // --> restore algorithm from data
5416 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5417 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5418 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5419 SMESH::SMESH_Hypothesis_var myHyp;
5421 try { // protect persistence mechanism against exceptions
5422 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5424 catch( SALOME::SALOME_Exception& ex )
5426 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5429 INFOS( "Exception during hypothesis creation" );
5432 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5434 //myImpl->LoadFrom( hypdata.c_str() );
5435 hypDataList.push_back( make_pair( myImpl, hypdata ));
5436 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5437 int newId = myStudyContext->findId( iorString.in() );
5438 myStudyContext->mapOldToNew( id, newId );
5441 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5445 // close algorithms root HDF group
5446 aTopGroup->CloseOnDisk();
5450 // --> the rest groups should be meshes
5451 for ( int i = 0; i < aNbGroups; i++ ) {
5452 // identify next group
5453 char meshName[ HDF_NAME_MAX_LEN+1 ];
5454 aFile->InternalObjectIndentify( i, meshName );
5456 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5458 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5462 // open mesh HDF group
5463 aTopGroup = new HDFgroup( meshName, aFile );
5464 aTopGroup->OpenOnDisk();
5466 // get number of child HDF objects
5467 int aNbObjects = aTopGroup->nInternalObjects();
5468 if ( aNbObjects > 0 ) {
5470 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5471 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5472 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5473 if ( !myNewMeshImpl )
5475 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5477 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5478 int newId = myStudyContext->findId( iorString.in() );
5479 myStudyContext->mapOldToNew( id, newId );
5482 // try to read and set auto color flag
5483 char aMeshAutoColorName[ 30 ];
5484 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5485 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5487 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5488 aDataset->OpenOnDisk();
5489 size = aDataset->GetSize();
5490 int* anAutoColor = new int[ size ];
5491 aDataset->ReadFromDisk( anAutoColor );
5492 aDataset->CloseOnDisk();
5493 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5494 delete [] anAutoColor;
5497 // try to read and set reference to shape
5498 GEOM::GEOM_Object_var aShapeObject;
5499 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5500 // load mesh "Ref on shape" - it's an entry to SObject
5501 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5502 aDataset->OpenOnDisk();
5503 size = aDataset->GetSize();
5504 char* refFromFile = new char[ size ];
5505 aDataset->ReadFromDisk( refFromFile );
5506 aDataset->CloseOnDisk();
5507 if ( strlen( refFromFile ) > 0 ) {
5508 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5509 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5510 if ( !CORBA::is_nil( shapeObject ) ) {
5511 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5512 if ( !aShapeObject->_is_nil() )
5513 myNewMeshImpl->SetShape( aShapeObject );
5516 delete [] refFromFile;
5519 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5520 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5522 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5523 aDataset->OpenOnDisk();
5524 size = aDataset->GetSize();
5525 int* meshPersistentId = new int[ size ];
5526 aDataset->ReadFromDisk( meshPersistentId );
5527 aDataset->CloseOnDisk();
5528 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5529 delete [] meshPersistentId;
5532 // Restore SMESH_Mesh_i::_mainShapeTick
5533 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5535 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5536 aDataset->OpenOnDisk();
5537 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5538 aDataset->ReadFromDisk( shapeTick );
5539 aDataset->CloseOnDisk();
5542 // Restore file info
5543 if ( aTopGroup->ExistInternalObject( "file info" ))
5545 aDataset = new HDFdataset( "file info", aTopGroup );
5546 aDataset->OpenOnDisk();
5547 size = aDataset->GetSize();
5548 std::string info( size, ' ');
5549 aDataset->ReadFromDisk( (char*) info.data() );
5550 aDataset->CloseOnDisk();
5551 myNewMeshImpl->FileInfoFromString( info );
5557 // As all object that can be referred by hypothesis are created,
5558 // we can restore hypothesis data
5560 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5561 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5563 SMESH_Hypothesis_i* hyp = hyp_data->first;
5564 string & data = hyp_data->second;
5565 hyp->LoadFrom( data.c_str() );
5568 // Restore the rest mesh data
5570 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5571 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5573 aTopGroup = meshi_group->second;
5574 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5576 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5577 bool hasData = false;
5580 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5581 int newId = myStudyContext->findId( iorString.in() );
5582 int meshOldId = myStudyContext->getOldId( newId );
5584 // try to find mesh data dataset
5585 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5586 // load mesh "has data" flag
5587 aDataset = new HDFdataset( "Has data", aTopGroup );
5588 aDataset->OpenOnDisk();
5589 size = aDataset->GetSize();
5590 char* strHasData = new char[ size ];
5591 aDataset->ReadFromDisk( strHasData );
5592 aDataset->CloseOnDisk();
5593 if ( strcmp( strHasData, "1") == 0 ) {
5596 delete [] strHasData;
5599 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5600 // nodes and elements are not yet put into sub-meshes)
5601 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5602 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5603 aGroup->OpenOnDisk();
5604 // get number of applied algorithms
5605 int aNbSubObjects = aGroup->nInternalObjects();
5606 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5607 for ( int j = 0; j < aNbSubObjects; j++ ) {
5608 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5609 aGroup->InternalObjectIndentify( j, name_dataset );
5610 // check if it is an algorithm
5611 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5612 aDataset = new HDFdataset( name_dataset, aGroup );
5613 aDataset->OpenOnDisk();
5614 size = aDataset->GetSize();
5615 char* refFromFile = new char[ size ];
5616 aDataset->ReadFromDisk( refFromFile );
5617 aDataset->CloseOnDisk();
5618 // san - it is impossible to recover applied algorithms using their entries within Load() method
5619 int id = atoi( refFromFile );
5620 delete [] refFromFile;
5621 string anIOR = myStudyContext->getIORbyOldId( id );
5622 if ( !anIOR.empty() ) {
5623 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5624 if ( !CORBA::is_nil( hypObject ) ) {
5625 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5626 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5627 || !myNewMeshImpl->HasShapeToMesh()) )
5628 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5633 aGroup->CloseOnDisk();
5636 // try to get applied hypotheses
5637 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5638 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5639 aGroup->OpenOnDisk();
5640 // get number of applied hypotheses
5641 int aNbSubObjects = aGroup->nInternalObjects();
5642 for ( int j = 0; j < aNbSubObjects; j++ ) {
5643 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5644 aGroup->InternalObjectIndentify( j, name_dataset );
5645 // check if it is a hypothesis
5646 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5647 aDataset = new HDFdataset( name_dataset, aGroup );
5648 aDataset->OpenOnDisk();
5649 size = aDataset->GetSize();
5650 char* refFromFile = new char[ size ];
5651 aDataset->ReadFromDisk( refFromFile );
5652 aDataset->CloseOnDisk();
5653 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5654 int id = atoi( refFromFile );
5655 delete [] refFromFile;
5656 string anIOR = myStudyContext->getIORbyOldId( id );
5657 if ( !anIOR.empty() ) {
5658 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5659 if ( !CORBA::is_nil( hypObject ) ) {
5660 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5661 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5662 || !myNewMeshImpl->HasShapeToMesh()) )
5663 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5668 aGroup->CloseOnDisk();
5671 // --> try to find SUB-MESHES containers for each type of submesh
5672 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5673 const char* name_meshgroup = 0;
5674 if ( j == GetSubMeshOnVertexTag() )
5675 name_meshgroup = "SubMeshes On Vertex";
5676 else if ( j == GetSubMeshOnEdgeTag() )
5677 name_meshgroup = "SubMeshes On Edge";
5678 else if ( j == GetSubMeshOnWireTag() )
5679 name_meshgroup = "SubMeshes On Wire";
5680 else if ( j == GetSubMeshOnFaceTag() )
5681 name_meshgroup = "SubMeshes On Face";
5682 else if ( j == GetSubMeshOnShellTag() )
5683 name_meshgroup = "SubMeshes On Shell";
5684 else if ( j == GetSubMeshOnSolidTag() )
5685 name_meshgroup = "SubMeshes On Solid";
5686 else if ( j == GetSubMeshOnCompoundTag() )
5687 name_meshgroup = "SubMeshes On Compound";
5689 // try to get submeshes container HDF group
5690 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5691 // open submeshes containers HDF group
5692 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5693 aGroup->OpenOnDisk();
5695 // get number of submeshes
5696 int aNbSubMeshes = aGroup->nInternalObjects();
5697 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5699 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5700 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5701 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5702 // --> get submesh id
5703 int subid = atoi( name_submeshgroup + 7 );
5706 // open submesh HDF group
5707 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5708 aSubGroup->OpenOnDisk();
5710 // try to read and set reference to subshape
5711 GEOM::GEOM_Object_var aSubShapeObject;
5712 SMESH::SMESH_subMesh_var aSubMesh;
5714 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5715 // load submesh "Ref on shape" - it's an entry to SObject
5716 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5717 aDataset->OpenOnDisk();
5718 size = aDataset->GetSize();
5719 char* refFromFile = new char[ size ];
5720 aDataset->ReadFromDisk( refFromFile );
5721 aDataset->CloseOnDisk();
5722 if ( strlen( refFromFile ) > 0 ) {
5723 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5724 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5725 if ( !CORBA::is_nil( subShapeObject ) ) {
5726 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5727 if ( !aSubShapeObject->_is_nil() )
5728 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5729 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5730 if ( aSubMesh->_is_nil() )
5732 string iorSubString = GetORB()->object_to_string( aSubMesh );
5733 int newSubId = myStudyContext->findId( iorSubString );
5734 myStudyContext->mapOldToNew( subid, newSubId );
5737 delete [] refFromFile;
5740 if ( aSubMesh->_is_nil() )
5743 // try to get applied algorithms
5744 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5745 // open "applied algorithms" HDF group
5746 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5747 aSubSubGroup->OpenOnDisk();
5748 // get number of applied algorithms
5749 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5750 for ( int l = 0; l < aNbSubObjects; l++ ) {
5751 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5752 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5753 // check if it is an algorithm
5754 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5755 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5756 aDataset->OpenOnDisk();
5757 size = aDataset->GetSize();
5758 char* refFromFile = new char[ size ];
5759 aDataset->ReadFromDisk( refFromFile );
5760 aDataset->CloseOnDisk();
5762 int id = atoi( refFromFile );
5763 string anIOR = myStudyContext->getIORbyOldId( id );
5764 if ( !anIOR.empty() ) {
5765 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5766 if ( !CORBA::is_nil( hypObject ) ) {
5767 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5768 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5769 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5772 delete [] refFromFile;
5775 // close "applied algorithms" HDF group
5776 aSubSubGroup->CloseOnDisk();
5779 // try to get applied hypotheses
5780 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5781 // open "applied hypotheses" HDF group
5782 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5783 aSubSubGroup->OpenOnDisk();
5784 // get number of applied hypotheses
5785 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5786 for ( int l = 0; l < aNbSubObjects; l++ ) {
5787 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5788 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5789 // check if it is a hypothesis
5790 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5791 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5792 aDataset->OpenOnDisk();
5793 size = aDataset->GetSize();
5794 char* refFromFile = new char[ size ];
5795 aDataset->ReadFromDisk( refFromFile );
5796 aDataset->CloseOnDisk();
5798 int id = atoi( refFromFile );
5799 string anIOR = myStudyContext->getIORbyOldId( id );
5800 if ( !anIOR.empty() ) {
5801 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5802 if ( !CORBA::is_nil( hypObject ) ) {
5803 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5804 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5805 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5808 delete [] refFromFile;
5811 // close "APPLIED HYPOTHESES" hdf group
5812 aSubSubGroup->CloseOnDisk();
5815 // close SUB-MESH hdf group
5816 aSubGroup->CloseOnDisk();
5819 // close SUB-MESHES containers hdf group
5820 aGroup->CloseOnDisk();
5824 // try to get GROUPS
5825 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5826 char name_group[ 30 ];
5827 if ( ii == GetNodeGroupsTag() )
5828 strcpy( name_group, "Groups of Nodes" );
5829 else if ( ii == GetEdgeGroupsTag() )
5830 strcpy( name_group, "Groups of Edges" );
5831 else if ( ii == GetFaceGroupsTag() )
5832 strcpy( name_group, "Groups of Faces" );
5833 else if ( ii == GetVolumeGroupsTag() )
5834 strcpy( name_group, "Groups of Volumes" );
5835 else if ( ii == Get0DElementsGroupsTag() )
5836 strcpy( name_group, "Groups of 0D Elements" );
5837 else if ( ii == GetBallElementsGroupsTag() )
5838 strcpy( name_group, "Groups of Balls" );
5840 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5841 aGroup = new HDFgroup( name_group, aTopGroup );
5842 aGroup->OpenOnDisk();
5843 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5844 // within aGroup->ExistInternalObject( name )
5845 std::vector< std::string > subNames;
5846 TColStd_MapOfAsciiString mapOfNames;
5847 aGroup->GetAllObjects( subNames );
5848 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5849 mapOfNames.Add( subNames[ iN ].c_str() );
5851 for ( size_t j = 0; j < subNames.size(); j++ ) {
5852 const std::string& name_dataset = subNames[ j ];
5853 // check if it is a group
5854 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5857 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5860 int groupID = -1; // group local ID (also persistent)
5862 groupID = atoi( endptr + 1 );
5863 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5864 aDataset->OpenOnDisk();
5866 // Retrieve actual group name
5867 size = aDataset->GetSize();
5868 char* nameFromFile = new char[ size ];
5869 aDataset->ReadFromDisk( nameFromFile );
5870 aDataset->CloseOnDisk();
5872 // Try to find a shape reference
5873 TopoDS_Shape aShape;
5874 char aRefName[ 30 ];
5875 sprintf( aRefName, "Ref on shape %d", subid);
5876 if ( mapOfNames.Contains( aRefName ))
5878 // load mesh "Ref on shape" - it's an entry to SObject
5879 aDataset = new HDFdataset( aRefName, aGroup );
5880 aDataset->OpenOnDisk();
5881 size = aDataset->GetSize();
5882 char* refFromFile = new char[ size ];
5883 aDataset->ReadFromDisk( refFromFile );
5884 aDataset->CloseOnDisk();
5885 if ( strlen( refFromFile ) > 0 ) {
5886 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5887 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5888 if ( !CORBA::is_nil( shapeObject ) ) {
5889 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5890 if ( !aShapeObject->_is_nil() )
5891 aShape = GeomObjectToShape( aShapeObject );
5894 delete [] refFromFile;
5896 // Try to read a filter of SMESH_GroupOnFilter
5897 SMESH::Filter_var filter;
5898 SMESH_PredicatePtr predicate;
5899 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5900 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5902 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5903 aDataset->OpenOnDisk();
5904 size = aDataset->GetSize();
5905 char* persistStr = new char[ size ];
5906 aDataset->ReadFromDisk( persistStr );
5907 aDataset->CloseOnDisk();
5908 if ( strlen( persistStr ) > 0 ) {
5909 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5910 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5911 filters.push_back( filter );
5913 delete [] persistStr;
5916 // Create group servant
5917 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5918 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5919 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5920 delete [] nameFromFile;
5921 // Obtain a SMESHDS_Group object
5922 if ( aNewGroup->_is_nil() )
5925 string iorSubString = GetORB()->object_to_string( aNewGroup );
5926 int newSubId = myStudyContext->findId( iorSubString );
5927 myStudyContext->mapOldToNew( subid, newSubId );
5929 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5933 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5934 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5936 aFilterGroup->SetFilter( filter );
5937 filter->UnRegister();
5939 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5940 if ( !aGroupBaseDS )
5943 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5946 // Read color of the group
5947 char aGroupColorName[ 30 ];
5948 sprintf( aGroupColorName, "ColorGroup %d", subid);
5949 if ( mapOfNames.Contains( aGroupColorName ))
5951 aDataset = new HDFdataset( aGroupColorName, aGroup );
5952 aDataset->OpenOnDisk();
5953 size = aDataset->GetSize();
5954 double* anRGB = new double[ size ];
5955 aDataset->ReadFromDisk( anRGB );
5956 aDataset->CloseOnDisk();
5957 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5958 aGroupBaseDS->SetColor( aColor );
5963 aGroup->CloseOnDisk();
5967 // instead of reading mesh data, we read only brief information of all
5968 // objects: mesh, groups, sub-meshes (issue 0021208)
5971 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5972 meshfile.ToCString(), filename.ToCString(),
5976 // read Sub-Mesh ORDER if any
5977 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
5978 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5979 aDataset->OpenOnDisk();
5980 size = aDataset->GetSize();
5981 int* smIDs = new int[ size ];
5982 aDataset->ReadFromDisk( smIDs );
5983 aDataset->CloseOnDisk();
5984 TListOfListOfInt anOrderIds;
5985 anOrderIds.push_back( TListOfInt() );
5986 for ( int i = 0; i < size; i++ )
5987 if ( smIDs[ i ] < 0 ) // is separator
5988 anOrderIds.push_back( TListOfInt() );
5990 anOrderIds.back().push_back(smIDs[ i ]);
5992 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5995 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
5997 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
5998 aDataset->OpenOnDisk();
5999 size = aDataset->GetSize();
6000 std::string dataString; dataString.resize( size );
6001 aDataset->ReadFromDisk((char*) dataString.data() );
6002 aDataset->CloseOnDisk();
6004 std::istringstream istream( dataString.data() );
6005 boost::archive::text_iarchive archive( istream );
6006 std::list< std::list< std::string > > orderEntryLists;
6008 archive >> orderEntryLists;
6012 TListOfListOfInt anOrderIds;
6013 for ( const std::list< std::string >& entryList : orderEntryLists )
6015 anOrderIds.emplace_back();
6016 for ( const std::string & entry : entryList )
6018 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6019 TopoDS_Shape shape = GeomObjectToShape( go );
6020 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6021 anOrderIds.back().emplace_back( sm->GetId() );
6024 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6028 // update hyps needing full mesh data restored (issue 20918)
6029 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6031 SMESH_Hypothesis_i* hyp = hyp_data->first;
6032 hyp->UpdateAsMeshesRestored();
6035 // notify algos on completed restoration to set sub-mesh event listeners
6036 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6038 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6039 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6041 TopoDS_Shape myLocShape;
6042 if(myLocMesh.HasShapeToMesh())
6043 myLocShape = myLocMesh.GetShapeToMesh();
6045 myLocShape = SMESH_Mesh::PseudoShape();
6047 myLocMesh.GetSubMesh(myLocShape)->
6048 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6051 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6052 list< SMESH::Filter_var >::iterator f = filters.begin();
6053 for ( ; f != filters.end(); ++f )
6054 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6055 fi->FindBaseObjects();
6060 aTopGroup->CloseOnDisk();
6063 aFile->CloseOnDisk();
6066 // Remove temporary files created from the stream
6069 SMESH_File meshFile( meshfile.ToCString() );
6070 if ( !meshFile ) // no meshfile exists
6072 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6076 Engines::Container_var container = GetContainerRef();
6077 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6079 container_i->registerTemporaryFile( filename.ToCString() );
6080 container_i->registerTemporaryFile( meshfile.ToCString() );
6081 container_i->registerTemporaryFile( tmpDir.ToCString() );
6086 // creation of tree nodes for all data objects in the study
6087 // to support tree representation customization and drag-n-drop:
6088 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6089 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6090 useCaseBuilder->SetRootCurrent();
6091 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6092 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6093 for (it->InitEx(true); it->More(); it->Next()) {
6094 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6101 //=============================================================================
6103 * SMESH_Gen_i::LoadASCII
6105 * Load SMESH module's data in ASCII format
6107 //=============================================================================
6109 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6110 const SALOMEDS::TMPFile& theStream,
6112 bool isMultiFile ) {
6113 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6114 return Load( theComponent, theStream, theURL, isMultiFile );
6116 //before call main ::Load method it's need for decipher text format to
6117 //binary ( "|xx" => x' )
6118 int size = theStream.length();
6119 if ( int((size / 3 )*3) != size ) //error size of buffer
6122 int real_size = int(size / 3);
6124 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6127 unsigned int c = -1;
6128 for ( int i = 0; i < real_size; i++ )
6130 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6131 sscanf( tmp, "%x", &c );
6132 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6135 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6137 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6140 //=============================================================================
6142 * SMESH_Gen_i::Close
6144 * Clears study-connected data when it is closed
6146 //=============================================================================
6148 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6150 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6152 // Clear study contexts data
6153 myStudyContext->Clear();
6155 // remove the tmp files meshes are loaded from
6156 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6158 // Clean trace of API methods calls
6164 //=============================================================================
6166 * SMESH_Gen_i::ComponentDataType
6168 * Get component data type
6170 //=============================================================================
6172 char* SMESH_Gen_i::ComponentDataType()
6174 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6175 return CORBA::string_dup( "SMESH" );
6179 //=============================================================================
6181 * SMESH_Gen_i::IORToLocalPersistentID
6183 * Transform data from transient form to persistent
6185 //=============================================================================
6187 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6188 const char* IORString,
6189 CORBA::Boolean /*isMultiFile*/,
6190 CORBA::Boolean /*isASCII*/ )
6192 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6194 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6195 int anId = myStudyContext->findId( IORString );
6197 if(MYDEBUG) MESSAGE( "VSR " << anId )
6199 sprintf( strId, "%d", anId );
6200 return CORBA::string_dup( strId );
6203 return CORBA::string_dup( "" );
6206 //=============================================================================
6208 * SMESH_Gen_i::LocalPersistentIDToIOR
6210 * Transform data from persistent form to transient
6212 //=============================================================================
6214 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6215 const char* aLocalPersistentID,
6216 CORBA::Boolean /*isMultiFile*/,
6217 CORBA::Boolean /*isASCII*/ )
6219 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6221 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6222 int anId = atoi( aLocalPersistentID );
6223 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6225 return CORBA::string_dup( "" );
6228 //=======================================================================
6229 //function : RegisterObject
6231 //=======================================================================
6233 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6235 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6236 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6237 return myStudyContext->addObject( string( iorString.in() ) );
6242 //================================================================================
6244 * \brief Return id of registered object
6245 * \param theObject - the Object
6246 * \retval int - Object id
6248 //================================================================================
6250 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6252 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6253 string iorString = GetORB()->object_to_string( theObject );
6254 return myStudyContext->findId( iorString );
6259 //=============================================================================
6261 * SMESH_Gen_i::SetName
6263 * Set a new object name
6265 //=============================================================================
6267 void SMESH_Gen_i::SetName(const char* theIOR,
6268 const char* theName)
6270 if ( theIOR && strcmp( theIOR, "" ) ) {
6271 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6272 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6273 if ( !aSO->_is_nil() ) {
6274 SetName( aSO, theName );
6279 // Version information
6280 char* SMESH_Gen_i::getVersion()
6282 #if SMESH_DEVELOPMENT
6283 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6285 return CORBA::string_dup(SMESH_VERSION_STR);
6289 //=================================================================================
6290 // function : Move()
6291 // purpose : Moves objects to the specified position.
6292 // Is used in the drag-n-drop functionality.
6293 //=================================================================================
6295 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6296 SALOMEDS::SObject_ptr where,
6299 if ( CORBA::is_nil( where ) ) return;
6301 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6302 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6303 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6304 std::string dataType = father->ComponentDataType();
6305 if ( dataType != "SMESH" ) return; // not a SMESH component
6307 SALOMEDS::SObject_var objAfter;
6308 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6309 // insert at given row -> find insertion position
6310 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6312 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6313 if ( i == row && useCaseIt->More() ) {
6314 objAfter = useCaseIt->Value();
6318 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6319 SALOMEDS::SObject_var sobj = what[i];
6320 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6321 // insert the object to the use case tree
6322 if ( !CORBA::is_nil( objAfter ) )
6323 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6325 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6328 //================================================================================
6330 * \brief Returns true if algorithm can be used to mesh a given geometry
6331 * \param [in] theAlgoType - the algorithm type
6332 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6333 * \param [in] theGeomObject - the geometry to mesh
6334 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6335 * else, returns \c True if at least one shape is meshable
6336 * \return CORBA::Boolean - can or can't
6338 //================================================================================
6340 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6341 const char* theLibName,
6342 GEOM::GEOM_Object_ptr theGeomObject,
6343 CORBA::Boolean toCheckAll)
6347 std::string aPlatformLibName;
6348 GenericHypothesisCreator_i* aCreator =
6349 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6352 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6353 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6354 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6361 SMESH_CATCH( SMESH::doNothing );
6364 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6369 //================================================================================
6371 * \brief Collect indices of elements, which are located inside the sphere
6373 //================================================================================
6375 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6376 SMESH::ElementType theElemType,
6382 SMESH::long_array_var aResult = new SMESH::long_array();
6383 if ( meshPart->_is_nil() )
6384 return aResult._retn();
6386 // 1. Create geometrical object
6387 gp_Pnt aP( theX, theY, theZ );
6388 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6390 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6392 if ( lst.size() > 0 ) {
6393 aResult->length( lst.size() );
6394 for ( size_t i = 0; i < lst.size(); i++ ) {
6395 aResult[i] = lst[i];
6398 return aResult._retn();
6401 //================================================================================
6403 * \brief Collect indices of elements, which are located inside the box
6405 //================================================================================
6407 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6408 SMESH::ElementType theElemType,
6409 CORBA::Double theX1,
6410 CORBA::Double theY1,
6411 CORBA::Double theZ1,
6412 CORBA::Double theX2,
6413 CORBA::Double theY2,
6414 CORBA::Double theZ2)
6416 SMESH::long_array_var aResult = new SMESH::long_array();
6417 if( meshPart->_is_nil() )
6418 return aResult._retn();
6420 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6421 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6423 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6425 if( lst.size() > 0 ) {
6426 aResult->length( lst.size() );
6427 for ( size_t i = 0; i < lst.size(); i++ ) {
6428 aResult[i] = lst[i];
6431 return aResult._retn();
6434 //================================================================================
6436 * \brief Collect indices of elements, which are located inside the cylinder
6438 //================================================================================
6440 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6441 SMESH::ElementType theElemType,
6445 CORBA::Double theDX,
6446 CORBA::Double theDY,
6447 CORBA::Double theDZ,
6449 CORBA::Double theR )
6451 SMESH::long_array_var aResult = new SMESH::long_array();
6452 if( meshPart->_is_nil() )
6453 return aResult._retn();
6455 gp_Pnt aP( theX, theY, theZ );
6456 gp_Vec aV( theDX, theDY, theDZ );
6457 gp_Ax2 anAxes (aP, aV);
6459 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6461 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6463 if( lst.size() > 0 ) {
6464 aResult->length( lst.size() );
6465 for ( size_t i = 0; i < lst.size(); i++ ) {
6466 aResult[i] = lst[i];
6469 return aResult._retn();
6472 //================================================================================
6474 * \brief Collect indices of elements, which are located inside the geom object
6476 //================================================================================
6478 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6479 SMESH::ElementType theElemType,
6480 GEOM::GEOM_Object_ptr theGeom,
6481 CORBA::Double theTolerance )
6483 SMESH::long_array_var aResult = new SMESH::long_array();
6484 if( meshPart->_is_nil() || theGeom->_is_nil() )
6485 return aResult._retn();
6487 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6489 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6491 if( lst.size() > 0 ) {
6492 aResult->length( lst.size() );
6493 for ( size_t i = 0; i < lst.size(); i++ ) {
6494 aResult[i] = lst[i];
6497 return aResult._retn();
6500 //================================================================================
6502 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6504 //================================================================================
6506 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6507 SMESH::ElementType theElemType,
6508 const TopoDS_Shape& theShape,
6509 double* theTolerance) {
6511 std::vector<long> res;
6512 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6514 if ( mesh->_is_nil() )
6517 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6521 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6526 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6527 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6528 anElementsOnShape->SetAllNodes( true );
6529 anElementsOnShape->SetMesh( meshDS );
6530 anElementsOnShape->SetShape( theShape, aType );
6533 anElementsOnShape->SetTolerance(*theTolerance);
6535 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6536 if ( !msource->_is_nil() ) { // Mesh case
6537 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6539 while ( elemIt->more() ) {
6540 const SMDS_MeshElement* anElem = elemIt->next();
6541 long anId = anElem->GetID();
6542 if ( anElementsOnShape->IsSatisfy( anId ) )
6543 res.push_back( anId );
6547 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6548 if ( !gsource->_is_nil() ) {
6549 if(theElemType == SMESH::NODE) {
6550 SMESH::smIdType_array_var nodes = gsource->GetNodeIDs();
6551 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6552 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6553 long anId = node->GetID();
6554 if ( anElementsOnShape->IsSatisfy( anId ) )
6555 res.push_back( anId );
6558 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6559 SMESH::smIdType_array_var elems = gsource->GetListOfID();
6560 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6561 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6562 long anId = elem->GetID();
6563 if ( anElementsOnShape->IsSatisfy( anId ) )
6564 res.push_back( anId );
6569 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6570 if ( !smsource->_is_nil() ) {
6571 SMESH::smIdType_array_var elems = smsource->GetElementsByType( theElemType );
6572 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6573 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6575 long anId = elem->GetID();
6576 if ( anElementsOnShape->IsSatisfy( anId ) )
6577 res.push_back( anId );
6584 //=============================================================================
6586 * SMESHEngine_factory
6588 * C factory, accessible with dlsym, after dlopen
6590 //=============================================================================
6594 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6595 PortableServer::POA_ptr poa,
6596 PortableServer::ObjectId* contId,
6597 const char* instanceName,
6598 const char* interfaceName )
6600 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6601 if(MYDEBUG) SCRUTE(interfaceName);
6602 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6603 return aSMESHGen->getId() ;