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>
52 #include "SALOME_KernelServices.hxx"
59 #include <libgen.h> // for basename function
63 #define LibHandle HMODULE
64 #define LoadLib( name ) LoadLibrary( name )
65 #define GetProc GetProcAddress
66 #define UnLoadLib( handle ) FreeLibrary( handle );
68 #define LibHandle void*
70 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
71 #else // DYNLOAD_LOCAL
72 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
73 #endif // DYNLOAD_LOCAL
75 #define UnLoadLib( handle ) dlclose( handle );
78 #include "SMESH_Gen_i.hxx"
79 #include "SMESH_version.h"
81 #include "DriverMED_W_SMESHDS_Mesh.h"
82 #include "DriverMED_R_SMESHDS_Mesh.h"
84 #include "DriverCGNS_Read.hxx"
86 #include "MED_Factory.hxx"
87 #include "SMDS_EdgePosition.hxx"
88 #include "SMDS_FacePosition.hxx"
89 #include "SMDS_SetIterator.hxx"
90 #include "SMDS_SpacePosition.hxx"
91 #include "SMDS_VertexPosition.hxx"
92 #include "SMESHDS_Document.hxx"
93 #include "SMESHDS_Group.hxx"
94 #include "SMESHDS_GroupOnGeom.hxx"
95 #include "SMESH_Algo_i.hxx"
96 #include "SMESH_File.hxx"
97 #include "SMESH_Group.hxx"
98 #include "SMESH_Group_i.hxx"
99 #include "SMESH_Hypothesis.hxx"
100 #include "SMESH_Hypothesis_i.hxx"
101 #include "SMESH_Mesh.hxx"
102 #include "SMESH_MeshEditor.hxx"
103 #include "SMESH_Mesh_i.hxx"
104 #include "SMESH_PreMeshInfo.hxx"
105 #include "SMESH_PythonDump.hxx"
106 #include "SMESH_ControlsDef.hxx"
108 // to pass CORBA exception through SMESH_TRY
109 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
110 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
112 #include CORBA_SERVER_HEADER(SMESH_Group)
113 #include CORBA_SERVER_HEADER(SMESH_Filter)
114 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
117 #include <GEOMImpl_Types.hxx>
118 #include <GEOM_Client.hxx>
120 #include <Basics_Utils.hxx>
121 #include <Basics_DirUtils.hxx>
123 #include <OpUtil.hxx>
124 #include <SALOMEDS_Tool.hxx>
125 #include <SALOME_Container_i.hxx>
126 #include <SALOME_LifeCycleCORBA.hxx>
127 #include <SALOME_NamingService.hxx>
128 #include <Utils_CorbaException.hxx>
129 #include <Utils_ExceptHandlers.hxx>
130 #include <Utils_SINGLETON.hxx>
131 #include <utilities.h>
133 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
134 #include CORBA_CLIENT_HEADER(SALOME_Session)
136 // helpers about SALOME::GenericObj
137 #include <SALOMEDS_wrap.hxx>
138 #include <SALOMEDS_Attributes_wrap.hxx>
139 #include <GEOM_wrap.hxx>
148 #include <boost/archive/text_oarchive.hpp>
149 #include <boost/archive/text_iarchive.hpp>
150 #include <boost/serialization/list.hpp>
151 #include <boost/serialization/string.hpp>
154 using SMESH::TPythonDump;
157 #define NUM_TMP_FILES 2
160 static int MYDEBUG = 0;
162 static int MYDEBUG = 0;
165 // Static variables definition
166 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
167 CORBA::ORB_var SMESH_Gen_i::myOrb;
168 PortableServer::POA_var SMESH_Gen_i::myPoa;
169 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
170 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
171 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
174 const int nbElemPerDiagonal = 10;
176 //=============================================================================
178 * GetServant [ static ]
180 * Get servant of the CORBA object
182 //=============================================================================
184 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
186 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
189 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
192 catch (PortableServer::POA::ObjectNotActive &ex)
194 INFOS("GetServant: ObjectNotActive");
197 catch (PortableServer::POA::WrongAdapter &ex)
199 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
202 catch (PortableServer::POA::WrongPolicy &ex)
204 INFOS("GetServant: WrongPolicy");
209 INFOS( "GetServant - Unknown exception was caught!!!" );
214 //=============================================================================
216 * SObjectToObject [ static ]
218 * Get CORBA object corresponding to the SALOMEDS::SObject
220 //=============================================================================
222 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
224 SALOMEDS::GenericAttribute_wrap anAttr;
225 CORBA::Object_var anObj;
226 if ( !theSObject->_is_nil() ) {
228 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
229 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
230 CORBA::String_var aValue = anIOR->Value();
231 if( strcmp( aValue, "" ) != 0 )
232 anObj = GetORB()->string_to_object( aValue );
236 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
242 //=============================================================================
246 * Get SALOME_NamingService object
248 //=============================================================================
250 SALOME_NamingService* SMESH_Gen_i::GetNS()
252 if ( myNS == NULL ) {
253 myNS = SINGLETON_<SALOME_NamingService>::Instance();
254 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
255 myNS->init_orb( GetORB() );
260 //=============================================================================
264 * Get SALOME_LifeCycleCORBA object
266 //=============================================================================
268 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
270 if ( myLCC == NULL ) {
271 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
276 //=============================================================================
278 * GetGeomEngine [ static ]
280 * Get GEOM::GEOM_Gen reference
282 //=============================================================================
284 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( bool isShaper )
286 CORBA::Object_var temp = KERNEL::RetrieveCompo(isShaper ? "SHAPERSTUDY" : "GEOM");
287 myGeomGen = GEOM::GEOM_Gen::_narrow( temp );
291 //=============================================================================
293 * GetGeomEngine [ static ]
295 * Get GEOM::GEOM_Gen reference
297 //=============================================================================
299 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
301 GEOM::GEOM_Gen_ptr gen = GEOM::GEOM_Gen::_nil();
302 if ( !CORBA::is_nil( go ))
307 //=============================================================================
309 * SMESH_Gen_i::SMESH_Gen_i
311 * Default constructor: not for use
313 //=============================================================================
315 SMESH_Gen_i::SMESH_Gen_i()
319 //=============================================================================
321 * SMESH_Gen_i::SMESH_Gen_i
323 * Standard constructor, used with Container
325 //=============================================================================
327 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
328 PortableServer::POA_ptr poa,
329 PortableServer::ObjectId* contId,
330 const char* instanceName,
331 const char* interfaceName,
333 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName, false, checkNS )
336 myOrb = CORBA::ORB::_duplicate(orb);
337 myPoa = PortableServer::POA::_duplicate(poa);
340 _id = myPoa->activate_object( _thisObj );
342 myStudyContext = new StudyContext;
344 myIsEmbeddedMode = false;
345 myIsEnablePublish = true;
346 myShapeReader = NULL; // shape reader
348 myIsHistoricalPythonDump = true;
349 myToForgetMeshDataOnHypModif = false;
351 // set it in standalone mode only
352 //OSD::SetSignal( true );
354 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
355 // find out mode (embedded or standalone) here else
356 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
357 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
360 if ( SALOME_NamingService* ns = GetNS() )
362 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
363 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
364 if ( !session->_is_nil() )
366 CORBA::String_var str_host = session->getHostname();
367 CORBA::Long s_pid = session->getPID();
368 string my_host = Kernel_Utils::GetHostname();
370 long my_pid = (long)_getpid();
372 long my_pid = (long) getpid();
374 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
380 //=============================================================================
382 * SMESH_Gen_i::~SMESH_Gen_i
386 //=============================================================================
388 SMESH_Gen_i::~SMESH_Gen_i()
390 // delete hypothesis creators
391 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
392 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
394 // same creator can be mapped under different names
395 GenericHypothesisCreator_i* creator = (*itHyp).second;
399 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
400 if ( creator == (*itHyp2).second )
401 (*itHyp2).second = 0;
403 myHypCreatorMap.clear();
405 // Clear study contexts data
406 delete myStudyContext;
408 // delete shape reader
410 delete myShapeReader;
413 //=============================================================================
415 * SMESH_Gen_i::getHypothesisCreator
417 * Get hypothesis creator
419 //=============================================================================
421 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
422 const char* theLibName,
423 std::string& thePlatformLibName)
425 std::string aPlatformLibName;
426 /* It's Need to translate lib name for WIN32 or X platform */
427 if ( theLibName && theLibName[0] != '\0' )
429 int libNameLen = strlen(theLibName);
430 //check for old format "libXXXXXXX.so"
431 if (libNameLen > 7 &&
432 !strncmp( theLibName, "lib", 3 ) &&
433 !strcmp( theLibName+libNameLen-3, ".so" ))
437 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
438 #elif defined(__APPLE__)
439 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
441 aPlatformLibName = theLibName;
446 //try to use new format
448 aPlatformLibName = theLibName;
449 aPlatformLibName += ".dll";
450 #elif defined(__APPLE__)
451 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
453 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
457 thePlatformLibName = aPlatformLibName;
459 Unexpect aCatch(SALOME_SalomeException);
460 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
462 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
463 GenericHypothesisCreator_i* aCreator;
466 // check, if creator for this hypothesis type already exists
467 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
469 // load plugin library
470 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
473 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
475 const char* path = aPlatformLibName.c_str();
478 const char* path = aPlatformLibName.c_str();
480 LibHandle libHandle = LoadLib( path );
481 #if defined(WIN32) && defined(UNICODE)
486 // report any error, if occurred
488 const char* anError = dlerror();
489 throw(SALOME_Exception( anError ));
491 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
492 << aPlatformLibName));
496 // get method, returning hypothesis creator
497 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
498 GetHypothesisCreator procHandle =
499 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
502 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
503 << aPlatformLibName ));
504 UnLoadLib(libHandle);
507 // get hypothesis creator
508 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
509 aCreator = procHandle(theHypName);
512 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
513 << aPlatformLibName));
515 // map hypothesis creator to a hypothesis name
516 myHypCreatorMap[string(theHypName)] = aCreator;
521 return myHypCreatorMap[string(theHypName)];
524 catch (SALOME_Exception& S_ex)
526 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
531 //=============================================================================
533 * SMESH_Gen_i::createHypothesis
535 * Create hypothesis of given type
537 //=============================================================================
539 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
540 const char* theLibName)
542 SMESH_Hypothesis_i* myHypothesis_i = 0;
543 SMESH::SMESH_Hypothesis_var hypothesis_i;
544 std::string aPlatformLibName;
545 GenericHypothesisCreator_i* aCreator =
546 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
548 // create a new hypothesis object, store its ref. in studyContext
549 myHypothesis_i = aCreator->Create(myPoa, &myGen);
552 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
553 CORBA::String_var hypName = myHypothesis_i->GetName();
554 myHypCreatorMap[ hypName.in() ] = aCreator;
556 // activate the CORBA servant of hypothesis
557 hypothesis_i = myHypothesis_i->_this();
558 int nextId = RegisterObject( hypothesis_i );
559 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
560 else { (void)nextId; } // avoid "unused variable" warning in release mode
562 return hypothesis_i._retn();
565 //=============================================================================
567 * SMESH_Gen_i::createMesh
569 * Create empty mesh on shape
571 //=============================================================================
573 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
575 Unexpect aCatch(SALOME_SalomeException);
576 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
578 // Get or create the GEOM_Client instance
580 // create a new mesh object servant, store it in a map in study context
581 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
582 // create a new mesh object
583 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
584 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
586 // activate the CORBA servant of Mesh
587 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
588 int nextId = RegisterObject( mesh );
589 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
590 else { (void)nextId; } // avoid "unused variable" warning in release mode
593 catch (SALOME_Exception& S_ex) {
594 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
596 return SMESH::SMESH_Mesh::_nil();
599 //=============================================================================
601 * SMESH_Gen_i::GetShapeReader
605 //=============================================================================
607 GEOM_Client* SMESH_Gen_i::GetShapeReader()
609 // create shape reader if necessary
610 if ( !myShapeReader )
611 myShapeReader = new GEOM_Client(GetContainerRef());
612 ASSERT( myShapeReader );
613 return myShapeReader;
616 //=============================================================================
618 * SMESH_Gen_i::SetGeomEngine
620 * Set GEOM::GEOM_Gen reference
622 //=============================================================================
624 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
626 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
629 //=============================================================================
631 * SMESH_Gen_i::SetEmbeddedMode
635 //=============================================================================
637 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
639 myIsEmbeddedMode = theMode;
641 if ( !myIsEmbeddedMode ) {
642 //PAL10867: disable signals catching with "noexcepthandler" option
643 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
644 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
649 char* envDisableFPE = getenv("DISABLE_FPE");
650 if (envDisableFPE && atoi(envDisableFPE))
655 OSD::SetSignal( raiseFPE );
657 // else OSD::SetSignal() is called in GUI
661 //=============================================================================
663 * SMESH_Gen_i::IsEmbeddedMode
667 //=============================================================================
669 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
671 return myIsEmbeddedMode;
674 //=============================================================================
676 * SMESH_Gen_i::SetEnablePublish
678 * Set enable publishing in the study
680 //=============================================================================
682 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
684 myIsEnablePublish = theIsEnablePublish;
687 //=============================================================================
689 * SMESH_Gen_i::IsEnablePublish
691 * Check enable publishing
693 //=============================================================================
695 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
697 return myIsEnablePublish;
700 //=============================================================================
702 * SMESH_Gen_i::UpdateStudy
704 * Update study (needed at switching GEOM->SMESH)
706 //=============================================================================
708 void SMESH_Gen_i::UpdateStudy()
710 if ( !myStudyContext )
711 myStudyContext = new StudyContext;
713 SALOMEDS::Study_var aStudy = getStudyServant();
714 if ( !CORBA::is_nil( aStudy ) )
716 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
718 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
719 if( !GEOM_var->_is_nil() )
720 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
722 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
723 if( !GEOM_var->_is_nil() )
724 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
726 // NPAL16168, issue 0020210
727 // Let meshes update their data depending on GEOM groups that could change
728 CORBA::String_var compDataType = ComponentDataType();
729 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
730 if ( !me->_is_nil() ) {
731 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
732 for ( ; anIter->More(); anIter->Next() ) {
733 SALOMEDS::SObject_wrap so = anIter->Value();
734 CORBA::Object_var ior = SObjectToObject( so );
735 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
736 mesh->CheckGeomModif();
742 //================================================================================
744 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
746 //================================================================================
748 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
750 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
751 SALOMEDS::GenericAttribute_wrap attr;
752 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
754 SALOMEDS::AttributePixMap_wrap pm = attr;
755 CORBA::String_var ico = pm->GetPixMap();
756 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
761 //=================================================================================
762 // function : hasObjectInfo()
763 // purpose : shows if module provides information for its objects
764 //=================================================================================
766 bool SMESH_Gen_i::hasObjectInfo()
771 //=================================================================================
772 // function : getObjectInfo()
773 // purpose : returns an information for a given object by its entry
774 //=================================================================================
776 char* SMESH_Gen_i::getObjectInfo( const char* entry )
778 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
779 // for the rest, "module 'SMESH', ID=0:1:2:*"
783 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
784 CORBA::Object_var obj = SObjectToObject( so );
785 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
786 if ( isGeomModifIcon( mesh ))
788 txt << "The geometry was changed and the mesh needs to be recomputed";
793 CORBA::String_var compType = ComponentDataType();
794 txt << "module '" << compType << "', ID=" << entry;
796 return CORBA::string_dup( txt );
799 //=============================================================================
801 * SMESH_Gen_i::GetStudyContext
805 //=============================================================================
807 StudyContext* SMESH_Gen_i::GetStudyContext()
809 return myStudyContext;
812 //=============================================================================
814 * SMESH_Gen_i::CreateHypothesis
816 * Create hypothesis/algorithm of given type and publish it in the study
818 //=============================================================================
820 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
821 const char* theLibName )
823 Unexpect aCatch(SALOME_SalomeException);
824 // Create hypothesis/algorithm
825 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
827 // Publish hypothesis/algorithm in the study
828 if ( CanPublishInStudy( hyp ) ) {
829 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
830 if ( !aSO->_is_nil() ) {
831 // Update Python script
832 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
833 << theHypName << "', '" << theLibName << "')";
840 //================================================================================
842 * \brief Return a hypothesis initialized by given average length.
843 * \param theHypType - hypothesis type name
844 * \param theLibName - plugin library name
845 * \param theAverageLength - average length
846 * \param theQuadDominated - is quad-dominated flag
847 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
849 //================================================================================
851 SMESH::SMESH_Hypothesis_ptr
852 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
853 const char* theLibName,
854 CORBA::Double theAverageLength,
855 CORBA::Boolean theQuadDominated)
857 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
858 theAverageLength, theQuadDominated };
860 SMESH::SMESH_Hypothesis_var hyp =
861 GetHypothesisParameterValues( theHypType, theLibName,
862 SMESH::SMESH_Mesh::_nil(),
863 GEOM::GEOM_Object::_nil(),
865 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
867 TPythonDump() << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
868 << theHypType << "', '"
869 << theLibName << "', "
870 << theAverageLength << ", "
871 << theQuadDominated << " )";
876 //================================================================================
878 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
879 * existing on the given geometry or to size of the geometry.
880 * \param theHypType - hypothesis type name
881 * \param theLibName - plugin library name
882 * \param theMesh - The mesh of interest
883 * \param theGeom - The shape to get parameter values from
884 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
885 * in a study and used to compute the mesh, or a temporary one created just to pass
888 //================================================================================
890 SMESH::SMESH_Hypothesis_ptr
891 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
892 const char* theLibName,
893 SMESH::SMESH_Mesh_ptr theMesh,
894 GEOM::GEOM_Object_ptr theGeom,
895 const SMESH::HypInitParams& theParams)
897 Unexpect aCatch(SALOME_SalomeException);
899 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
900 if ( byMesh && CORBA::is_nil( theMesh ) )
901 return SMESH::SMESH_Hypothesis::_nil();
902 if ( byMesh && CORBA::is_nil( theGeom ) )
903 return SMESH::SMESH_Hypothesis::_nil();
905 // -----------------------------------------------
906 // find hypothesis used to mesh theGeom
907 // -----------------------------------------------
909 // get mesh and shape
910 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
911 TopoDS_Shape shape = GeomObjectToShape( theGeom );
912 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
913 return SMESH::SMESH_Hypothesis::_nil();
914 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
916 // create a temporary hypothesis to know its dimension
917 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
918 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
920 return SMESH::SMESH_Hypothesis::_nil();
921 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
924 // look for a hypothesis of theHypType used to mesh the shape
925 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
928 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
929 int nbLocalHyps = aHypList->length();
930 for ( int i = 0; i < nbLocalHyps; i++ ) {
931 CORBA::String_var hypName = aHypList[i]->GetName();
932 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
933 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
935 // check super shapes
936 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
937 while ( nbLocalHyps == 0 && itShape.More() ) {
938 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
939 if ( ! CORBA::is_nil( geomObj )) {
940 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
941 nbLocalHyps = aHypList->length();
942 for ( int i = 0; i < nbLocalHyps; i++ )
943 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
944 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
950 // let the temporary hypothesis find out somehow parameter values by mesh
951 if ( hyp->SetParametersByMesh( mesh, shape ))
952 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
956 ::SMESH_Hypothesis::TDefaults dflts;
957 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
958 dflts._nbSegments = myGen.GetDefaultNbSegments();
959 dflts._elemLength = theParams.averageLength;
960 dflts._quadDominated = theParams.quadDominated;
961 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
964 dflts._diagonal = mesh->GetShapeDiagonalSize();
966 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
967 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
968 dflts._shape = &shape;
971 // let the hypothesis initialize it's values
972 if ( hyp->SetParametersByDefaults( dflts, mesh ))
973 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
976 return SMESH::SMESH_Hypothesis::_nil();
979 //=============================================================================
981 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
982 * \param [in] theHyp - the hypothesis of interest
983 * \param [out] theMesh - the sole mesh using \a theHyp
984 * \param [out] theShape - the sole geometry \a theHyp is assigned to
985 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
987 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
988 * considered as SAME sub-mesh => result is \c true.
989 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
990 * a shape to which an hyp being edited is assigned.
992 //=============================================================================
994 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
995 SMESH::SMESH_Mesh_out theMesh,
996 GEOM::GEOM_Object_out theShape)
998 if ( CORBA::is_nil( theHyp ))
1001 // get Mesh component SO
1002 CORBA::String_var compDataType = ComponentDataType();
1003 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
1004 if ( CORBA::is_nil( comp ))
1007 // look for child SO of meshes
1008 SMESH::SMESH_Mesh_var foundMesh;
1009 TopoDS_Shape foundShape;
1011 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1012 for ( ; meshIter->More() && isSole; meshIter->Next() )
1014 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1015 CORBA::Object_var obj = SObjectToObject( curSO );
1016 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1020 // look for a sole shape where theHyp is assigned
1021 bool isHypFound = false;
1022 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1023 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1024 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1026 const THypList& hyps = s2hypsIt.Value();
1027 THypList::const_iterator h = hyps.begin();
1028 for ( ; h != hyps.end(); ++h )
1029 if ( (*h)->GetID() == theHyp->GetId() )
1031 if ( h != hyps.end()) // theHyp found
1034 if ( ! foundShape.IsNull() &&
1035 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1037 foundShape.Nullify();
1041 foundShape = s2hypsIt.Key();
1043 } // loop on assigned hyps
1045 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1047 if ( !foundMesh->_is_nil() ) // not a sole mesh
1049 if ( !foundMesh->HasShapeToMesh() ||
1050 !mesh_i ->HasShapeToMesh() )
1052 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1056 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1057 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1058 isSole = s1->IsSame( s2 );
1061 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1067 ! foundMesh->_is_nil() &&
1068 ! foundShape.IsNull() )
1070 theMesh = foundMesh._retn();
1071 theShape = ShapeToGeomObject( foundShape );
1072 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1077 //=============================================================================
1079 * Set number of segments per diagonal of boundary box of geometry by which
1080 * default segment length of appropriate 1D hypotheses is defined
1082 //=============================================================================
1084 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1086 if ( theNbSegments > 0 )
1087 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1089 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1092 //=============================================================================
1094 * \brief Set default number of segments per edge
1096 //=============================================================================
1098 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1100 if ( theNbSegments > 0 )
1101 myGen.SetDefaultNbSegments( int(theNbSegments) );
1103 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1106 //=============================================================================
1108 * Set an option value
1110 //=============================================================================
1112 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1114 if ( name && value && strlen( value ) > 0 )
1117 if ( strcmp(name, "historical_python_dump") == 0 )
1119 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1120 msgToGUI = "preferences/SMESH/historical_python_dump/";
1121 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1123 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1125 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1126 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1127 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1129 else if ( strcmp(name, "default_grp_color") == 0 )
1133 // color must be presented as a string of following form:
1134 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1135 str = str.substr(1);
1136 for ( size_t i = 0; i < str.length()/2; i++ )
1137 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1138 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1140 else if ( value ) { // rgb color ("255,170,0", for example)
1141 string tempValue( value );
1142 char* colorValue = strtok( &tempValue[0], "," );
1143 while ( colorValue != NULL ) {
1144 int c_value = atoi( colorValue );
1145 if ( c_value >= 0 && c_value <= 255 )
1146 color.push_back( c_value );
1147 colorValue = strtok( NULL, "," );
1150 if ( color.size() == 3 ) { // color must have three valid component
1151 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1152 myDefaultGroupColor = value;
1153 msgToGUI = "preferences/SMESH/default_grp_color/";
1158 // update preferences in case if SetOption() is invoked from python console
1159 if ( !msgToGUI.empty() )
1161 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1162 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1163 if ( !CORBA::is_nil( session ) )
1164 session->emitMessageOneWay(msgToGUI.c_str());
1169 //=============================================================================
1171 * Return an option value
1173 //=============================================================================
1175 char* SMESH_Gen_i::GetOption(const char* name)
1179 if ( strcmp(name, "historical_python_dump") == 0 )
1181 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1183 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1185 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1187 if ( strcmp(name, "default_grp_color") == 0 )
1189 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1192 return CORBA::string_dup( "" );
1195 //=============================================================================
1197 * SMESH_Gen_i::CreateMesh
1199 * Create empty mesh on a shape and publish it in the study
1201 //=============================================================================
1203 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1205 Unexpect aCatch(SALOME_SalomeException);
1206 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1208 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1210 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1211 ASSERT( meshServant );
1212 meshServant->SetShape( theShapeObject );
1214 // publish mesh in the study
1215 if ( CanPublishInStudy( mesh ) ) {
1216 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1217 aStudyBuilder->NewCommand(); // There is a transaction
1218 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1219 aStudyBuilder->CommitCommand();
1220 if ( !aSO->_is_nil() ) {
1221 // Update Python script
1222 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1226 return mesh._retn();
1229 //=============================================================================
1231 * SMESH_Gen_i::CreateEmptyMesh
1235 //=============================================================================
1237 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1239 Unexpect aCatch(SALOME_SalomeException);
1240 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1242 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1244 // publish mesh in the study
1245 if ( CanPublishInStudy( mesh ) ) {
1246 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1247 aStudyBuilder->NewCommand(); // There is a transaction
1248 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1249 aStudyBuilder->CommitCommand();
1250 if ( !aSO->_is_nil() ) {
1251 // Update Python script
1252 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1256 return mesh._retn();
1261 //================================================================================
1263 * \brief Throw an exception in case if the file can't be read
1265 //================================================================================
1267 void checkFileReadable( const char* theFileName )
1269 SMESH_File f ( theFileName );
1272 if ( !f.error().empty() )
1273 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1275 THROW_SALOME_CORBA_EXCEPTION
1276 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1277 SALOME::BAD_PARAM );
1282 //=============================================================================
1284 * SMESH_Gen_i::CreateMeshFromUNV
1286 * Create mesh and import data from UNV file
1288 //=============================================================================
1290 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1292 Unexpect aCatch(SALOME_SalomeException);
1294 checkFileReadable( theFileName );
1296 SMESH::SMESH_Mesh_var aMesh = createMesh();
1298 // publish mesh in the study
1299 if ( CanPublishInStudy( aMesh ) ) {
1300 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1301 aStudyBuilder->NewCommand(); // There is a transaction
1302 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1303 aStudyBuilder->CommitCommand();
1304 if ( !aSO->_is_nil() ) {
1305 // Update Python script
1306 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1310 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1312 aServant->ImportUNVFile( theFileName );
1314 // Dump creation of groups
1315 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1317 aServant->GetImpl().GetMeshDS()->Modified();
1318 return aMesh._retn();
1321 //=============================================================================
1323 * SMESH_Gen_i::CreateMeshFromMED
1325 * Create mesh and import data from MED file
1327 //=============================================================================
1329 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1330 SMESH::DriverMED_ReadStatus& theStatus,
1331 const char* theCommandNameForPython,
1332 const char* theFileNameForPython)
1335 char bname[ _MAX_FNAME ];
1336 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1337 string aFileName = bname;
1339 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1341 // Retrieve mesh names from the file
1342 DriverMED_R_SMESHDS_Mesh myReader;
1343 myReader.SetFile( theFileName );
1344 myReader.SetMeshId( -1 );
1345 Driver_Mesh::Status aStatus;
1346 list<string> aNames = myReader.GetMeshNames(aStatus);
1347 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1348 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1350 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1353 TPythonDump aPythonDump;
1354 aPythonDump << "([";
1356 if (theStatus == SMESH::DRS_OK) {
1357 SALOMEDS::StudyBuilder_var aStudyBuilder;
1358 aStudyBuilder = getStudyServant()->NewBuilder();
1359 aStudyBuilder->NewCommand(); // There is a transaction
1361 aResult->length( aNames.size() );
1364 // Iterate through all meshes and create mesh objects
1365 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1368 if (i > 0) aPythonDump << ", ";
1371 SMESH::SMESH_Mesh_var mesh = createMesh();
1373 // publish mesh in the study
1374 SALOMEDS::SObject_wrap aSO;
1375 if ( CanPublishInStudy( mesh ) )
1376 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1377 // - as names of meshes are stored in MED file, we use them for data publishing
1378 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1379 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1382 if ( !aSO->_is_nil() ) {
1385 aPythonDump << "mesh_" << i;
1388 // Read mesh data (groups are published automatically by ImportMEDFile())
1389 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1390 ASSERT( meshServant );
1391 SMESH::DriverMED_ReadStatus status1 =
1392 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1393 if (status1 > theStatus)
1394 theStatus = status1;
1396 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1397 meshServant->GetImpl().GetMeshDS()->Modified();
1399 if ( !aStudyBuilder->_is_nil() )
1400 aStudyBuilder->CommitCommand();
1403 // Update Python script
1404 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1406 // Dump creation of groups
1407 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1408 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1410 return aResult._retn();
1413 //================================================================================
1415 * \brief Create meshes by reading a MED file
1417 //================================================================================
1419 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1420 SMESH::DriverMED_ReadStatus& theStatus)
1422 Unexpect aCatch(SALOME_SalomeException);
1423 checkFileReadable( theFileName );
1425 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus,
1426 "CreateMeshesFromMED", theFileName);
1430 //=============================================================================
1432 * SMESH_Gen_i::CreateMeshFromSAUV
1434 * Create mesh and import data from SAUV file
1436 //=============================================================================
1438 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1439 SMESH::DriverMED_ReadStatus& theStatus)
1441 Unexpect aCatch(SALOME_SalomeException);
1442 checkFileReadable( theFileName );
1444 std::string sauvfilename(theFileName);
1445 std::string medfilename(theFileName);
1446 medfilename += ".med";
1449 cmd = "%PYTHONBIN% ";
1454 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1456 system(cmd.c_str());
1457 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(),
1459 "CreateMeshesFromSAUV",
1460 sauvfilename.c_str());
1462 cmd = "%PYTHONBIN% ";
1467 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1469 system(cmd.c_str());
1473 //=============================================================================
1475 * SMESH_Gen_i::CreateMeshFromSTL
1477 * Create mesh and import data from STL file
1479 //=============================================================================
1481 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1483 Unexpect aCatch(SALOME_SalomeException);
1484 checkFileReadable( theFileName );
1486 SMESH::SMESH_Mesh_var aMesh = createMesh();
1489 char bname[ _MAX_FNAME ];
1490 _splitpath( theFileName, NULL, NULL, bname, NULL );
1491 string aFileName = bname;
1493 string aFileName = basename( const_cast<char *>(theFileName) );
1495 // publish mesh in the study
1496 if ( CanPublishInStudy( aMesh ) ) {
1497 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1498 aStudyBuilder->NewCommand(); // There is a transaction
1499 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1500 aStudyBuilder->CommitCommand();
1501 if ( !aSO->_is_nil() ) {
1502 // Update Python script
1503 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1507 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1509 aServant->ImportSTLFile( theFileName );
1510 aServant->GetImpl().GetMeshDS()->Modified();
1511 return aMesh._retn();
1514 //================================================================================
1516 * \brief Create meshes and import data from the CGSN file
1518 //================================================================================
1520 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1521 SMESH::DriverMED_ReadStatus& theStatus)
1523 Unexpect aCatch(SALOME_SalomeException);
1524 checkFileReadable( theFileName );
1526 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1529 // Retrieve nb meshes from the file
1530 DriverCGNS_Read myReader;
1531 myReader.SetFile( theFileName );
1532 Driver_Mesh::Status aStatus;
1533 int nbMeshes = myReader.GetNbMeshes(aStatus);
1534 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1536 aResult->length( nbMeshes );
1538 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1541 TPythonDump aPythonDump;
1542 aPythonDump << "([";
1544 if (theStatus == SMESH::DRS_OK)
1546 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1547 aStudyBuilder->NewCommand(); // There is a transaction
1551 // Iterate through all meshes and create mesh objects
1552 for ( ; i < nbMeshes; ++i )
1555 if (i > 0) aPythonDump << ", ";
1558 SMESH::SMESH_Mesh_var mesh = createMesh();
1559 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1561 // Read mesh data (groups are published automatically by ImportMEDFile())
1562 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1563 ASSERT( meshServant );
1565 SMESH::DriverMED_ReadStatus status1 =
1566 meshServant->ImportCGNSFile( theFileName, i, meshName );
1567 if (status1 > theStatus)
1568 theStatus = status1;
1570 meshServant->GetImpl().GetMeshDS()->Modified();
1571 // publish mesh in the study
1572 SALOMEDS::SObject_wrap aSO;
1573 if ( CanPublishInStudy( mesh ) )
1574 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1577 if ( !aSO->_is_nil() ) {
1581 aPythonDump << "mesh_" << i;
1584 aStudyBuilder->CommitCommand();
1587 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1589 // Dump creation of groups
1590 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1591 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1593 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1596 return aResult._retn();
1599 //================================================================================
1601 * \brief Create a mesh and import data from a GMF file
1603 //================================================================================
1605 SMESH::SMESH_Mesh_ptr
1606 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1607 CORBA::Boolean theMakeRequiredGroups,
1608 SMESH::ComputeError_out theError)
1610 Unexpect aCatch(SALOME_SalomeException);
1611 checkFileReadable( theFileName );
1613 SMESH::SMESH_Mesh_var aMesh = createMesh();
1615 char bname[ _MAX_FNAME ];
1616 _splitpath( theFileName, NULL, NULL, bname, NULL );
1617 string aFileName = bname;
1619 string aFileName = basename( const_cast<char *>(theFileName) );
1621 // publish mesh in the study
1622 if ( CanPublishInStudy( aMesh ) ) {
1623 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1624 aStudyBuilder->NewCommand(); // There is a transaction
1625 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1626 aStudyBuilder->CommitCommand();
1627 if ( !aSO->_is_nil() ) {
1628 // Update Python script
1629 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1630 << theFileName << "', "
1631 << theMakeRequiredGroups << " )";
1634 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1636 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1637 aServant->GetImpl().GetMeshDS()->Modified();
1638 return aMesh._retn();
1642 //=============================================================================
1644 * SMESH_Gen_i::IsReadyToCompute
1646 * Return true if mesh contains enough data to be computed
1648 //=============================================================================
1650 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1651 GEOM::GEOM_Object_ptr theShapeObject )
1653 Unexpect aCatch(SALOME_SalomeException);
1654 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1656 if ( CORBA::is_nil( theShapeObject ) )
1657 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1658 SALOME::BAD_PARAM );
1659 if ( CORBA::is_nil( theMesh ) )
1660 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1661 SALOME::BAD_PARAM );
1664 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1665 ASSERT( meshServant );
1666 if ( meshServant ) {
1667 // get local TopoDS_Shape
1668 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1669 // call implementation
1670 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1671 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1674 catch ( SALOME_Exception& S_ex ) {
1675 INFOS( "catch exception "<< S_ex.what() );
1680 //================================================================================
1682 * \brief Find SObject for an algo
1684 //================================================================================
1686 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1689 SALOMEDS::Study_var aStudy = getStudyServant();
1690 if ( !aStudy->_is_nil() ) {
1691 // find algo in the study
1692 CORBA::String_var compDataType = ComponentDataType();
1693 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1694 if ( !father->_is_nil() ) {
1695 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1696 for ( ; itBig->More(); itBig->Next() ) {
1697 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1698 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1699 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1700 for ( ; algoIt->More(); algoIt->Next() ) {
1701 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1702 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1703 if ( !CORBA::is_nil( algoIOR )) {
1704 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1705 if ( impl && impl->GetImpl() == algo )
1706 return algoSO._retn();
1708 } // loop on algo SO's
1711 } // SMESH component iterator
1715 return SALOMEDS::SObject::_nil();
1718 //================================================================================
1720 * \brief Return errors of mesh computation
1722 //================================================================================
1724 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1725 GEOM::GEOM_Object_ptr theSubObject )
1727 Unexpect aCatch(SALOME_SalomeException);
1728 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1730 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1731 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1733 if ( CORBA::is_nil( theMesh ) )
1734 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1736 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1738 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1741 if(theMesh->HasShapeToMesh())
1742 shape = GeomObjectToShape( theSubObject );
1744 shape = SMESH_Mesh::PseudoShape();
1746 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1748 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1751 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1752 const bool includeSelf = true, complexShapeFirst = true;
1753 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1755 while ( smIt->more() )
1758 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1760 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1761 if ( error && !error->IsOK() )
1763 if ( !( error->myAlgo ) &&
1764 !( error->myAlgo = sm->GetAlgo() ))
1766 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1767 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1768 errStruct.comment = error->myComment.c_str();
1769 errStruct.subShapeID = sm->GetId();
1770 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1771 if ( !algoSO->_is_nil() ) {
1772 CORBA::String_var algoName = algoSO->GetName();
1773 errStruct.algoName = algoName;
1776 errStruct.algoName = error->myAlgo->GetName();
1778 errStruct.hasBadMesh = error->HasBadElems();
1781 error_array->length( nbErr );
1784 catch ( SALOME_Exception& S_ex ) {
1785 INFOS( "catch exception "<< S_ex.what() );
1788 return error_array._retn();
1791 //================================================================================
1793 * \brief Return mesh elements preventing computation of a subshape
1795 //================================================================================
1797 SMESH::MeshPreviewStruct*
1798 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1799 CORBA::Short theSubShapeID )
1801 Unexpect aCatch(SALOME_SalomeException);
1802 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1804 if ( CORBA::is_nil( theMesh ) )
1805 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1807 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1810 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1812 // mesh implementation
1813 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1814 // submesh by subshape id
1815 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1818 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1819 if ( error && error->HasBadElems() )
1821 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1822 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1824 // get nodes of elements and count elements
1825 TNode2LocalIDMap mapNode2LocalID;
1826 list< TNodeLocalID > connectivity;
1827 int i, nbElements = 0, nbConnNodes = 0;
1829 const list<const SMDS_MeshElement*>& badElems =
1830 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1831 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1832 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1833 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1835 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1836 while ( nIt->more() )
1837 connectivity.push_back
1838 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1840 // fill node coords and assign local ids to the nodes
1841 int nbNodes = mapNode2LocalID.size();
1842 result->nodesXYZ.length( nbNodes );
1843 TNodeLocalID node2ID = mapNode2LocalID.begin();
1844 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1845 node2ID->second = i;
1846 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1847 result->nodesXYZ[i].x = node->X();
1848 result->nodesXYZ[i].y = node->Y();
1849 result->nodesXYZ[i].z = node->Z();
1851 // fill connectivity
1852 result->elementConnectivities.length( nbConnNodes );
1853 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1854 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1855 result->elementConnectivities[i] = (*connIt)->second;
1857 // fill element types
1858 result->elementTypes.length( nbElements );
1859 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1861 const SMDS_MeshElement* elem = *elemIt;
1862 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1863 result->elementTypes[i].isPoly = elem->IsPoly();
1864 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1870 catch ( SALOME_Exception& S_ex ) {
1871 INFOS( "catch exception "<< S_ex.what() );
1874 return result._retn();
1877 //================================================================================
1879 * \brief Create a group of elements preventing computation of a sub-shape
1881 //================================================================================
1883 SMESH::ListOfGroups*
1884 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1885 CORBA::Short theSubShapeID,
1886 const char* theGroupName )
1888 Unexpect aCatch(SALOME_SalomeException);
1890 SMESH::ListOfGroups_var groups;
1892 if ( CORBA::is_nil( theMesh ) )
1893 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1896 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1898 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1899 TPythonDump() << groups << " = " << this
1900 << ".MakeGroupsOfBadInputElements( "
1901 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1904 catch ( SALOME_Exception& S_ex ) {
1905 INFOS( "catch exception "<< S_ex.what() );
1907 return groups._retn();
1910 //================================================================================
1912 * \brief Returns errors of hypotheses definition
1913 * \param theMesh - the mesh
1914 * \param theSubObject - the main or sub- shape
1915 * \retval SMESH::algo_error_array* - sequence of errors
1917 //================================================================================
1919 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1920 GEOM::GEOM_Object_ptr theSubObject )
1922 Unexpect aCatch(SALOME_SalomeException);
1923 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1925 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1926 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1928 if ( CORBA::is_nil( theMesh ) )
1929 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1931 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1933 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1934 ASSERT( meshServant );
1935 if ( meshServant ) {
1936 TopoDS_Shape myLocShape;
1937 if(theMesh->HasShapeToMesh())
1938 myLocShape = GeomObjectToShape( theSubObject );
1940 myLocShape = SMESH_Mesh::PseudoShape();
1942 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1943 list< ::SMESH_Gen::TAlgoStateError > error_list;
1944 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1945 // call ::SMESH_Gen::GetAlgoState()
1946 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1947 error_array->length( error_list.size() );
1949 for ( error = error_list.begin(); error != error_list.end(); ++error )
1951 // fill AlgoStateError structure
1952 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1953 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1954 errStruct.algoDim = error->_algoDim;
1955 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1956 errStruct.algoName = "";
1957 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1958 if ( !algoSO->_is_nil() ) {
1959 CORBA::String_var algoName = algoSO->GetName();
1960 errStruct.algoName = algoName.in();
1965 catch ( SALOME_Exception& S_ex ) {
1966 INFOS( "catch exception "<< S_ex.what() );
1968 return error_array._retn();
1971 //=============================================================================
1973 * SMESH_Gen_i::GetSubShapesId
1975 * Get sub-shapes unique ID's list
1977 //=============================================================================
1980 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1981 const SMESH::object_array& theListOfSubShapeObject )
1983 Unexpect aCatch(SALOME_SalomeException);
1984 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1986 SMESH::long_array_var shapesId = new SMESH::long_array;
1989 if ( CORBA::is_nil( theMainShapeObject ) )
1990 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1994 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1995 TopTools_IndexedMapOfShape myIndexToShape;
1996 TopExp::MapShapes(myMainShape,myIndexToShape);
1998 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
2000 GEOM::GEOM_Object_var aShapeObject
2001 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
2002 if ( CORBA::is_nil( aShapeObject ) )
2003 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
2004 SALOME::BAD_PARAM );
2006 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
2007 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
2009 const TopoDS_Face& F = TopoDS::Face(exp.Current());
2010 setId.insert(myIndexToShape.FindIndex(F));
2011 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
2013 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
2015 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
2016 setId.insert(myIndexToShape.FindIndex(E));
2017 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
2019 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
2021 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
2022 setId.insert(myIndexToShape.FindIndex(V));
2023 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
2026 shapesId->length(setId.size());
2027 set<int>::iterator iind;
2029 for (iind = setId.begin(); iind != setId.end(); iind++)
2031 if(MYDEBUG) SCRUTE((*iind));
2032 shapesId[i] = (*iind);
2033 if(MYDEBUG) SCRUTE(shapesId[i]);
2037 catch (SALOME_Exception& S_ex)
2039 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2042 return shapesId._retn();
2045 //=============================================================================
2047 * SMESH_Gen_i::Compute
2049 * Compute mesh on a shape
2051 //=============================================================================
2053 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2054 GEOM::GEOM_Object_ptr theShapeObject )
2057 Unexpect aCatch(SALOME_SalomeException);
2058 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2060 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2061 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2062 SALOME::BAD_PARAM );
2064 if ( CORBA::is_nil( theMesh ) )
2065 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2066 SALOME::BAD_PARAM );
2068 // Update Python script
2069 TPythonDump() << "isDone = " << this << ".Compute( "
2070 << theMesh << ", " << theShapeObject << ")";
2074 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2075 ASSERT( meshServant );
2076 if ( meshServant ) {
2077 if ( isGeomModifIcon( theMesh ))
2078 meshServant->Clear();
2080 meshServant->Load();
2081 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2082 meshServant->CheckGeomModif();
2083 // get local TopoDS_Shape
2084 TopoDS_Shape myLocShape;
2085 if(theMesh->HasShapeToMesh())
2086 myLocShape = GeomObjectToShape( theShapeObject );
2088 myLocShape = SMESH_Mesh::PseudoShape();
2089 // call implementation compute
2090 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2091 myGen.PrepareCompute( myLocMesh, myLocShape );
2092 int how = ::SMESH_Gen::COMPACT_MESH;
2093 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2094 how |= ::SMESH_Gen::SHAPE_ONLY;
2095 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2096 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2097 myLocMesh.GetMeshDS()->Modified();
2098 UpdateIcons( theMesh );
2100 HighLightInvalid( theMesh, /*isInvalid=*/false );
2104 catch ( std::bad_alloc& ) {
2105 INFOS( "Compute(): lack of memory" );
2107 catch ( SALOME_Exception& S_ex ) {
2108 INFOS( "Compute(): catch exception "<< S_ex.what() );
2111 INFOS( "Compute(): unknown exception " );
2116 //=============================================================================
2118 * SMESH_Gen_i::CancelCompute
2120 * Cancel Compute mesh on a shape
2122 //=============================================================================
2124 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2125 GEOM::GEOM_Object_ptr theShapeObject )
2127 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2129 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2130 TopoDS_Shape myLocShape;
2131 if(theMesh->HasShapeToMesh())
2132 myLocShape = GeomObjectToShape( theShapeObject );
2134 myLocShape = SMESH_Mesh::PseudoShape();
2135 myGen.CancelCompute( myLocMesh, myLocShape);
2139 //=============================================================================
2141 * SMESH_Gen_i::Precompute
2143 * Compute mesh as preview till indicated dimension on shape
2145 //=============================================================================
2147 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2148 GEOM::GEOM_Object_ptr theShapeObject,
2149 SMESH::Dimension theDimension,
2150 SMESH::long_array& theShapesId)
2152 Unexpect aCatch(SALOME_SalomeException);
2153 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2155 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2156 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2157 SALOME::BAD_PARAM );
2159 if ( CORBA::is_nil( theMesh ) )
2160 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2161 SALOME::BAD_PARAM );
2163 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2166 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2167 meshServant->Load();
2168 ASSERT( meshServant );
2169 if ( meshServant ) {
2170 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2171 meshServant->CheckGeomModif();
2172 // get local TopoDS_Shape
2173 TopoDS_Shape myLocShape;
2174 if(theMesh->HasShapeToMesh())
2175 myLocShape = GeomObjectToShape( theShapeObject );
2177 return result._retn();
2179 // call implementation compute
2180 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2182 ::MeshDimension aDim = (MeshDimension)theDimension;
2183 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2185 int nbShapeId = shapeIds.size();
2186 theShapesId.length( nbShapeId );
2187 // iterates on shapes and collect mesh entities into mesh preview
2188 TSetOfInt::const_iterator idIt = shapeIds.begin();
2189 TSetOfInt::const_iterator idEnd = shapeIds.end();
2190 std::map< int, int > mapOfShIdNb;
2191 std::set< SMESH_TLink > setOfEdge;
2192 std::list< SMDSAbs_ElementType > listOfElemType;
2193 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2194 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2195 TNode2LocalIDMap mapNode2LocalID;
2196 list< TNodeLocalID > connectivity;
2197 int i, nbConnNodes = 0;
2198 std::set< const SMESH_subMesh* > setOfVSubMesh;
2199 // iterates on shapes
2200 for ( ; idIt != idEnd; idIt++ )
2202 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2204 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2205 if ( !sm || !sm->IsMeshComputed() )
2208 const TopoDS_Shape& aSh = sm->GetSubShape();
2209 const int shDim = myGen.GetShapeDim( aSh );
2210 if ( shDim < 1 || shDim > theDimension )
2213 mapOfShIdNb[ *idIt ] = 0;
2214 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2216 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2217 if ( !smDS ) continue;
2219 if ( theDimension == SMESH::DIM_2D )
2221 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2222 while ( faceIt->more() )
2224 const SMDS_MeshElement* face = faceIt->next();
2225 int aNbNode = face->NbNodes();
2227 aNbNode /= 2; // do not take into account additional middle nodes
2229 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2230 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2232 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2233 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2235 listOfElemType.push_back( SMDSAbs_Edge );
2236 connectivity.push_back
2237 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2238 connectivity.push_back
2239 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2245 else if ( theDimension == SMESH::DIM_1D )
2247 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2248 while ( nodeIt->more() )
2250 listOfElemType.push_back( SMDSAbs_Node );
2251 connectivity.push_back
2252 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2254 // add corner nodes by first vertex from edge
2255 SMESH_subMeshIteratorPtr edgeSmIt =
2256 sm->getDependsOnIterator(/*includeSelf*/false,
2257 /*complexShapeFirst*/false);
2258 while ( edgeSmIt->more() )
2260 SMESH_subMesh* vertexSM = edgeSmIt->next();
2261 // check that vertex is not already treated
2262 if ( !setOfVSubMesh.insert( vertexSM ).second )
2264 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2267 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2268 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2269 while ( nodeIt->more() )
2271 listOfElemType.push_back( SMDSAbs_Node );
2272 connectivity.push_back
2273 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2279 // fill node coords and assign local ids to the nodes
2280 int nbNodes = mapNode2LocalID.size();
2281 result->nodesXYZ.length( nbNodes );
2282 TNodeLocalID node2ID = mapNode2LocalID.begin();
2283 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2284 node2ID->second = i;
2285 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2286 result->nodesXYZ[i].x = node->X();
2287 result->nodesXYZ[i].y = node->Y();
2288 result->nodesXYZ[i].z = node->Z();
2290 // fill connectivity
2291 result->elementConnectivities.length( nbConnNodes );
2292 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2293 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2294 result->elementConnectivities[i] = (*connIt)->second;
2297 // fill element types
2298 result->elementTypes.length( listOfElemType.size() );
2299 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2300 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2301 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2303 SMDSAbs_ElementType elemType = *typeIt;
2304 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2305 result->elementTypes[i].isPoly = false;
2306 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2309 // correct number of shapes
2310 theShapesId.length( mapOfShIdNb.size() );
2314 catch ( std::bad_alloc& ) {
2315 INFOS( "Precompute(): lack of memory" );
2317 catch ( SALOME_Exception& S_ex ) {
2318 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2321 INFOS( "Precompute(): unknown exception " );
2323 return result._retn();
2327 //=============================================================================
2329 * SMESH_Gen_i::Evaluate
2331 * Evaluate mesh on a shape
2333 //=============================================================================
2335 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2336 GEOM::GEOM_Object_ptr theShapeObject)
2337 // SMESH::long_array& theNbElems)
2339 Unexpect aCatch(SALOME_SalomeException);
2340 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2342 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2343 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2345 if ( CORBA::is_nil( theMesh ) )
2346 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2348 SMESH::long_array_var nbels = new SMESH::long_array;
2349 nbels->length(SMESH::Entity_Last);
2350 int i = SMESH::Entity_Node;
2351 for (; i < SMESH::Entity_Last; i++)
2354 // Update Python script
2355 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2356 << theMesh << ", " << theShapeObject << ")";
2360 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2361 ASSERT( meshServant );
2362 if ( meshServant ) {
2363 meshServant->Load();
2364 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2365 meshServant->CheckGeomModif();
2366 // get local TopoDS_Shape
2367 TopoDS_Shape myLocShape;
2368 if(theMesh->HasShapeToMesh())
2369 myLocShape = GeomObjectToShape( theShapeObject );
2371 myLocShape = SMESH_Mesh::PseudoShape();
2372 // call implementation compute
2373 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2374 MapShapeNbElems aResMap;
2375 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2376 MapShapeNbElemsItr anIt = aResMap.begin();
2377 for(; anIt!=aResMap.end(); anIt++) {
2378 const vector<int>& aVec = (*anIt).second;
2379 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2380 int nbElem = aVec[i];
2381 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2383 SMESH_subMesh* sm = anIt->first;
2384 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2385 const SMESH_Algo* algo = sm->GetAlgo();
2386 if ( (algo && !error.get()) || error->IsOK() )
2387 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2391 nbels[i] += aVec[i];
2395 return nbels._retn();
2398 catch ( std::bad_alloc& ) {
2399 INFOS( "Evaluate(): lack of memory" );
2401 catch ( SALOME_Exception& S_ex ) {
2402 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2405 INFOS( "Evaluate(): unknown exception " );
2408 return nbels._retn();
2411 //================================================================================
2413 * \brief Return geometrical object the given element is built on
2414 * \param theMesh - the mesh the element is in
2415 * \param theElementID - the element ID
2416 * \param theGeomName - the name of the result geom object if it is not yet published
2417 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2419 //================================================================================
2421 GEOM::GEOM_Object_ptr
2422 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2423 CORBA::Long theElementID,
2424 const char* theGeomName)
2426 Unexpect aCatch(SALOME_SalomeException);
2428 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2429 if ( !geom->_is_nil() ) {
2430 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2431 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2433 // try to find the corresponding SObject
2434 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2435 if ( SObj->_is_nil() ) // submesh can be not found even if published
2437 // try to find published submesh
2438 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2439 if ( !geom->IsMainShape() && list->length() == 1 ) {
2440 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2441 SALOMEDS::ChildIterator_wrap it;
2442 if ( !mainSO->_is_nil() ) {
2443 it = getStudyServant()->NewChildIterator( mainSO );
2445 if ( !it->_is_nil() ) {
2446 for ( it->InitEx(true); it->More(); it->Next() ) {
2447 SALOMEDS::SObject_wrap so = it->Value();
2448 CORBA::Object_var obj = SObjectToObject( so );
2449 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2450 if ( !subGeom->_is_nil() ) {
2451 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2452 if ( subList->length() == 1 && list[0] == subList[0] ) {
2462 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2463 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2465 // return only published geometry
2466 if ( !SObj->_is_nil() ) {
2467 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2468 CORBA::Object_var obj = SObjectToObject( SObj );
2469 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2473 return GEOM::GEOM_Object::_nil();
2476 //================================================================================
2478 * \brief Return geometrical object the given element is built on.
2479 * \param theMesh - the mesh the element is in
2480 * \param theElementID - the element ID
2481 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2483 //================================================================================
2485 GEOM::GEOM_Object_ptr
2486 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2487 CORBA::Long theElementID)
2489 Unexpect aCatch(SALOME_SalomeException);
2490 if ( CORBA::is_nil( theMesh ) )
2491 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2493 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2494 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2496 // get a core mesh DS
2497 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2498 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2500 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2501 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2502 // find the element in mesh
2503 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2504 // find a shape id by the element
2505 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2506 // get a geom object by the shape id
2507 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2508 if ( geom->_is_nil() ) {
2509 // try to find a published sub-shape
2510 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2511 SALOMEDS::ChildIterator_wrap it;
2512 if ( !mainSO->_is_nil() ) {
2513 it = getStudyServant()->NewChildIterator( mainSO );
2515 if ( !it->_is_nil() ) {
2516 for ( it->InitEx(true); it->More(); it->Next() ) {
2517 SALOMEDS::SObject_wrap so = it->Value();
2518 CORBA::Object_var obj = SObjectToObject( so );
2519 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2520 if ( !subGeom->_is_nil() ) {
2521 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2522 if ( subList->length() == 1 && shapeID == subList[0] ) {
2530 if ( geom->_is_nil() ) {
2532 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2533 if ( !op->_is_nil() )
2534 geom = op->GetSubShape( mainShape, shapeID );
2539 if ( !geom->_is_nil() ) {
2540 GeomObjectToShape( geom ); // let geom client remember the found shape
2541 return geom._retn();
2546 return GEOM::GEOM_Object::_nil();
2549 //================================================================================
2551 * SMESH_Gen_i::Concatenate
2553 * Concatenate the given meshes into one mesh
2555 //================================================================================
2557 SMESH::SMESH_Mesh_ptr
2558 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2559 CORBA::Boolean theUniteIdenticalGroups,
2560 CORBA::Boolean theMergeNodesAndElements,
2561 CORBA::Double theMergeTolerance,
2562 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2564 return ConcatenateCommon(theMeshesArray,
2565 theUniteIdenticalGroups,
2566 theMergeNodesAndElements,
2572 //================================================================================
2574 * SMESH_Gen_i::ConcatenateWithGroups
2576 * Concatenate the given meshes into one mesh
2577 * Create the groups of all elements from initial meshes
2579 //================================================================================
2581 SMESH::SMESH_Mesh_ptr
2582 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2583 CORBA::Boolean theUniteIdenticalGroups,
2584 CORBA::Boolean theMergeNodesAndElements,
2585 CORBA::Double theMergeTolerance,
2586 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2588 return ConcatenateCommon(theMeshesArray,
2589 theUniteIdenticalGroups,
2590 theMergeNodesAndElements,
2596 //================================================================================
2598 * SMESH_Gen_i::ConcatenateCommon
2600 * Concatenate the given meshes into one mesh
2602 //================================================================================
2604 SMESH::SMESH_Mesh_ptr
2605 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2606 CORBA::Boolean theUniteIdenticalGroups,
2607 CORBA::Boolean theMergeNodesAndElements,
2608 CORBA::Double theMergeTolerance,
2609 CORBA::Boolean theCommonGroups,
2610 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2612 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2613 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2615 // create mesh if theMeshToAppendTo not provided
2616 SMESH::SMESH_Mesh_var newMesh;
2617 if ( CORBA::is_nil( theMeshToAppendTo ))
2618 newMesh = CreateEmptyMesh();
2620 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2621 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2622 if ( !newImpl ) return newMesh._retn();
2625 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2626 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2628 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2629 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2630 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2631 TGroupsMap groupsMap;
2632 TListOfNewGroups listOfNewGroups;
2634 if ( !CORBA::is_nil( theMeshToAppendTo ))
2636 // fill groupsMap with existing groups
2637 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2638 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2640 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2641 if ( !group->_is_nil() )
2643 CORBA::String_var name = group->GetName();
2644 SMESH::ElementType type = group->GetType();
2645 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2650 ::SMESH_MeshEditor newEditor( &locMesh );
2651 ::SMESH_MeshEditor::ElemFeatures elemType;
2653 // loop on sub-meshes
2654 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2656 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2657 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2658 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2659 if ( !initImpl ) continue;
2660 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2664 // assure that IDs increment by one during iteration
2665 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2666 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2667 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2668 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2670 initMeshDS->Modified();
2671 initMeshDS->CompactMesh();
2674 // remember nb of elements before filling in
2675 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2679 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2680 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2681 while ( elemIt->more() )
2683 SMESH_NodeXYZ node = elemIt->next();
2684 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2689 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2690 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2692 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2693 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2694 while ( elemIt->more() )
2696 const SMDS_MeshElement* elem = elemIt->next();
2697 elemType.myNodes.resize( elem->NbNodes() );
2699 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2700 for ( int k = 0; itNodes->more(); k++)
2702 const SMDS_MeshNode* node = itNodes->next();
2703 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2706 // creates a corresponding element on existent nodes in new mesh
2707 newElems[ elem->GetID() ] =
2708 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2710 newEditor.ClearLastCreated(); // forget the history
2713 // create groups of just added elements
2714 SMESH::SMESH_Group_var newGroup;
2715 SMESH::ElementType groupType;
2716 if ( theCommonGroups )
2719 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2720 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2721 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2722 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2725 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2727 for( groupType = SMESH::NODE;
2728 groupType < SMESH::NB_ELEMENT_TYPES;
2729 groupType = (SMESH::ElementType)( groupType + 1 ))
2731 if ( curState[ groupType ] <= prevState[ groupType ])
2732 continue; // no elements of groupType added from the i-th mesh
2734 // make a group name
2735 std::string groupName = "Gr";
2736 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2738 CORBA::String_var name = meshSO->GetName();
2742 groupName += typeNames[ groupType ];
2744 // make and fill a group
2745 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2746 std::vector< const SMDS_MeshElement* > & elemVec =
2747 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2748 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2750 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2752 for ( size_t j = 0; j < elemVec.size(); ++j )
2754 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2755 grpDS->Add( elemVec[j] );
2759 listOfNewGroups.clear();
2760 listOfNewGroups.push_back( newGroup );
2761 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2766 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2770 SMESH::SMESH_GroupBase_ptr group;
2771 CORBA::String_var groupName;
2772 SMESH::long_array_var newIDs = new SMESH::long_array();
2774 // loop on groups of a source mesh
2775 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2776 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2778 group = listOfGroups[iG];
2779 groupType = group->GetType();
2780 groupName = group->GetName();
2781 std::string name = groupName.in();
2783 // convert a list of IDs
2784 newIDs->length( group->Size() );
2785 std::vector< const SMDS_MeshElement* > & elemVec =
2786 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2787 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2789 while ( itGrElems->more() )
2791 const SMDS_MeshElement* elem = itGrElems->next();
2792 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2794 newIDs[ nbElems++ ] = newElem->GetID();
2796 newIDs->length( nbElems );
2798 // check that a current group name and type don't have identical ones in final mesh
2799 listOfNewGroups.clear();
2800 TNameAndType nameAndType( name, groupType );
2801 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2802 if ( anIter == groupsMap.end() )
2804 // add a new group in the mesh
2805 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2806 newGroup->Add( newIDs );
2808 listOfNewGroups.push_back( newGroup );
2809 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2811 else if ( theUniteIdenticalGroups )
2813 // unite identical groups
2814 TListOfNewGroups& aNewGroups = anIter->second;
2815 aNewGroups.front()->Add( newIDs );
2819 // rename identical groups
2820 newGroup = newImpl->CreateGroup( groupType, groupName );
2821 newGroup->Add( newIDs );
2823 TListOfNewGroups& newGroups = anIter->second;
2824 std::string newGroupName;
2825 if ( newGroups.size() == 1 )
2827 newGroupName = name + "_1";
2828 newGroups.front()->SetName( newGroupName.c_str() );
2830 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2831 newGroup->SetName( newGroupName.c_str() );
2832 newGroups.push_back( newGroup );
2835 } // if an IDSource is a mesh
2838 if ( theMergeNodesAndElements ) // merge nodes
2840 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2841 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2842 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2843 /*SeparateCornersAndMedium=*/ false );
2844 newEditor.MergeNodes( groupsOfNodes );
2846 newEditor.MergeEqualElements();
2849 // Update Python script
2850 pythonDump << newMesh << " = " << this
2851 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2852 << theMeshesArray << ", "
2853 << theUniteIdenticalGroups << ", "
2854 << theMergeNodesAndElements << ", "
2855 << TVar( theMergeTolerance ) << ", "
2856 << theMeshToAppendTo << " )";
2858 pPythonDump.reset(); // enable python dump from GetGroups()
2860 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2861 if ( !newMesh->_is_nil() )
2863 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2866 // IPAL21468 Change icon of compound because it need not be computed.
2867 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2868 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2870 newMeshDS->Modified();
2872 return newMesh._retn();
2875 //================================================================================
2877 * \brief Create a mesh by copying a part of another mesh
2878 * \param meshPart - a part of mesh to copy
2879 * \param toCopyGroups - to create in the new mesh groups
2880 * the copied elements belongs to
2881 * \param toKeepIDs - to preserve IDs of the copied elements or not
2882 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2884 //================================================================================
2886 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2887 const char* meshName,
2888 CORBA::Boolean toCopyGroups,
2889 CORBA::Boolean toKeepIDs)
2891 Unexpect aCatch(SALOME_SalomeException);
2893 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2894 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2896 // 1. Get source mesh
2898 if ( CORBA::is_nil( meshPart ))
2899 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2901 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2902 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2904 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2906 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2908 // 2. Make a new mesh
2910 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2911 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2913 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2914 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2915 if ( !meshSO->_is_nil() )
2917 SetName( meshSO, meshName, "Mesh" );
2918 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2920 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2921 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2922 ::SMESH_MeshEditor::ElemFeatures elemType;
2924 // 3. Get elements to copy
2926 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2927 TIDSortedElemSet srcElems;
2928 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2929 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2932 srcElemIt = srcMeshDS->elementsIterator();
2933 srcNodeIt = srcMeshDS->nodesIterator();
2937 SMESH::long_array_var ids = meshPart->GetIDs();
2938 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2940 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2941 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2942 srcElems.insert( elem );
2946 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2947 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2948 srcElems.insert( elem );
2950 if ( srcElems.empty() )
2951 return newMesh._retn();
2953 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2954 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2959 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2960 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2961 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2963 const SMDS_MeshNode *nSrc, *nTgt;
2964 vector< const SMDS_MeshNode* > nodes;
2965 while ( srcElemIt->more() )
2967 const SMDS_MeshElement * elem = srcElemIt->next();
2969 nodes.resize( elem->NbNodes());
2970 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2972 for ( iN = 0; nIt->more(); ++iN )
2974 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2975 nTgt = newMeshDS->FindNode( nSrc->GetID());
2977 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2982 for ( iN = 0; nIt->more(); ++iN )
2984 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2985 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2987 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2988 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2992 if ( elem->GetType() != SMDSAbs_Node )
2994 elemType.Init( elem, /*basicOnly=*/false );
2995 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2997 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2998 if ( toCopyGroups && !toKeepIDs )
2999 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
3001 } // while ( srcElemIt->more() )
3003 // 4(b). Copy free nodes
3005 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3007 while ( srcNodeIt->more() )
3009 nSrc = srcNodeIt->next();
3010 if ( nSrc->NbInverseElements() == 0 )
3013 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3015 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3022 int nbNewGroups = 0;
3025 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3026 while ( gIt->more() )
3028 SMESH_Group* group = gIt->next();
3029 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3031 // Check group type. We copy nodal groups containing nodes of copied element
3032 SMDSAbs_ElementType groupType = groupDS->GetType();
3033 if ( groupType != SMDSAbs_Node &&
3034 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3035 continue; // group type differs from types of meshPart
3037 // Find copied elements in the group
3038 vector< const SMDS_MeshElement* > groupElems;
3039 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3042 const SMDS_MeshElement* foundElem;
3043 if ( groupType == SMDSAbs_Node )
3045 while ( eIt->more() )
3046 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3047 groupElems.push_back( foundElem );
3051 while ( eIt->more() )
3052 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3053 groupElems.push_back( foundElem );
3058 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3059 if ( e2eMap.empty() ) continue;
3060 int minID = e2eMap.begin()->first->GetID();
3061 int maxID = e2eMap.rbegin()->first->GetID();
3062 TE2EMap::iterator e2e;
3063 while ( eIt->more() && groupElems.size() < e2eMap.size())
3065 const SMDS_MeshElement* e = eIt->next();
3066 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3067 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3068 groupElems.push_back( e2e->second );
3072 if ( !groupElems.empty() )
3074 SMESH::SMESH_Group_var newGroupObj =
3075 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3076 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3078 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3079 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3080 for ( unsigned i = 0; i < groupElems.size(); ++i )
3081 smdsGroup.Add( groupElems[i] );
3089 newMeshDS->Modified();
3091 *pyDump << newMesh << " = " << this
3092 << ".CopyMesh( " << meshPart << ", "
3093 << "'" << meshName << "', "
3094 << toCopyGroups << ", "
3095 << toKeepIDs << ")";
3097 pyDumpDeleter.reset(); // allow dump in GetGroups()
3099 if ( nbNewGroups > 0 ) // dump created groups
3100 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3102 return newMesh._retn();
3106 namespace // utils for CopyMeshWithGeom()
3108 typedef std::map< std::string, std::string > TStr2StrMap;
3109 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3110 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3111 typedef std::map< std::string, int > TName2IndexMap;
3113 //================================================================================
3115 * \brief Return a new sub-shape corresponding to an old one
3117 //================================================================================
3121 SMESH_Mesh_i* mySrcMesh_i;
3122 SMESH_Mesh_i* myNewMesh_i;
3123 SMESH_Gen_i* myGen_i;
3127 TStr2StrMap myOld2NewEntryMap; // map of study entries
3129 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3130 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3131 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3134 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3136 // not directly relating to shape search
3137 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3139 //================================================================================
3141 * \brief Constructor
3143 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3144 SMESH_Mesh_i* newMesh_i,
3145 SMESH_Gen_i* smeshGen_i )
3146 : mySrcMesh_i( srcMesh_i ),
3147 myNewMesh_i( newMesh_i ),
3148 myGen_i ( smeshGen_i ),
3149 myToPublish( smeshGen_i->IsEnablePublish() ),
3150 myGIPMapDone( false )
3152 // retrieve from the study shape mapping made thanks to
3153 // "Set presentation parameters and sub-shapes from arguments" option
3155 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3156 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3157 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3158 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3159 if ( newSO->_is_nil() )
3161 myToPublish = false;
3164 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3166 CORBA::String_var oldEntry = oldSO->GetID();
3167 CORBA::String_var newEntry = newSO->GetID();
3168 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3169 std::string( newEntry.in() )));
3170 std::string newMainEntry = newEntry.in();
3172 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3173 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3174 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3175 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3176 /*groupsOnly=*/false );
3177 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3179 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3180 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3181 bool refFound = false;
3182 for ( ; anIter->More(); anIter->Next() )
3184 SALOMEDS::SObject_wrap so = anIter->Value();
3185 if ( so->ReferencedObject( oldSO.inout() ))
3187 oldEntry = oldSO->GetID();
3188 newEntry = newSO->GetID();
3189 if (( refFound = ( newMainEntry != oldEntry.in() )))
3190 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3191 std::string( newEntry.in() )));
3196 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3197 if ( father->_is_equivalent( mainShapeNew ))
3199 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3200 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3201 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3202 CORBA::String_var name = newSO->GetName();
3204 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3210 //================================================================================
3212 * \brief Find a new sub-shape corresponding to an old one
3214 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3217 return GEOM::GEOM_Object::_duplicate( oldShape );
3219 GEOM::GEOM_Object_var newShape;
3221 if ( CORBA::is_nil( oldShape ))
3222 return newShape._retn();
3224 if ( !isChildOfOld( oldShape ))
3225 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3227 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3228 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3230 // try to find by entry or name
3233 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3234 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3235 if ( o2nID != myOld2NewEntryMap.end() )
3237 newShape = getShapeByEntry( o2nID->second );
3239 if ( newShape->_is_nil() )
3241 CORBA::String_var name = oldShape->GetName();
3242 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3243 if ( n2ind != myName2SubshapeIndex.end() )
3245 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3246 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3247 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3248 if ( oldIndices->length() == 0 ||
3249 newIndices->length() == 0 ||
3250 getShapeType( myNewMesh_i, newIndices[0] ) !=
3251 getShapeType( mySrcMesh_i, oldIndices[0] ))
3252 newShape = GEOM::GEOM_Object::_nil();
3257 if ( newShape->_is_nil() )
3259 // try to construct a new sub-shape using myGIPMap
3261 std::vector< int > newIndices;
3262 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3263 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3265 findNewIDs( oldIndices[i], newIndices );
3267 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3270 newShape = getInPlace( oldShape );
3272 if ( !newIndices.empty() && newShape->_is_nil() )
3274 // search for a sub-shape with same ids
3275 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3276 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3277 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3278 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3280 if ( newShape->_is_nil() )
3283 // create a new shape
3284 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3286 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3288 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3289 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3291 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3292 newIndicesList->length( newIndices.size() );
3293 for ( size_t i = 0; i < newIndices.size(); ++i )
3294 newIndicesList[ i ] = newIndices[ i ];
3295 grOp->UnionIDs( newShape, newIndicesList );
3299 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3300 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3309 if ( !newShape->_is_nil() && myToPublish )
3311 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3312 if ( !newEntry.in() || !newEntry.in()[0] )
3314 CORBA::String_var name = oldShape->GetName();
3315 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3316 newEntry = newShape->GetStudyEntry();
3317 oldEntry = oldShape->GetStudyEntry();
3318 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3319 std::string( newEntry.in() )));
3323 return newShape._retn();
3326 //================================================================================
3328 * \brief Return a study entry of a new shape by study entry of the old one
3330 std::string FindNew( const std::string & oldEntry )
3335 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3336 if ( o2nID != myOld2NewEntryMap.end() )
3337 return o2nID->second;
3339 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3340 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3343 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3344 if ( newShape->_is_nil() )
3345 return std::string();
3347 CORBA::String_var newEntry = newShape->GetStudyEntry();
3348 return newEntry.in();
3351 //================================================================================
3353 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3354 * Return zero if not found or there are more than one new ID
3356 int FindNew( int oldID )
3365 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3367 if ( myGIPMap[ oldID ].length() == 1 )
3369 newID = myGIPMap[ oldID ][ 0 ];
3371 else if ( myGIPMap[ oldID ].length() > 1 &&
3372 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3374 // select a meshed VERTEX
3375 SMESH_subMesh* newSM;
3376 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3377 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3378 ( !newSM->IsEmpty() ))
3379 newID = myGIPMap[ oldID ][ i ];
3385 //================================================================================
3387 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3388 * Return zero if the old shape is not kept as is in the new shape.
3390 int FindNewNotChanged( SMESH_subMesh* oldSM )
3393 return oldSM->GetId();
3395 int newID = FindNew( oldSM->GetId() );
3399 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3403 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3404 // one new sub-shape of the same type.
3406 if ( oldSM->DependsOn().size() !=
3407 newSM->DependsOn().size() )
3410 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3411 while ( srcSMIt->more() )
3413 oldSM = srcSMIt->next();
3414 int newSubID = FindNew( oldSM->GetId() );
3415 if ( getShapeType( myNewMesh_i, newSubID ) !=
3416 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3422 //================================================================================
3424 * \brief Return shape by study entry
3426 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3428 GEOM::GEOM_Object_var shape;
3429 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3430 if ( !so->_is_nil() )
3432 CORBA::Object_var obj = so->GetObject();
3433 shape = GEOM::GEOM_Object::_narrow( obj );
3435 return shape._retn();
3438 //================================================================================
3440 * \brief Fill myGIPMap by calling GetInPlaceMap()
3444 if ( !myGIPMapDone )
3446 myGIPMapDone = true;
3448 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3449 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3450 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3451 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3454 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3458 myGIPMap = new GEOM::ListOfListOfLong();
3463 //================================================================================
3465 * \brief Get new sub-shape by calling GetInPlace()
3467 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3469 GEOM::GEOM_Object_var newShape;
3471 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3472 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3473 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3476 newShape = op->GetInPlace( mainShapeNew, oldShape );
3481 return newShape._retn();
3484 //================================================================================
3486 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3487 * number of found IDs
3489 int findNewIDs( int oldID, std::vector< int >& newIDs )
3491 size_t prevNbIDs = newIDs.size();
3493 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3495 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3496 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3498 return newIDs.size() - prevNbIDs;
3501 //================================================================================
3503 * \brief Check if an object relates to the old shape
3505 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3507 if ( CORBA::is_nil( oldShape ))
3509 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3510 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3511 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3512 mainShapeOld1->_is_equivalent( oldShape ));
3515 //================================================================================
3517 * \brief Return shape type by shape ID
3519 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3521 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3522 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3523 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3526 //================================================================================
3528 * \brief Store a source sub-shape for which a counterpart not found and
3529 * a smesh object invalid due to that
3531 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3532 SALOMEDS::SObject_wrap smeshSO )
3534 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3535 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3537 CORBA::String_var smeshEntry = smeshSO->GetID();
3538 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3542 //================================================================================
3544 * \brief Store a source sub-shape for which a counterpart not found and
3545 * a smesh object invalid due to that
3547 void AddInvalid( std::string geomEntry,
3548 SALOMEDS::SObject_wrap smeshSO )
3550 if ( !geomEntry.empty() )
3552 CORBA::String_var smeshEntry = smeshSO->GetID();
3553 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3557 //================================================================================
3559 * \brief Store a source sub-shape for which a counterpart not found and
3560 * a smesh object invalid due to that
3562 void AddInvalid( int oldGeomID,
3563 SALOMEDS::SObject_wrap smeshSO )
3565 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3566 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3569 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3570 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3572 SMESH_Comment geomName( typeName[ shapeType ]);
3573 geomName << " #" << oldGeomID;
3575 CORBA::String_var smeshEntry = smeshSO->GetID();
3576 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3579 //================================================================================
3581 * \brief Return entries of a source sub-shape for which a counterpart not found and
3582 * of smesh objects invalid due to that
3584 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3585 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3588 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3589 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3591 nbSO += 1 + entry2entrySet->second.size();
3593 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3594 theInvalidEntries->length ( nbSO );
3595 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3597 entry2entrySet = myInvalidMap.begin();
3598 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3600 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3602 std::set< std::string > & entrySet = entry2entrySet->second;
3603 std::set< std::string >::iterator entry = entrySet.begin();
3604 for ( ; entry != entrySet.end(); ++entry )
3606 theInvalidEntries[ iEntry++ ] = entry->c_str();
3608 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3609 if ( !so->_is_nil() )
3610 theInvalidMeshSObjects[ iSO++ ] = so;
3615 }; // struct ShapeMapper
3617 //================================================================================
3619 * \brief Append an item to a CORBA sequence
3621 template < class CORBA_seq, class ITEM >
3622 void append( CORBA_seq& seq, ITEM item )
3624 if ( !CORBA::is_nil( item ))
3626 seq->length( 1 + seq->length() );
3627 seq[ seq->length() - 1 ] = item;
3630 } // namespace // utils for CopyMeshWithGeom()
3632 //================================================================================
3634 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3635 * \param [in] sourceMesh - a mesh to copy
3636 * \param [in] newGeometry - a new geometry
3637 * \param [in] toCopyGroups - to create groups in the new mesh
3638 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3639 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3640 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3641 * \param [out] newMesh - return a new mesh
3642 * \param [out] newGroups - return new groups
3643 * \param [out] newSubmeshes - return new sub-meshes
3644 * \param [out] newHypotheses - return new algorithms and hypotheses
3645 * \param [out] invalidEntries - return study entries of objects whose
3646 * counterparts are not found in the newGeometry, followed by entries
3647 * of mesh sub-objects that are invalid because they depend on a not found
3648 * preceding sub-shape
3649 * \return CORBA::Boolean - is a success
3651 //================================================================================
3653 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3654 GEOM::GEOM_Object_ptr theNewGeometry,
3655 const char* theMeshName,
3656 CORBA::Boolean theToCopyGroups,
3657 CORBA::Boolean theToReuseHypotheses,
3658 CORBA::Boolean theToCopyElements,
3659 SMESH::SMESH_Mesh_out theNewMesh,
3660 SMESH::ListOfGroups_out theNewGroups,
3661 SMESH::submesh_array_out theNewSubmeshes,
3662 SMESH::ListOfHypothesis_out theNewHypotheses,
3663 SMESH::string_array_out theInvalidEntries)
3665 if ( CORBA::is_nil( theSourceMesh ) ||
3666 CORBA::is_nil( theNewGeometry ))
3667 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3669 if ( !theSourceMesh->HasShapeToMesh() )
3670 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3675 TPythonDump pyDump; // prevent dump from CreateMesh()
3677 theNewMesh = CreateMesh( theNewGeometry );
3678 theNewGroups = new SMESH::ListOfGroups();
3679 theNewSubmeshes = new SMESH::submesh_array();
3680 theNewHypotheses = new SMESH::ListOfHypothesis();
3681 theInvalidEntries = new SMESH::string_array();
3683 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3685 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3686 GEOM::GEOM_Object_var geom, newGeom;
3687 SALOMEDS::SObject_wrap so;
3689 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3690 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3693 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3695 // treat hypotheses of mesh and sub-meshes
3696 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3697 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3699 bool isSubMesh = ( iSM < smList->length() );
3702 // create a new sub-mesh
3703 SMESH::SMESH_subMesh_var newSM;
3704 geom = smList[iSM]->GetSubShape();
3705 so = ObjectToSObject( smList[iSM] );
3706 CORBA::String_var name;
3707 if ( !so->_is_nil() )
3708 name = so->GetName();
3709 newGeom = shapeMapper.FindNew( geom );
3710 if ( newGeom->_is_nil() )
3712 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3713 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3718 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3720 append( theNewSubmeshes, newSM );
3722 if ( newGeom->_is_nil() )
3723 continue; // don't assign hypotheses
3727 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3729 so = ObjectToSObject( theNewMesh );
3730 SetName( so, theMeshName, "Mesh" );
3733 // assign hypotheses
3734 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3735 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3737 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3738 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3740 // get geometry hyp depends on
3741 std::vector< std::string > entryArray;
3742 std::vector< int > subIDArray;
3743 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3745 if ( !theToReuseHypotheses || dependsOnGeom )
3747 // create a new hypothesis
3748 CORBA::String_var type = hyp->GetName();
3749 CORBA::String_var lib = hyp->GetLibName();
3750 CORBA::String_var data = hyp_i->SaveTo();
3753 hyp = CreateHypothesis( type, lib );
3754 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3755 hyp_i->LoadFrom( data.in() );
3756 append( theNewHypotheses, hyp );
3760 // update geometry hyp depends on
3761 if ( dependsOnGeom )
3763 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3765 if ( !entryArray[ iGeo ].empty() )
3767 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3768 if ( newEntry.empty() )
3771 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3772 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3774 entryArray[ iGeo ] = newEntry;
3777 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3779 if ( subIDArray[ iGeo ] > 0 )
3781 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3785 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3786 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3788 subIDArray[ iGeo ] = newID;
3791 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3795 CORBA::String_var errorText;
3796 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3797 if ( errorText.in()[0] )
3800 } // loop on hypotheses
3801 } // loop on sub-meshes and mesh
3804 // copy mesh elements, keeping IDs
3805 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3806 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3808 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3809 ::SMESH_MeshEditor::ElemFeatures elemData;
3811 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3812 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3813 /*vertexLast=*/false);
3814 while ( srcSMIt->more() )
3816 SMESH_subMesh* srcSM = srcSMIt->next();
3817 if ( srcSM->IsEmpty() )
3818 continue; // not yet computed
3819 int newID = shapeMapper.FindNewNotChanged( srcSM );
3823 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3824 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3825 while ( nIt->more() )
3827 SMESH_NodeXYZ node( nIt->next() );
3828 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3830 const SMDS_PositionPtr pos = node->GetPosition();
3831 const double* uv = pos->GetParameters();
3832 switch ( pos->GetTypeOfPosition() )
3834 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3835 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3836 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3837 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3841 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3842 while( eIt->more() )
3844 const SMDS_MeshElement* e = eIt->next();
3845 elemData.Init( e, /*basicOnly=*/false );
3846 elemData.SetID( e->GetID() );
3847 elemData.myNodes.resize( e->NbNodes() );
3848 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3850 for ( iN = 0; nnIt->more(); ++iN )
3852 const SMDS_MeshNode* srcNode = nnIt->next();
3853 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3854 if ( !elemData.myNodes[ iN ])
3857 if ( iN == elemData.myNodes.size() )
3858 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3859 newMeshDS->SetMeshElementOnShape( newElem, newID );
3861 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3862 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3865 newMeshDS->Modified();
3871 TStr2StrMap old2newGroupMap;
3873 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3875 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3876 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3877 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3879 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3880 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3881 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3883 CORBA::String_var name = groups[ i ]->GetName();
3884 SMESH::ElementType elemType = groups[ i ]->GetType();
3886 SMESH::SMESH_GroupBase_var newGroup;
3888 if ( !stdlGroup->_is_nil() )
3890 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3892 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3893 const bool isElem = ( elemType != SMESH::NODE );
3894 CORBA::ULong iE = 0;
3895 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3896 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3898 if ( iE < elemIDs->length() )
3900 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3901 stdlGroup->Add( elemIDs );
3902 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3906 else if ( !geomGroup->_is_nil() )
3908 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3909 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3910 if ( newGeom->_is_nil() )
3912 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3913 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3918 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3921 else if ( !fltrGroup->_is_nil() )
3923 // replace geometry in a filter
3924 SMESH::Filter_var filter = fltrGroup->GetFilter();
3925 SMESH::Filter::Criteria_var criteria;
3926 filter->GetCriteria( criteria.out() );
3928 bool isMissingGroup = false;
3929 std::vector< std::string > badEntries;
3931 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3933 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3934 switch ( criteria[ iCr ].Type )
3936 case SMESH::FT_BelongToMeshGroup:
3938 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3939 btgg->SetGroupID( thresholdID );
3940 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3941 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3942 if ( refGroupSO->_is_nil() )
3944 CORBA::String_var refID = refGroupSO->GetID();
3945 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3946 if ( o2nID == old2newGroupMap.end() )
3948 isMissingGroup = true; // corresponding new group not yet created
3951 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3953 if ( o2nID->second.empty() ) // new referred group is invalid
3954 badEntries.push_back( refID.in() );
3957 case SMESH::FT_BelongToGeom:
3958 case SMESH::FT_BelongToPlane:
3959 case SMESH::FT_BelongToCylinder:
3960 case SMESH::FT_BelongToGenSurface:
3961 case SMESH::FT_LyingOnGeom:
3963 std::string newID = shapeMapper.FindNew( thresholdID );
3964 criteria[ iCr ].ThresholdID = newID.c_str();
3965 if ( newID.empty() )
3966 badEntries.push_back( thresholdID );
3969 case SMESH::FT_ConnectedElements:
3971 if ( thresholdID && thresholdID[0] )
3973 std::string newID = shapeMapper.FindNew( thresholdID );
3974 criteria[ iCr ].ThresholdID = newID.c_str();
3975 if ( newID.empty() )
3976 badEntries.push_back( thresholdID );
3982 } // loop on criteria
3984 if ( isMissingGroup && i < nbGroups )
3986 // to treat the group again
3987 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3991 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3992 newFilter->SetCriteria( criteria );
3994 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3995 newFilter->UnRegister();
3997 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3998 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3999 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
4001 if ( isMissingGroup ) // all groups treated but a referred groups still not found
4003 invalidSObjects.push_back( ObjectToSObject( newGroup ));
4006 if ( !badEntries.empty() )
4009 } // treat a group on filter
4011 append( theNewGroups, newGroup );
4013 // fill old2newGroupMap
4014 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4015 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4016 if ( !srcSO->_is_nil() )
4018 CORBA::String_var srcID, newID("");
4019 srcID = srcSO->GetID();
4020 if ( !newSO->_is_nil() )
4021 newID = newSO->GetID();
4022 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4023 std::string( newID.in() )));
4026 if ( newGroup->_is_nil() )
4031 newMeshDS->CompactMesh();
4034 if ( !theMeshName || !theMeshName[0] )
4036 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4037 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4038 CORBA::String_var oldName = soOld->GetName();
4039 SetName( soNew, oldName.in(), "Mesh" );
4041 // mark invalid objects
4042 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4044 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4045 highLightInvalid( invalidSObjects[i].in(), true );
4048 << theNewMesh << ", "
4049 << theNewGroups << ", "
4050 << *theNewSubmeshes.ptr() << ", "
4051 << *theNewHypotheses.ptr() << ", "
4052 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4053 << theSourceMesh << ", "
4054 << theNewGeometry << ", "
4055 << "'" << theMeshName << "', "
4056 << theToCopyGroups << ", "
4057 << theToReuseHypotheses << ", "
4058 << theToCopyElements << " )";
4060 SMESH_CATCH( SMESH::throwCorbaException );
4065 //================================================================================
4067 * \brief Get version of MED format being used.
4069 //================================================================================
4071 char* SMESH_Gen_i::GetMEDFileVersion()
4073 MED::TInt majeur, mineur, release;
4074 majeur = mineur = release = 0;
4075 MED::GetVersionRelease(majeur, mineur, release);
4076 std::ostringstream version;
4077 version << majeur << "." << mineur << "." << release;
4078 return CORBA::string_dup( version.str().c_str() );
4081 //================================================================================
4083 * SMESH_Gen_i::GetMEDVersion
4085 * Get MED version of the file by its name
4087 //================================================================================
4089 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4091 std::string version = MED::GetMEDVersion( theFileName );
4092 return CORBA::string_dup( version.c_str() );
4095 //================================================================================
4097 * SMESH_Gen_i::CheckCompatibility
4099 * Check compatibility of file with MED format being used, read only.
4101 //================================================================================
4103 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4105 return MED::CheckCompatibility( theFileName );
4108 //================================================================================
4110 * SMESH_Gen_i::CheckWriteCompatibility
4112 * Check compatibility of file with MED format being used, for append on write.
4114 //================================================================================
4116 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4118 return MED::CheckCompatibility( theFileName, true );
4121 //================================================================================
4123 * SMESH_Gen_i::GetMeshNames
4125 * Get names of meshes defined in file with the specified name
4127 //================================================================================
4128 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4131 SMESH::string_array_var aResult = new SMESH::string_array();
4132 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4134 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4136 aResult->length( aNbMeshes );
4137 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4138 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4139 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4142 return aResult._retn();
4145 //=============================================================================
4149 * Save SMESH module's data
4151 //=============================================================================
4153 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4158 Kernel_Utils::Localizer loc;
4160 if (!myStudyContext)
4163 // Store study contents as a set of python commands
4166 SALOMEDS::Study_var aStudy = getStudyServant();
4168 // Declare a byte stream
4169 SALOMEDS::TMPFile_var aStreamFile;
4171 // Obtain a temporary dir
4172 TCollection_AsciiString tmpDir =
4173 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4175 // Create a sequence of files processed
4176 SALOMEDS_Tool::ListOfFiles aFileSeq;
4177 aFileSeq.reserve( NUM_TMP_FILES );
4179 TCollection_AsciiString aStudyName( "" );
4181 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4183 // Set names of temporary files
4184 TCollection_AsciiString filename =
4185 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4186 TCollection_AsciiString meshfile =
4187 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4188 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4189 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4190 filename = tmpDir + filename;
4191 meshfile = tmpDir + meshfile;
4194 HDFdataset* aDataset;
4195 HDFgroup* aTopGroup;
4197 HDFgroup* aSubGroup;
4198 HDFgroup* aSubSubGroup;
4199 hdf_size aSize[ 1 ];
4202 //Remove the files if they exist: BugID: 11225
4203 #ifndef WIN32 /* unix functionality */
4204 TCollection_AsciiString cmd("rm -f \"");
4206 TCollection_AsciiString cmd("del /F \"");
4216 system(cmd.ToCString());
4218 // MED writer to be used by storage process
4219 DriverMED_W_SMESHDS_Mesh myWriter;
4220 myWriter.SetFile( meshfile.ToCString() );
4223 // SetStoreName() to groups before storing hypotheses to let them refer to
4224 // groups using "store name", which is "Group <group_persistent_id>"
4226 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4227 for ( ; itBig->More(); itBig->Next() ) {
4228 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4229 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4230 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4231 if ( !CORBA::is_nil( anObject ) ) {
4232 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4233 if ( !myMesh->_is_nil() ) {
4234 myMesh->Load(); // load from study file if not yet done
4235 TPythonDump pd; // not to dump GetGroups()
4236 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4237 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4239 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4242 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4243 int anId = myStudyContext->findId( string( objStr.in() ) );
4245 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4246 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4247 aGrpBaseDS->SetStoreName( grpName );
4257 // ---> create HDF file
4258 aFile = new HDFfile( (char*) filename.ToCString() );
4259 aFile->CreateOnDisk();
4261 // --> iterator for top-level objects
4262 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4263 for ( ; itBig->More(); itBig->Next() ) {
4264 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4266 // --> hypotheses root branch (only one for the study)
4267 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4268 // create hypotheses root HDF group
4269 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4270 aTopGroup->CreateOnDisk();
4272 // iterator for all hypotheses
4273 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4274 for ( ; it->More(); it->Next() ) {
4275 SALOMEDS::SObject_wrap mySObject = it->Value();
4276 CORBA::Object_var anObject = SObjectToObject( mySObject );
4277 if ( !CORBA::is_nil( anObject ) ) {
4278 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4279 if ( !myHyp->_is_nil() ) {
4280 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4282 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4283 std::string hypname = hn.in();
4284 std::string libname = ln.in();
4286 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4287 // WIN32 and ".so" for X-system) must be deleted
4288 int libname_len = libname.length();
4290 if( libname_len > 4 )
4291 libname.resize( libname_len - 4 );
4293 // PAL17753 (Regression: missing hypothesis in restored study)
4294 // "lib" also should be removed from the beginning
4295 if( libname_len > 6 )
4296 libname = libname.substr( 3, libname_len - 3 - 3 );
4298 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4299 CORBA::String_var hypdata = myImpl->SaveTo();
4300 int id = myStudyContext->findId( string( objStr.in() ));
4302 // for each hypothesis create HDF group basing on its id
4303 char hypGrpName[30];
4304 sprintf( hypGrpName, "Hypothesis %d", id );
4305 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4306 aGroup->CreateOnDisk();
4307 // --> type name of hypothesis
4308 aSize[ 0 ] = hypname.length() + 1;
4309 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4310 aDataset->CreateOnDisk();
4311 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4312 aDataset->CloseOnDisk();
4313 // --> server plugin library name of hypothesis
4314 aSize[ 0 ] = libname.length() + 1;
4315 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4316 aDataset->CreateOnDisk();
4317 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4318 aDataset->CloseOnDisk();
4319 // --> persistent data of hypothesis
4320 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4321 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4322 aDataset->CreateOnDisk();
4323 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4324 aDataset->CloseOnDisk();
4325 // close hypothesis HDF group
4326 aGroup->CloseOnDisk();
4331 // close hypotheses root HDF group
4332 aTopGroup->CloseOnDisk();
4334 // --> algorithms root branch (only one for the study)
4335 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4336 // create algorithms root HDF group
4337 aTopGroup = new HDFgroup( "Algorithms", aFile );
4338 aTopGroup->CreateOnDisk();
4340 // iterator for all algorithms
4341 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4342 for ( ; it->More(); it->Next() ) {
4343 SALOMEDS::SObject_wrap mySObject = it->Value();
4344 CORBA::Object_var anObject = SObjectToObject( mySObject );
4345 if ( !CORBA::is_nil( anObject ) ) {
4346 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4347 if ( !myHyp->_is_nil() ) {
4348 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4350 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4351 std::string hypname = hn.in();
4352 std::string libname = ln.in();
4354 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4355 // WIN32 and ".so" for X-system) must be deleted
4356 int libname_len = libname.length();
4358 if( libname_len > 4 )
4359 libname.resize( libname_len - 4 );
4361 // PAL17753 (Regression: missing hypothesis in restored study)
4362 // "lib" also should be removed from the beginning
4363 if( libname_len > 6 )
4364 libname = libname.substr( 3, libname_len - 3 - 3 );
4366 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4367 CORBA::String_var hypdata = myImpl->SaveTo();
4368 int id = myStudyContext->findId( string( objStr.in() ) );
4370 // for each algorithm create HDF group basing on its id
4371 char hypGrpName[30];
4372 sprintf( hypGrpName, "Algorithm %d", id );
4373 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4374 aGroup->CreateOnDisk();
4375 // --> type name of algorithm
4376 aSize[0] = hypname.length() + 1;
4377 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4378 aDataset->CreateOnDisk();
4379 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4380 aDataset->CloseOnDisk();
4381 // --> server plugin library name of hypothesis
4382 aSize[0] = libname.length() + 1;
4383 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4384 aDataset->CreateOnDisk();
4385 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4386 aDataset->CloseOnDisk();
4387 // --> persistent data of algorithm
4388 aSize[0] = strlen( hypdata.in() ) + 1;
4389 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4390 aDataset->CreateOnDisk();
4391 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4392 aDataset->CloseOnDisk();
4393 // close algorithm HDF group
4394 aGroup->CloseOnDisk();
4399 // close algorithms root HDF group
4400 aTopGroup->CloseOnDisk();
4402 // --> mesh objects roots branches
4403 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4404 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4405 if ( !CORBA::is_nil( anObject ) ) {
4406 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4407 if ( !myMesh->_is_nil() ) {
4408 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4410 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4411 int id = myStudyContext->findId( string( objStr.in() ) );
4412 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4413 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4414 bool hasShape = myLocMesh.HasShapeToMesh();
4416 // for each mesh open the HDF group basing on its id
4417 char meshGrpName[ 30 ];
4418 sprintf( meshGrpName, "Mesh %d", id );
4419 aTopGroup = new HDFgroup( meshGrpName, aFile );
4420 aTopGroup->CreateOnDisk();
4422 // --> put dataset to hdf file which is a flag that mesh has data
4423 string strHasData = "0";
4424 // check if the mesh is not empty
4425 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4426 // write mesh data to med file
4427 myWriter.SetMesh( mySMESHDSMesh );
4428 myWriter.SetMeshId( id );
4431 aSize[ 0 ] = strHasData.length() + 1;
4432 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4433 aDataset->CreateOnDisk();
4434 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4435 aDataset->CloseOnDisk();
4438 // for each mesh open the HDF group basing on its auto color parameter
4439 char meshAutoColorName[ 30 ];
4440 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4442 anAutoColor[0] = myImpl->GetAutoColor();
4444 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4445 aDataset->CreateOnDisk();
4446 aDataset->WriteOnDisk( anAutoColor );
4447 aDataset->CloseOnDisk();
4449 // issue 0020693. Store _isModified flag
4450 int isModified = myLocMesh.GetIsModified();
4452 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4453 aDataset->CreateOnDisk();
4454 aDataset->WriteOnDisk( &isModified );
4455 aDataset->CloseOnDisk();
4457 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4458 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4460 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4461 aDataset->CreateOnDisk();
4462 aDataset->WriteOnDisk( &meshPersistentId );
4463 aDataset->CloseOnDisk();
4465 // Store SMESH_Mesh_i::_mainShapeTick
4466 int shapeTick = myImpl->MainShapeTick();
4468 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4469 aDataset->CreateOnDisk();
4470 aDataset->WriteOnDisk( &shapeTick );
4471 aDataset->CloseOnDisk();
4473 // write reference on a shape if exists
4474 SALOMEDS::SObject_wrap myRef;
4475 bool shapeRefFound = false;
4476 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4478 SALOMEDS::SObject_wrap myShape;
4479 bool ok = myRef->ReferencedObject( myShape.inout() );
4481 CORBA::Object_var shapeObj = myShape->GetObject();
4482 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4483 CORBA::String_var myRefOnObject = myShape->GetID();
4484 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4485 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4486 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4487 aDataset->CreateOnDisk();
4488 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4489 aDataset->CloseOnDisk();
4495 std::string info = myImpl->FileInfoToString();
4496 if ( !info.empty() )
4498 aSize[ 0 ] = info.size();
4499 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4500 aDataset->CreateOnDisk();
4501 aDataset->WriteOnDisk( (char*) info.data() );
4502 aDataset->CloseOnDisk();
4505 // write applied hypotheses if exist
4506 SALOMEDS::SObject_wrap myHypBranch;
4507 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4508 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4509 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4511 if ( found && (shapeRefFound || !hasShape) ) {
4512 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4513 aGroup->CreateOnDisk();
4515 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4517 for ( ; it->More(); it->Next() ) {
4518 SALOMEDS::SObject_wrap mySObject = it->Value();
4519 SALOMEDS::SObject_wrap myRefOnHyp;
4520 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4522 // san - it is impossible to recover applied hypotheses
4523 // using their entries within Load() method,
4524 // for there are no AttributeIORs in the study when Load() is working.
4525 // Hence, it is better to store persistent IDs of hypotheses as references to them
4527 //string myRefOnObject = myRefOnHyp->GetID();
4528 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4529 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4530 int id = myStudyContext->findId( string( objStr.in() ) );
4531 //if ( myRefOnObject.length() > 0 ) {
4532 //aSize[ 0 ] = myRefOnObject.length() + 1;
4533 char hypName[ 30 ], hypId[ 30 ];
4534 sprintf( hypName, "Hyp %d", ++hypNb );
4535 sprintf( hypId, "%d", id );
4536 aSize[ 0 ] = strlen( hypId ) + 1;
4537 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4538 aDataset->CreateOnDisk();
4539 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4540 aDataset->WriteOnDisk( hypId );
4541 aDataset->CloseOnDisk();
4545 aGroup->CloseOnDisk();
4548 // write applied algorithms if exist
4549 SALOMEDS::SObject_wrap myAlgoBranch;
4550 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4551 myAlgoBranch.inout() );
4552 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4553 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4555 if ( found && (shapeRefFound || !hasShape)) {
4556 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4557 aGroup->CreateOnDisk();
4559 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4561 for ( ; it->More(); it->Next() ) {
4562 SALOMEDS::SObject_wrap mySObject = it->Value();
4563 SALOMEDS::SObject_wrap myRefOnAlgo;
4564 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4566 // san - it is impossible to recover applied algorithms
4567 // using their entries within Load() method,
4568 // for there are no AttributeIORs in the study when Load() is working.
4569 // Hence, it is better to store persistent IDs of algorithms as references to them
4571 //string myRefOnObject = myRefOnAlgo->GetID();
4572 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4573 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4574 int id = myStudyContext->findId( string( objStr.in() ) );
4575 //if ( myRefOnObject.length() > 0 ) {
4576 //aSize[ 0 ] = myRefOnObject.length() + 1;
4577 char algoName[ 30 ], algoId[ 30 ];
4578 sprintf( algoName, "Algo %d", ++algoNb );
4579 sprintf( algoId, "%d", id );
4580 aSize[ 0 ] = strlen( algoId ) + 1;
4581 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4582 aDataset->CreateOnDisk();
4583 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4584 aDataset->WriteOnDisk( algoId );
4585 aDataset->CloseOnDisk();
4589 aGroup->CloseOnDisk();
4592 // --> submesh objects sub-branches
4594 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4595 SALOMEDS::SObject_wrap mySubmeshBranch;
4596 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4598 if ( found ) // check if there is shape reference in submeshes
4600 bool hasShapeRef = false;
4601 SALOMEDS::ChildIterator_wrap itSM =
4602 aStudy->NewChildIterator( mySubmeshBranch );
4603 for ( ; itSM->More(); itSM->Next() ) {
4604 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4605 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4606 mySubRef->ReferencedObject( myShape.inout() );
4607 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4610 { // remove one submesh
4611 if ( shapeRefFound )
4612 { // unassign hypothesis
4613 SMESH::SMESH_subMesh_var mySubMesh =
4614 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4615 if ( !mySubMesh->_is_nil() ) {
4616 int shapeID = mySubMesh->GetId();
4617 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4618 const list<const SMESHDS_Hypothesis*>& hypList =
4619 mySMESHDSMesh->GetHypothesis( S );
4620 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4621 while ( hyp != hypList.end() ) {
4622 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4623 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4627 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4629 } // loop on submeshes of a type
4630 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4631 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4634 } // end check if there is shape reference in submeshes
4636 char name_meshgroup[ 30 ];
4637 if ( i == GetSubMeshOnVertexTag() )
4638 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4639 else if ( i == GetSubMeshOnEdgeTag() )
4640 strcpy( name_meshgroup, "SubMeshes On Edge" );
4641 else if ( i == GetSubMeshOnWireTag() )
4642 strcpy( name_meshgroup, "SubMeshes On Wire" );
4643 else if ( i == GetSubMeshOnFaceTag() )
4644 strcpy( name_meshgroup, "SubMeshes On Face" );
4645 else if ( i == GetSubMeshOnShellTag() )
4646 strcpy( name_meshgroup, "SubMeshes On Shell" );
4647 else if ( i == GetSubMeshOnSolidTag() )
4648 strcpy( name_meshgroup, "SubMeshes On Solid" );
4649 else if ( i == GetSubMeshOnCompoundTag() )
4650 strcpy( name_meshgroup, "SubMeshes On Compound" );
4652 // for each type of submeshes create container HDF group
4653 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4654 aGroup->CreateOnDisk();
4656 // iterator for all submeshes of given type
4657 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4658 for ( ; itSM->More(); itSM->Next() ) {
4659 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4660 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4661 if ( !CORBA::is_nil( anSubObject ))
4663 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4664 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4665 int subid = myStudyContext->findId( string( objStr.in() ) );
4667 // for each mesh open the HDF group basing on its id
4668 char submeshGrpName[ 30 ];
4669 sprintf( submeshGrpName, "SubMesh %d", subid );
4670 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4671 aSubGroup->CreateOnDisk();
4673 // write reference on a shape, already checked if it exists
4674 SALOMEDS::SObject_wrap mySubRef, myShape;
4675 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4676 mySubRef->ReferencedObject( myShape.inout() );
4677 string myRefOnObject = myShape->GetID();
4678 if ( myRefOnObject.length() > 0 ) {
4679 aSize[ 0 ] = myRefOnObject.length() + 1;
4680 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4681 aDataset->CreateOnDisk();
4682 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4683 aDataset->CloseOnDisk();
4686 // write applied hypotheses if exist
4687 SALOMEDS::SObject_wrap mySubHypBranch;
4688 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4689 mySubHypBranch.inout() );
4691 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4692 aSubSubGroup->CreateOnDisk();
4694 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4696 for ( ; it->More(); it->Next() ) {
4697 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4698 SALOMEDS::SObject_wrap myRefOnHyp;
4699 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4701 //string myRefOnObject = myRefOnHyp->GetID();
4702 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4703 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4704 int id = myStudyContext->findId( string( objStr.in() ) );
4705 //if ( myRefOnObject.length() > 0 ) {
4706 //aSize[ 0 ] = myRefOnObject.length() + 1;
4707 char hypName[ 30 ], hypId[ 30 ];
4708 sprintf( hypName, "Hyp %d", ++hypNb );
4709 sprintf( hypId, "%d", id );
4710 aSize[ 0 ] = strlen( hypId ) + 1;
4711 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4712 aDataset->CreateOnDisk();
4713 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4714 aDataset->WriteOnDisk( hypId );
4715 aDataset->CloseOnDisk();
4719 aSubSubGroup->CloseOnDisk();
4722 // write applied algorithms if exist
4723 SALOMEDS::SObject_wrap mySubAlgoBranch;
4724 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4725 mySubAlgoBranch.inout() );
4727 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4728 aSubSubGroup->CreateOnDisk();
4730 SALOMEDS::ChildIterator_wrap it =
4731 aStudy->NewChildIterator( mySubAlgoBranch );
4733 for ( ; it->More(); it->Next() ) {
4734 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4735 SALOMEDS::SObject_wrap myRefOnAlgo;
4736 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4738 //string myRefOnObject = myRefOnAlgo->GetID();
4739 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4740 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4741 int id = myStudyContext->findId( string( objStr.in() ) );
4742 //if ( myRefOnObject.length() > 0 ) {
4743 //aSize[ 0 ] = myRefOnObject.length() + 1;
4744 char algoName[ 30 ], algoId[ 30 ];
4745 sprintf( algoName, "Algo %d", ++algoNb );
4746 sprintf( algoId, "%d", id );
4747 aSize[ 0 ] = strlen( algoId ) + 1;
4748 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4749 aDataset->CreateOnDisk();
4750 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4751 aDataset->WriteOnDisk( algoId );
4752 aDataset->CloseOnDisk();
4756 aSubSubGroup->CloseOnDisk();
4758 // close submesh HDF group
4759 aSubGroup->CloseOnDisk();
4762 // close container of submeshes by type HDF group
4763 aGroup->CloseOnDisk();
4767 // store submesh order if any
4768 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4769 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4770 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4771 char order_list[ 30 ];
4772 strcpy( order_list, "Mesh Order" );
4773 // count number of submesh ids
4775 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4776 for ( ; idIt != theOrderIds.end(); idIt++ )
4777 nbIDs += (*idIt).size();
4778 // number of values = number of IDs +
4779 // number of lists (for separators) - 1
4780 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4781 idIt = theOrderIds.begin();
4782 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4783 const TListOfInt& idList = *idIt;
4784 if (idIt != theOrderIds.begin()) // not first list
4785 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4786 // dump submesh ids from current list
4787 TListOfInt::const_iterator id_smId = idList.begin();
4788 for( ; id_smId != idList.end(); id_smId++ )
4789 smIDs[ i++ ] = *id_smId;
4792 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4794 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4795 aDataset->CreateOnDisk();
4796 aDataset->WriteOnDisk( smIDs );
4797 aDataset->CloseOnDisk();
4801 if ( !theOrderIds.empty() && isNewOrederVersion )
4803 // convert ids to entries
4804 std::list< std::list< std::string > > orderEntryLists;
4805 for ( const TListOfInt& idList : theOrderIds )
4807 orderEntryLists.emplace_back();
4808 std::list< std::string > & entryList = orderEntryLists.back();
4809 for ( const int& id : idList )
4811 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4812 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4813 SALOMEDS::SObject_var so = ObjectToSObject( go );
4814 if ( !so->_is_nil() )
4816 CORBA::String_var entry = so->GetID();
4817 entryList.emplace_back( entry.in() );
4821 // convert orderEntryLists to string
4822 std::ostringstream ostream;
4823 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4824 std::string orderEntryString = ostream.str();
4827 aSize[ 0 ] = orderEntryString.size() + 1;
4828 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4829 aDataset->CreateOnDisk();
4830 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4831 aDataset->CloseOnDisk();
4834 // groups root sub-branch
4835 SALOMEDS::SObject_wrap myGroupsBranch;
4836 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4837 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4839 char name_group[ 30 ];
4840 if ( i == GetNodeGroupsTag() )
4841 strcpy( name_group, "Groups of Nodes" );
4842 else if ( i == GetEdgeGroupsTag() )
4843 strcpy( name_group, "Groups of Edges" );
4844 else if ( i == GetFaceGroupsTag() )
4845 strcpy( name_group, "Groups of Faces" );
4846 else if ( i == GetVolumeGroupsTag() )
4847 strcpy( name_group, "Groups of Volumes" );
4848 else if ( i == Get0DElementsGroupsTag() )
4849 strcpy( name_group, "Groups of 0D Elements" );
4850 else if ( i == GetBallElementsGroupsTag() )
4851 strcpy( name_group, "Groups of Balls" );
4853 aGroup = new HDFgroup( name_group, aTopGroup );
4854 aGroup->CreateOnDisk();
4856 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4857 for ( ; it->More(); it->Next() ) {
4858 SALOMEDS::SObject_wrap mySObject = it->Value();
4859 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4860 if ( !CORBA::is_nil( aSubObject ) ) {
4861 SMESH_GroupBase_i* myGroupImpl =
4862 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4865 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4869 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4870 int anId = myStudyContext->findId( string( objStr.in() ) );
4872 // For each group, create a dataset named "Group <group_persistent_id>"
4873 // and store the group's user name into it
4874 const char* grpName = aGrpBaseDS->GetStoreName();
4875 CORBA::String_var aUserName = myGroupImpl->GetName();
4876 aSize[ 0 ] = strlen( aUserName ) + 1;
4878 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4879 aDataset->CreateOnDisk();
4880 aDataset->WriteOnDisk( aUserName );
4881 aDataset->CloseOnDisk();
4884 // For each group, create a dataset named "Group <group_persistent_id> Color"
4885 // and store the group's color into it
4886 char grpColorName[ 30 ];
4887 sprintf( grpColorName, "ColorGroup %d", anId );
4888 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4890 anRGB[ 0 ] = aColor.R;
4891 anRGB[ 1 ] = aColor.G;
4892 anRGB[ 2 ] = aColor.B;
4894 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4895 aDataset->CreateOnDisk();
4896 aDataset->WriteOnDisk( anRGB );
4897 aDataset->CloseOnDisk();
4899 // Pass SMESHDS_Group to MED writer
4900 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4902 myWriter.AddGroup( aGrpDS );
4904 // write reference on a shape if exists
4905 SMESHDS_GroupOnGeom* aGeomGrp =
4906 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4908 SALOMEDS::SObject_wrap mySubRef, myShape;
4909 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4910 mySubRef->ReferencedObject( myShape.inout() ) &&
4911 !CORBA::is_nil( myShape->GetObject() ))
4913 CORBA::String_var myRefOnObject = myShape->GetID();
4914 if ( myRefOnObject.in()[0] ) {
4915 char aRefName[ 30 ];
4916 sprintf( aRefName, "Ref on shape %d", anId);
4917 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4918 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4919 aDataset->CreateOnDisk();
4920 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4921 aDataset->CloseOnDisk();
4924 else // shape ref is invalid:
4926 // save a group on geometry as ordinary group
4927 myWriter.AddGroup( aGeomGrp );
4930 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4931 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4933 std::string str = aFilterGrp_i->FilterToString();
4934 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4935 aSize[ 0 ] = str.length() + 1;
4936 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4937 aDataset->CreateOnDisk();
4938 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4939 aDataset->CloseOnDisk();
4943 aGroup->CloseOnDisk();
4947 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4949 // Flush current mesh information into MED file
4952 // save info on nb of elements
4953 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4955 // maybe a shape was deleted in the study
4956 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4957 TopoDS_Shape nullShape;
4958 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4961 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4966 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4967 aGroup->CreateOnDisk();
4969 // each element belongs to one or none submesh,
4970 // so for each node/element, we store a submesh ID
4972 // Store submesh IDs
4973 for ( int isNode = 0; isNode < 2; ++isNode )
4975 SMDS_ElemIteratorPtr eIt =
4976 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4977 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4980 std::vector<int> smIDs; smIDs.reserve( nbElems );
4981 while ( eIt->more() )
4982 if ( const SMDS_MeshElement* e = eIt->next())
4983 smIDs.push_back( e->getshapeId() );
4985 aSize[ 0 ] = nbElems;
4986 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4987 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4988 aDataset->CreateOnDisk();
4989 aDataset->WriteOnDisk( & smIDs[0] );
4990 aDataset->CloseOnDisk();
4993 aGroup->CloseOnDisk();
4995 // Store node positions on sub-shapes (SMDS_Position):
4996 // ----------------------------------------------------
4998 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4999 aGroup->CreateOnDisk();
5001 // in aGroup, create 5 datasets to contain:
5002 // "Nodes on Edges" - ID of node on edge
5003 // "Edge positions" - U parameter on node on edge
5004 // "Nodes on Faces" - ID of node on face
5005 // "Face U positions" - U parameter of node on face
5006 // "Face V positions" - V parameter of node on face
5008 // Find out nb of nodes on edges and faces
5009 // Collect corresponding sub-meshes
5010 int nbEdgeNodes = 0, nbFaceNodes = 0;
5011 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
5012 // loop on SMESHDS_SubMesh'es
5013 while ( smIt->more() )
5015 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5016 if ( aSubMesh->IsComplexSubmesh() )
5017 continue; // submesh containing other submeshs
5018 int nbNodes = aSubMesh->NbNodes();
5019 if ( nbNodes == 0 ) continue;
5021 int aShapeID = aSubMesh->GetID();
5022 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5024 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5025 // write only SMDS_FacePosition and SMDS_EdgePosition
5026 switch ( aShapeType ) {
5028 nbFaceNodes += nbNodes;
5029 aFaceSM.push_back( aSubMesh );
5032 nbEdgeNodes += nbNodes;
5033 aEdgeSM.push_back( aSubMesh );
5039 // Treat positions on edges or faces
5040 for ( int onFace = 0; onFace < 2; onFace++ )
5042 // Create arrays to store in datasets
5043 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5044 if (!nbNodes) continue;
5045 int* aNodeIDs = new int [ nbNodes ];
5046 double* aUPos = new double [ nbNodes ];
5047 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5050 // loop on sub-meshes
5051 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5052 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5053 for ( ; itSM != pListSM->end(); itSM++ )
5055 SMESHDS_SubMesh* aSubMesh = (*itSM);
5057 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5058 // loop on nodes in aSubMesh
5059 while ( itNode->more() )
5062 const SMDS_MeshNode* node = itNode->next();
5063 aNodeIDs [ iNode ] = node->GetID();
5066 const SMDS_PositionPtr pos = node->GetPosition();
5067 if ( onFace ) { // on FACE
5068 SMDS_FacePositionPtr fPos = pos;
5070 aUPos[ iNode ] = fPos->GetUParameter();
5071 aVPos[ iNode ] = fPos->GetVParameter();
5078 SMDS_EdgePositionPtr ePos = pos;
5080 aUPos[ iNode ] = ePos->GetUParameter();
5086 } // loop on nodes in aSubMesh
5087 } // loop on sub-meshes
5092 aSize[ 0 ] = nbNodes;
5094 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5095 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5096 aDataset->CreateOnDisk();
5097 aDataset->WriteOnDisk( aNodeIDs );
5098 aDataset->CloseOnDisk();
5101 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5102 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5103 aDataset->CreateOnDisk();
5104 aDataset->WriteOnDisk( aUPos );
5105 aDataset->CloseOnDisk();
5108 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5109 aDataset->CreateOnDisk();
5110 aDataset->WriteOnDisk( aVPos );
5111 aDataset->CloseOnDisk();
5116 if ( aVPos ) delete [] aVPos;
5118 } // treat positions on edges or faces
5120 // close "Node Positions" group
5121 aGroup->CloseOnDisk();
5123 } // if ( there are submeshes in SMESHDS_Mesh )
5126 // close mesh HDF group
5127 aTopGroup->CloseOnDisk();
5135 aFile->CloseOnDisk();
5138 // Convert temporary files to stream
5139 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5141 // Remove temporary files and directory
5143 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5145 return aStreamFile._retn();
5148 //=============================================================================
5150 * SMESH_Gen_i::SaveASCII
5152 * Save SMESH module's data in ASCII format
5154 //=============================================================================
5156 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5158 bool isMultiFile ) {
5159 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5160 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5161 return aStreamFile._retn();
5163 //after usual saving needs to encipher binary to text string
5164 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5165 int size = aStreamFile.in().length();
5166 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5167 for ( int i = 0; i < size; i++ )
5168 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5170 buffer[size * 3] = '\0';
5172 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5174 return anAsciiStreamFile._retn();
5177 //=============================================================================
5181 * Load SMESH module's data
5183 //=============================================================================
5185 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5186 const SALOMEDS::TMPFile& theStream,
5190 UpdateStudy(); // load geom data
5191 Kernel_Utils::Localizer loc;
5193 SALOMEDS::Study_var aStudy = getStudyServant();
5195 // Get temporary files location
5196 TCollection_AsciiString tmpDir =
5197 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5199 // Convert the stream into sequence of files to process
5200 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5203 TCollection_AsciiString aStudyName( "" );
5204 if ( isMultiFile ) {
5205 CORBA::WString_var url = aStudy->URL();
5206 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5208 // Set names of temporary files
5209 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5210 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5214 HDFdataset* aDataset;
5215 HDFgroup* aTopGroup;
5217 HDFgroup* aSubGroup;
5218 HDFgroup* aSubSubGroup;
5221 // ---> open HDF file
5222 aFile = new HDFfile( (char*) filename.ToCString() );
5224 aFile->OpenOnDisk( HDF_RDONLY );
5226 catch ( HDFexception ) {
5227 INFOS( "Load(): " << filename << " not found!" );
5231 TPythonDump pd; // prevent dump during loading
5233 // For PAL13473 ("Repetitive mesh") implementation.
5234 // New dependencies between SMESH objects are established:
5235 // now hypotheses can refer to meshes, shapes and other hypotheses.
5236 // To keep data consistent, the following order of data restoration
5238 // 1. Create hypotheses
5239 // 2. Create all meshes
5240 // 3. Load hypotheses' data
5243 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5244 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5245 list< SMESH::Filter_var > filters;
5247 // get total number of top-level groups
5248 int aNbGroups = aFile->nInternalObjects();
5249 if ( aNbGroups > 0 ) {
5250 // --> in first turn we should read&create hypotheses
5251 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5252 // open hypotheses root HDF group
5253 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5254 aTopGroup->OpenOnDisk();
5256 // get number of hypotheses
5257 int aNbObjects = aTopGroup->nInternalObjects();
5258 for ( int j = 0; j < aNbObjects; j++ ) {
5259 // try to identify hypothesis
5260 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5261 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5263 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5264 // open hypothesis group
5265 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5266 aGroup->OpenOnDisk();
5268 // --> get hypothesis id
5269 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5274 // get number of datasets
5275 int aNbSubObjects = aGroup->nInternalObjects();
5276 for ( int k = 0; k < aNbSubObjects; k++ ) {
5278 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5279 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5280 // --> get hypothesis name
5281 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5282 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5283 aDataset->OpenOnDisk();
5284 size = aDataset->GetSize();
5285 char* hypname_str = new char[ size ];
5286 aDataset->ReadFromDisk( hypname_str );
5287 hypname = string( hypname_str );
5288 delete [] hypname_str;
5289 aDataset->CloseOnDisk();
5291 // --> get hypothesis plugin library name
5292 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5293 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5294 aDataset->OpenOnDisk();
5295 size = aDataset->GetSize();
5296 char* libname_str = new char[ size ];
5297 aDataset->ReadFromDisk( libname_str );
5298 if(MYDEBUG) SCRUTE( libname_str );
5299 libname = string( libname_str );
5300 delete [] libname_str;
5301 aDataset->CloseOnDisk();
5303 // --> get hypothesis data
5304 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5305 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5306 aDataset->OpenOnDisk();
5307 size = aDataset->GetSize();
5308 char* hypdata_str = new char[ size ];
5309 aDataset->ReadFromDisk( hypdata_str );
5310 hypdata = string( hypdata_str );
5311 delete [] hypdata_str;
5312 aDataset->CloseOnDisk();
5315 // close hypothesis HDF group
5316 aGroup->CloseOnDisk();
5318 // --> restore hypothesis from data
5319 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5320 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5321 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5322 SMESH::SMESH_Hypothesis_var myHyp;
5324 try { // protect persistence mechanism against exceptions
5325 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5328 INFOS( "Exception during hypothesis creation" );
5331 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5333 // myImpl->LoadFrom( hypdata.c_str() );
5334 hypDataList.push_back( make_pair( myImpl, hypdata ));
5335 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5336 int newId = myStudyContext->findId( iorString.in() );
5337 myStudyContext->mapOldToNew( id, newId );
5340 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5344 // close hypotheses root HDF group
5345 aTopGroup->CloseOnDisk();
5349 // --> then we should read&create algorithms
5350 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5351 // open algorithms root HDF group
5352 aTopGroup = new HDFgroup( "Algorithms", aFile );
5353 aTopGroup->OpenOnDisk();
5355 // get number of algorithms
5356 int aNbObjects = aTopGroup->nInternalObjects();
5357 for ( int j = 0; j < aNbObjects; j++ ) {
5358 // try to identify algorithm
5359 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5360 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5362 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5363 // open algorithm group
5364 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5365 aGroup->OpenOnDisk();
5367 // --> get algorithm id
5368 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5373 // get number of datasets
5374 int aNbSubObjects = aGroup->nInternalObjects();
5375 for ( int k = 0; k < aNbSubObjects; k++ ) {
5377 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5378 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5379 // --> get algorithm name
5380 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5381 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5382 aDataset->OpenOnDisk();
5383 size = aDataset->GetSize();
5384 char* hypname_str = new char[ size ];
5385 aDataset->ReadFromDisk( hypname_str );
5386 hypname = string( hypname_str );
5387 delete [] hypname_str;
5388 aDataset->CloseOnDisk();
5390 // --> get algorithm plugin library name
5391 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5392 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5393 aDataset->OpenOnDisk();
5394 size = aDataset->GetSize();
5395 char* libname_str = new char[ size ];
5396 aDataset->ReadFromDisk( libname_str );
5397 if(MYDEBUG) SCRUTE( libname_str );
5398 libname = string( libname_str );
5399 delete [] libname_str;
5400 aDataset->CloseOnDisk();
5402 // --> get algorithm data
5403 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5404 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5405 aDataset->OpenOnDisk();
5406 size = aDataset->GetSize();
5407 char* hypdata_str = new char[ size ];
5408 aDataset->ReadFromDisk( hypdata_str );
5409 if(MYDEBUG) SCRUTE( hypdata_str );
5410 hypdata = string( hypdata_str );
5411 delete [] hypdata_str;
5412 aDataset->CloseOnDisk();
5415 // close algorithm HDF group
5416 aGroup->CloseOnDisk();
5418 // --> restore algorithm from data
5419 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5420 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5421 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5422 SMESH::SMESH_Hypothesis_var myHyp;
5424 try { // protect persistence mechanism against exceptions
5425 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5427 catch( SALOME::SALOME_Exception& ex )
5429 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5432 INFOS( "Exception during hypothesis creation" );
5435 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5437 //myImpl->LoadFrom( hypdata.c_str() );
5438 hypDataList.push_back( make_pair( myImpl, hypdata ));
5439 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5440 int newId = myStudyContext->findId( iorString.in() );
5441 myStudyContext->mapOldToNew( id, newId );
5444 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5448 // close algorithms root HDF group
5449 aTopGroup->CloseOnDisk();
5453 // --> the rest groups should be meshes
5454 for ( int i = 0; i < aNbGroups; i++ ) {
5455 // identify next group
5456 char meshName[ HDF_NAME_MAX_LEN+1 ];
5457 aFile->InternalObjectIndentify( i, meshName );
5459 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5461 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5465 // open mesh HDF group
5466 aTopGroup = new HDFgroup( meshName, aFile );
5467 aTopGroup->OpenOnDisk();
5469 // get number of child HDF objects
5470 int aNbObjects = aTopGroup->nInternalObjects();
5471 if ( aNbObjects > 0 ) {
5473 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5474 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5475 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5476 if ( !myNewMeshImpl )
5478 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5480 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5481 int newId = myStudyContext->findId( iorString.in() );
5482 myStudyContext->mapOldToNew( id, newId );
5485 // try to read and set auto color flag
5486 char aMeshAutoColorName[ 30 ];
5487 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5488 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5490 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5491 aDataset->OpenOnDisk();
5492 size = aDataset->GetSize();
5493 int* anAutoColor = new int[ size ];
5494 aDataset->ReadFromDisk( anAutoColor );
5495 aDataset->CloseOnDisk();
5496 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5497 delete [] anAutoColor;
5500 // try to read and set reference to shape
5501 GEOM::GEOM_Object_var aShapeObject;
5502 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5503 // load mesh "Ref on shape" - it's an entry to SObject
5504 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5505 aDataset->OpenOnDisk();
5506 size = aDataset->GetSize();
5507 char* refFromFile = new char[ size ];
5508 aDataset->ReadFromDisk( refFromFile );
5509 aDataset->CloseOnDisk();
5510 if ( strlen( refFromFile ) > 0 ) {
5511 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5512 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5513 if ( !CORBA::is_nil( shapeObject ) ) {
5514 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5515 if ( !aShapeObject->_is_nil() )
5516 myNewMeshImpl->SetShape( aShapeObject );
5519 delete [] refFromFile;
5522 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5523 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5525 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5526 aDataset->OpenOnDisk();
5527 size = aDataset->GetSize();
5528 int* meshPersistentId = new int[ size ];
5529 aDataset->ReadFromDisk( meshPersistentId );
5530 aDataset->CloseOnDisk();
5531 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5532 delete [] meshPersistentId;
5535 // Restore SMESH_Mesh_i::_mainShapeTick
5536 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5538 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5539 aDataset->OpenOnDisk();
5540 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5541 aDataset->ReadFromDisk( shapeTick );
5542 aDataset->CloseOnDisk();
5545 // Restore file info
5546 if ( aTopGroup->ExistInternalObject( "file info" ))
5548 aDataset = new HDFdataset( "file info", aTopGroup );
5549 aDataset->OpenOnDisk();
5550 size = aDataset->GetSize();
5551 std::string info( size, ' ');
5552 aDataset->ReadFromDisk( (char*) info.data() );
5553 aDataset->CloseOnDisk();
5554 myNewMeshImpl->FileInfoFromString( info );
5560 // As all object that can be referred by hypothesis are created,
5561 // we can restore hypothesis data
5563 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5564 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5566 SMESH_Hypothesis_i* hyp = hyp_data->first;
5567 string & data = hyp_data->second;
5568 hyp->LoadFrom( data.c_str() );
5571 // Restore the rest mesh data
5573 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5574 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5576 aTopGroup = meshi_group->second;
5577 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5579 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5580 bool hasData = false;
5583 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5584 int newId = myStudyContext->findId( iorString.in() );
5585 int meshOldId = myStudyContext->getOldId( newId );
5587 // try to find mesh data dataset
5588 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5589 // load mesh "has data" flag
5590 aDataset = new HDFdataset( "Has data", aTopGroup );
5591 aDataset->OpenOnDisk();
5592 size = aDataset->GetSize();
5593 char* strHasData = new char[ size ];
5594 aDataset->ReadFromDisk( strHasData );
5595 aDataset->CloseOnDisk();
5596 if ( strcmp( strHasData, "1") == 0 ) {
5599 delete [] strHasData;
5602 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5603 // nodes and elements are not yet put into sub-meshes)
5604 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5605 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5606 aGroup->OpenOnDisk();
5607 // get number of applied algorithms
5608 int aNbSubObjects = aGroup->nInternalObjects();
5609 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5610 for ( int j = 0; j < aNbSubObjects; j++ ) {
5611 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5612 aGroup->InternalObjectIndentify( j, name_dataset );
5613 // check if it is an algorithm
5614 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5615 aDataset = new HDFdataset( name_dataset, aGroup );
5616 aDataset->OpenOnDisk();
5617 size = aDataset->GetSize();
5618 char* refFromFile = new char[ size ];
5619 aDataset->ReadFromDisk( refFromFile );
5620 aDataset->CloseOnDisk();
5621 // san - it is impossible to recover applied algorithms using their entries within Load() method
5622 int id = atoi( refFromFile );
5623 delete [] refFromFile;
5624 string anIOR = myStudyContext->getIORbyOldId( id );
5625 if ( !anIOR.empty() ) {
5626 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5627 if ( !CORBA::is_nil( hypObject ) ) {
5628 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5629 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5630 || !myNewMeshImpl->HasShapeToMesh()) )
5631 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5636 aGroup->CloseOnDisk();
5639 // try to get applied hypotheses
5640 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5641 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5642 aGroup->OpenOnDisk();
5643 // get number of applied hypotheses
5644 int aNbSubObjects = aGroup->nInternalObjects();
5645 for ( int j = 0; j < aNbSubObjects; j++ ) {
5646 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5647 aGroup->InternalObjectIndentify( j, name_dataset );
5648 // check if it is a hypothesis
5649 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5650 aDataset = new HDFdataset( name_dataset, aGroup );
5651 aDataset->OpenOnDisk();
5652 size = aDataset->GetSize();
5653 char* refFromFile = new char[ size ];
5654 aDataset->ReadFromDisk( refFromFile );
5655 aDataset->CloseOnDisk();
5656 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5657 int id = atoi( refFromFile );
5658 delete [] refFromFile;
5659 string anIOR = myStudyContext->getIORbyOldId( id );
5660 if ( !anIOR.empty() ) {
5661 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5662 if ( !CORBA::is_nil( hypObject ) ) {
5663 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5664 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5665 || !myNewMeshImpl->HasShapeToMesh()) )
5666 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5671 aGroup->CloseOnDisk();
5674 // --> try to find SUB-MESHES containers for each type of submesh
5675 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5676 const char* name_meshgroup = 0;
5677 if ( j == GetSubMeshOnVertexTag() )
5678 name_meshgroup = "SubMeshes On Vertex";
5679 else if ( j == GetSubMeshOnEdgeTag() )
5680 name_meshgroup = "SubMeshes On Edge";
5681 else if ( j == GetSubMeshOnWireTag() )
5682 name_meshgroup = "SubMeshes On Wire";
5683 else if ( j == GetSubMeshOnFaceTag() )
5684 name_meshgroup = "SubMeshes On Face";
5685 else if ( j == GetSubMeshOnShellTag() )
5686 name_meshgroup = "SubMeshes On Shell";
5687 else if ( j == GetSubMeshOnSolidTag() )
5688 name_meshgroup = "SubMeshes On Solid";
5689 else if ( j == GetSubMeshOnCompoundTag() )
5690 name_meshgroup = "SubMeshes On Compound";
5692 // try to get submeshes container HDF group
5693 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5694 // open submeshes containers HDF group
5695 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5696 aGroup->OpenOnDisk();
5698 // get number of submeshes
5699 int aNbSubMeshes = aGroup->nInternalObjects();
5700 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5702 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5703 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5704 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5705 // --> get submesh id
5706 int subid = atoi( name_submeshgroup + 7 );
5709 // open submesh HDF group
5710 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5711 aSubGroup->OpenOnDisk();
5713 // try to read and set reference to subshape
5714 GEOM::GEOM_Object_var aSubShapeObject;
5715 SMESH::SMESH_subMesh_var aSubMesh;
5717 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5718 // load submesh "Ref on shape" - it's an entry to SObject
5719 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5720 aDataset->OpenOnDisk();
5721 size = aDataset->GetSize();
5722 char* refFromFile = new char[ size ];
5723 aDataset->ReadFromDisk( refFromFile );
5724 aDataset->CloseOnDisk();
5725 if ( strlen( refFromFile ) > 0 ) {
5726 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5727 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5728 if ( !CORBA::is_nil( subShapeObject ) ) {
5729 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5730 if ( !aSubShapeObject->_is_nil() )
5731 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5732 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5733 if ( aSubMesh->_is_nil() )
5735 string iorSubString = GetORB()->object_to_string( aSubMesh );
5736 int newSubId = myStudyContext->findId( iorSubString );
5737 myStudyContext->mapOldToNew( subid, newSubId );
5740 delete [] refFromFile;
5743 if ( aSubMesh->_is_nil() )
5746 // try to get applied algorithms
5747 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5748 // open "applied algorithms" HDF group
5749 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5750 aSubSubGroup->OpenOnDisk();
5751 // get number of applied algorithms
5752 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5753 for ( int l = 0; l < aNbSubObjects; l++ ) {
5754 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5755 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5756 // check if it is an algorithm
5757 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5758 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5759 aDataset->OpenOnDisk();
5760 size = aDataset->GetSize();
5761 char* refFromFile = new char[ size ];
5762 aDataset->ReadFromDisk( refFromFile );
5763 aDataset->CloseOnDisk();
5765 int id = atoi( refFromFile );
5766 string anIOR = myStudyContext->getIORbyOldId( id );
5767 if ( !anIOR.empty() ) {
5768 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5769 if ( !CORBA::is_nil( hypObject ) ) {
5770 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5771 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5772 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5775 delete [] refFromFile;
5778 // close "applied algorithms" HDF group
5779 aSubSubGroup->CloseOnDisk();
5782 // try to get applied hypotheses
5783 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5784 // open "applied hypotheses" HDF group
5785 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5786 aSubSubGroup->OpenOnDisk();
5787 // get number of applied hypotheses
5788 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5789 for ( int l = 0; l < aNbSubObjects; l++ ) {
5790 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5791 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5792 // check if it is a hypothesis
5793 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5794 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5795 aDataset->OpenOnDisk();
5796 size = aDataset->GetSize();
5797 char* refFromFile = new char[ size ];
5798 aDataset->ReadFromDisk( refFromFile );
5799 aDataset->CloseOnDisk();
5801 int id = atoi( refFromFile );
5802 string anIOR = myStudyContext->getIORbyOldId( id );
5803 if ( !anIOR.empty() ) {
5804 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5805 if ( !CORBA::is_nil( hypObject ) ) {
5806 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5807 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5808 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5811 delete [] refFromFile;
5814 // close "APPLIED HYPOTHESES" hdf group
5815 aSubSubGroup->CloseOnDisk();
5818 // close SUB-MESH hdf group
5819 aSubGroup->CloseOnDisk();
5822 // close SUB-MESHES containers hdf group
5823 aGroup->CloseOnDisk();
5827 // try to get GROUPS
5828 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5829 char name_group[ 30 ];
5830 if ( ii == GetNodeGroupsTag() )
5831 strcpy( name_group, "Groups of Nodes" );
5832 else if ( ii == GetEdgeGroupsTag() )
5833 strcpy( name_group, "Groups of Edges" );
5834 else if ( ii == GetFaceGroupsTag() )
5835 strcpy( name_group, "Groups of Faces" );
5836 else if ( ii == GetVolumeGroupsTag() )
5837 strcpy( name_group, "Groups of Volumes" );
5838 else if ( ii == Get0DElementsGroupsTag() )
5839 strcpy( name_group, "Groups of 0D Elements" );
5840 else if ( ii == GetBallElementsGroupsTag() )
5841 strcpy( name_group, "Groups of Balls" );
5843 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5844 aGroup = new HDFgroup( name_group, aTopGroup );
5845 aGroup->OpenOnDisk();
5846 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5847 // within aGroup->ExistInternalObject( name )
5848 std::vector< std::string > subNames;
5849 TColStd_MapOfAsciiString mapOfNames;
5850 aGroup->GetAllObjects( subNames );
5851 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5852 mapOfNames.Add( subNames[ iN ].c_str() );
5854 for ( size_t j = 0; j < subNames.size(); j++ ) {
5855 const std::string& name_dataset = subNames[ j ];
5856 // check if it is a group
5857 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5860 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5863 int groupID = -1; // group local ID (also persistent)
5865 groupID = atoi( endptr + 1 );
5866 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5867 aDataset->OpenOnDisk();
5869 // Retrieve actual group name
5870 size = aDataset->GetSize();
5871 char* nameFromFile = new char[ size ];
5872 aDataset->ReadFromDisk( nameFromFile );
5873 aDataset->CloseOnDisk();
5875 // Try to find a shape reference
5876 TopoDS_Shape aShape;
5877 char aRefName[ 30 ];
5878 sprintf( aRefName, "Ref on shape %d", subid);
5879 if ( mapOfNames.Contains( aRefName ))
5881 // load mesh "Ref on shape" - it's an entry to SObject
5882 aDataset = new HDFdataset( aRefName, aGroup );
5883 aDataset->OpenOnDisk();
5884 size = aDataset->GetSize();
5885 char* refFromFile = new char[ size ];
5886 aDataset->ReadFromDisk( refFromFile );
5887 aDataset->CloseOnDisk();
5888 if ( strlen( refFromFile ) > 0 ) {
5889 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5890 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5891 if ( !CORBA::is_nil( shapeObject ) ) {
5892 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5893 if ( !aShapeObject->_is_nil() )
5894 aShape = GeomObjectToShape( aShapeObject );
5897 delete [] refFromFile;
5899 // Try to read a filter of SMESH_GroupOnFilter
5900 SMESH::Filter_var filter;
5901 SMESH_PredicatePtr predicate;
5902 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5903 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5905 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5906 aDataset->OpenOnDisk();
5907 size = aDataset->GetSize();
5908 char* persistStr = new char[ size ];
5909 aDataset->ReadFromDisk( persistStr );
5910 aDataset->CloseOnDisk();
5911 if ( strlen( persistStr ) > 0 ) {
5912 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5913 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5914 filters.push_back( filter );
5916 delete [] persistStr;
5919 // Create group servant
5920 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5921 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5922 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5923 delete [] nameFromFile;
5924 // Obtain a SMESHDS_Group object
5925 if ( aNewGroup->_is_nil() )
5928 string iorSubString = GetORB()->object_to_string( aNewGroup );
5929 int newSubId = myStudyContext->findId( iorSubString );
5930 myStudyContext->mapOldToNew( subid, newSubId );
5932 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5936 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5937 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5939 aFilterGroup->SetFilter( filter );
5940 filter->UnRegister();
5942 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5943 if ( !aGroupBaseDS )
5946 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5949 // Read color of the group
5950 char aGroupColorName[ 30 ];
5951 sprintf( aGroupColorName, "ColorGroup %d", subid);
5952 if ( mapOfNames.Contains( aGroupColorName ))
5954 aDataset = new HDFdataset( aGroupColorName, aGroup );
5955 aDataset->OpenOnDisk();
5956 size = aDataset->GetSize();
5957 double* anRGB = new double[ size ];
5958 aDataset->ReadFromDisk( anRGB );
5959 aDataset->CloseOnDisk();
5960 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5961 aGroupBaseDS->SetColor( aColor );
5966 aGroup->CloseOnDisk();
5970 // instead of reading mesh data, we read only brief information of all
5971 // objects: mesh, groups, sub-meshes (issue 0021208)
5974 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5975 meshfile.ToCString(), filename.ToCString(),
5979 // read Sub-Mesh ORDER if any
5980 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
5981 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5982 aDataset->OpenOnDisk();
5983 size = aDataset->GetSize();
5984 int* smIDs = new int[ size ];
5985 aDataset->ReadFromDisk( smIDs );
5986 aDataset->CloseOnDisk();
5987 TListOfListOfInt anOrderIds;
5988 anOrderIds.push_back( TListOfInt() );
5989 for ( int i = 0; i < size; i++ )
5990 if ( smIDs[ i ] < 0 ) // is separator
5991 anOrderIds.push_back( TListOfInt() );
5993 anOrderIds.back().push_back(smIDs[ i ]);
5995 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5998 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
6000 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
6001 aDataset->OpenOnDisk();
6002 size = aDataset->GetSize();
6003 std::string dataString; dataString.resize( size );
6004 aDataset->ReadFromDisk((char*) dataString.data() );
6005 aDataset->CloseOnDisk();
6007 std::istringstream istream( dataString.data() );
6008 boost::archive::text_iarchive archive( istream );
6009 std::list< std::list< std::string > > orderEntryLists;
6011 archive >> orderEntryLists;
6015 TListOfListOfInt anOrderIds;
6016 for ( const std::list< std::string >& entryList : orderEntryLists )
6018 anOrderIds.emplace_back();
6019 for ( const std::string & entry : entryList )
6021 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6022 TopoDS_Shape shape = GeomObjectToShape( go );
6023 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6024 anOrderIds.back().emplace_back( sm->GetId() );
6027 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6031 // update hyps needing full mesh data restored (issue 20918)
6032 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6034 SMESH_Hypothesis_i* hyp = hyp_data->first;
6035 hyp->UpdateAsMeshesRestored();
6038 // notify algos on completed restoration to set sub-mesh event listeners
6039 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6041 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6042 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6044 TopoDS_Shape myLocShape;
6045 if(myLocMesh.HasShapeToMesh())
6046 myLocShape = myLocMesh.GetShapeToMesh();
6048 myLocShape = SMESH_Mesh::PseudoShape();
6050 myLocMesh.GetSubMesh(myLocShape)->
6051 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6054 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6055 list< SMESH::Filter_var >::iterator f = filters.begin();
6056 for ( ; f != filters.end(); ++f )
6057 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6058 fi->FindBaseObjects();
6063 aTopGroup->CloseOnDisk();
6066 aFile->CloseOnDisk();
6069 // Remove temporary files created from the stream
6072 SMESH_File meshFile( meshfile.ToCString() );
6073 if ( !meshFile ) // no meshfile exists
6075 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6079 Engines::Container_var container = GetContainerRef();
6080 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6082 container_i->registerTemporaryFile( filename.ToCString() );
6083 container_i->registerTemporaryFile( meshfile.ToCString() );
6084 container_i->registerTemporaryFile( tmpDir.ToCString() );
6089 // creation of tree nodes for all data objects in the study
6090 // to support tree representation customization and drag-n-drop:
6091 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6092 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6093 useCaseBuilder->SetRootCurrent();
6094 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6095 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6096 for (it->InitEx(true); it->More(); it->Next()) {
6097 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6104 //=============================================================================
6106 * SMESH_Gen_i::LoadASCII
6108 * Load SMESH module's data in ASCII format
6110 //=============================================================================
6112 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6113 const SALOMEDS::TMPFile& theStream,
6115 bool isMultiFile ) {
6116 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6117 return Load( theComponent, theStream, theURL, isMultiFile );
6119 //before call main ::Load method it's need for decipher text format to
6120 //binary ( "|xx" => x' )
6121 int size = theStream.length();
6122 if ( int((size / 3 )*3) != size ) //error size of buffer
6125 int real_size = int(size / 3);
6127 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6130 unsigned int c = -1;
6131 for ( int i = 0; i < real_size; i++ )
6133 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6134 sscanf( tmp, "%x", &c );
6135 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6138 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6140 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6143 //=============================================================================
6145 * SMESH_Gen_i::Close
6147 * Clears study-connected data when it is closed
6149 //=============================================================================
6151 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6153 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6155 // Clear study contexts data
6156 myStudyContext->Clear();
6158 // remove the tmp files meshes are loaded from
6159 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6161 // Clean trace of API methods calls
6167 //=============================================================================
6169 * SMESH_Gen_i::ComponentDataType
6171 * Get component data type
6173 //=============================================================================
6175 char* SMESH_Gen_i::ComponentDataType()
6177 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6178 return CORBA::string_dup( "SMESH" );
6182 //=============================================================================
6184 * SMESH_Gen_i::IORToLocalPersistentID
6186 * Transform data from transient form to persistent
6188 //=============================================================================
6190 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6191 const char* IORString,
6192 CORBA::Boolean /*isMultiFile*/,
6193 CORBA::Boolean /*isASCII*/ )
6195 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6197 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6198 int anId = myStudyContext->findId( IORString );
6200 if(MYDEBUG) MESSAGE( "VSR " << anId )
6202 sprintf( strId, "%d", anId );
6203 return CORBA::string_dup( strId );
6206 return CORBA::string_dup( "" );
6209 //=============================================================================
6211 * SMESH_Gen_i::LocalPersistentIDToIOR
6213 * Transform data from persistent form to transient
6215 //=============================================================================
6217 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6218 const char* aLocalPersistentID,
6219 CORBA::Boolean /*isMultiFile*/,
6220 CORBA::Boolean /*isASCII*/ )
6222 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6224 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6225 int anId = atoi( aLocalPersistentID );
6226 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6228 return CORBA::string_dup( "" );
6231 //=======================================================================
6232 //function : RegisterObject
6234 //=======================================================================
6236 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6238 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6239 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6240 return myStudyContext->addObject( string( iorString.in() ) );
6245 //================================================================================
6247 * \brief Return id of registered object
6248 * \param theObject - the Object
6249 * \retval int - Object id
6251 //================================================================================
6253 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6255 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6256 string iorString = GetORB()->object_to_string( theObject );
6257 return myStudyContext->findId( iorString );
6262 //=============================================================================
6264 * SMESH_Gen_i::SetName
6266 * Set a new object name
6268 //=============================================================================
6270 void SMESH_Gen_i::SetName(const char* theIOR,
6271 const char* theName)
6273 if ( theIOR && strcmp( theIOR, "" ) ) {
6274 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6275 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6276 if ( !aSO->_is_nil() ) {
6277 SetName( aSO, theName );
6282 // Version information
6283 char* SMESH_Gen_i::getVersion()
6285 #if SMESH_DEVELOPMENT
6286 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6288 return CORBA::string_dup(SMESH_VERSION_STR);
6292 //=================================================================================
6293 // function : Move()
6294 // purpose : Moves objects to the specified position.
6295 // Is used in the drag-n-drop functionality.
6296 //=================================================================================
6298 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6299 SALOMEDS::SObject_ptr where,
6302 if ( CORBA::is_nil( where ) ) return;
6304 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6305 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6306 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6307 std::string dataType = father->ComponentDataType();
6308 if ( dataType != "SMESH" ) return; // not a SMESH component
6310 SALOMEDS::SObject_var objAfter;
6311 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6312 // insert at given row -> find insertion position
6313 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6315 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6316 if ( i == row && useCaseIt->More() ) {
6317 objAfter = useCaseIt->Value();
6321 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6322 SALOMEDS::SObject_var sobj = what[i];
6323 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6324 // insert the object to the use case tree
6325 if ( !CORBA::is_nil( objAfter ) )
6326 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6328 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6331 //================================================================================
6333 * \brief Returns true if algorithm can be used to mesh a given geometry
6334 * \param [in] theAlgoType - the algorithm type
6335 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6336 * \param [in] theGeomObject - the geometry to mesh
6337 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6338 * else, returns \c True if at least one shape is meshable
6339 * \return CORBA::Boolean - can or can't
6341 //================================================================================
6343 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6344 const char* theLibName,
6345 GEOM::GEOM_Object_ptr theGeomObject,
6346 CORBA::Boolean toCheckAll)
6350 std::string aPlatformLibName;
6351 GenericHypothesisCreator_i* aCreator =
6352 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6355 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6356 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6357 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6364 SMESH_CATCH( SMESH::doNothing );
6367 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6372 //================================================================================
6374 * \brief Collect indices of elements, which are located inside the sphere
6376 //================================================================================
6378 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6379 SMESH::ElementType theElemType,
6385 SMESH::long_array_var aResult = new SMESH::long_array();
6386 if ( meshPart->_is_nil() )
6387 return aResult._retn();
6389 // 1. Create geometrical object
6390 gp_Pnt aP( theX, theY, theZ );
6391 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6393 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6395 if ( lst.size() > 0 ) {
6396 aResult->length( lst.size() );
6397 for ( size_t i = 0; i < lst.size(); i++ ) {
6398 aResult[i] = lst[i];
6401 return aResult._retn();
6404 //================================================================================
6406 * \brief Collect indices of elements, which are located inside the box
6408 //================================================================================
6410 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6411 SMESH::ElementType theElemType,
6412 CORBA::Double theX1,
6413 CORBA::Double theY1,
6414 CORBA::Double theZ1,
6415 CORBA::Double theX2,
6416 CORBA::Double theY2,
6417 CORBA::Double theZ2)
6419 SMESH::long_array_var aResult = new SMESH::long_array();
6420 if( meshPart->_is_nil() )
6421 return aResult._retn();
6423 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6424 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6426 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6428 if( lst.size() > 0 ) {
6429 aResult->length( lst.size() );
6430 for ( size_t i = 0; i < lst.size(); i++ ) {
6431 aResult[i] = lst[i];
6434 return aResult._retn();
6437 //================================================================================
6439 * \brief Collect indices of elements, which are located inside the cylinder
6441 //================================================================================
6443 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6444 SMESH::ElementType theElemType,
6448 CORBA::Double theDX,
6449 CORBA::Double theDY,
6450 CORBA::Double theDZ,
6452 CORBA::Double theR )
6454 SMESH::long_array_var aResult = new SMESH::long_array();
6455 if( meshPart->_is_nil() )
6456 return aResult._retn();
6458 gp_Pnt aP( theX, theY, theZ );
6459 gp_Vec aV( theDX, theDY, theDZ );
6460 gp_Ax2 anAxes (aP, aV);
6462 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6464 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6466 if( lst.size() > 0 ) {
6467 aResult->length( lst.size() );
6468 for ( size_t i = 0; i < lst.size(); i++ ) {
6469 aResult[i] = lst[i];
6472 return aResult._retn();
6475 //================================================================================
6477 * \brief Collect indices of elements, which are located inside the geom object
6479 //================================================================================
6481 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6482 SMESH::ElementType theElemType,
6483 GEOM::GEOM_Object_ptr theGeom,
6484 CORBA::Double theTolerance )
6486 SMESH::long_array_var aResult = new SMESH::long_array();
6487 if( meshPart->_is_nil() || theGeom->_is_nil() )
6488 return aResult._retn();
6490 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6492 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6494 if( lst.size() > 0 ) {
6495 aResult->length( lst.size() );
6496 for ( size_t i = 0; i < lst.size(); i++ ) {
6497 aResult[i] = lst[i];
6500 return aResult._retn();
6503 //================================================================================
6505 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6507 //================================================================================
6509 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6510 SMESH::ElementType theElemType,
6511 const TopoDS_Shape& theShape,
6512 double* theTolerance) {
6514 std::vector<long> res;
6515 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6517 if ( mesh->_is_nil() )
6520 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6524 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6529 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6530 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6531 anElementsOnShape->SetAllNodes( true );
6532 anElementsOnShape->SetMesh( meshDS );
6533 anElementsOnShape->SetShape( theShape, aType );
6536 anElementsOnShape->SetTolerance(*theTolerance);
6538 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6539 if ( !msource->_is_nil() ) { // Mesh case
6540 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6542 while ( elemIt->more() ) {
6543 const SMDS_MeshElement* anElem = elemIt->next();
6544 long anId = anElem->GetID();
6545 if ( anElementsOnShape->IsSatisfy( anId ) )
6546 res.push_back( anId );
6550 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6551 if ( !gsource->_is_nil() ) {
6552 if(theElemType == SMESH::NODE) {
6553 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6554 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6555 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6556 long anId = node->GetID();
6557 if ( anElementsOnShape->IsSatisfy( anId ) )
6558 res.push_back( anId );
6561 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6562 SMESH::long_array_var elems = gsource->GetListOfID();
6563 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6564 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6565 long anId = elem->GetID();
6566 if ( anElementsOnShape->IsSatisfy( anId ) )
6567 res.push_back( anId );
6572 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6573 if ( !smsource->_is_nil() ) {
6574 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6575 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6576 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6578 long anId = elem->GetID();
6579 if ( anElementsOnShape->IsSatisfy( anId ) )
6580 res.push_back( anId );