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>
57 #include <libgen.h> // for basename function
61 #define LibHandle HMODULE
62 #define LoadLib( name ) LoadLibrary( name )
63 #define GetProc GetProcAddress
64 #define UnLoadLib( handle ) FreeLibrary( handle );
66 #define LibHandle void*
68 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
69 #else // DYNLOAD_LOCAL
70 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
71 #endif // DYNLOAD_LOCAL
73 #define UnLoadLib( handle ) dlclose( handle );
76 #include "SMESH_Gen_i.hxx"
77 #include "SMESH_version.h"
79 #include "DriverMED_W_SMESHDS_Mesh.h"
80 #include "DriverMED_R_SMESHDS_Mesh.h"
82 #include "DriverCGNS_Read.hxx"
84 #include "MED_Factory.hxx"
85 #include "SMDS_EdgePosition.hxx"
86 #include "SMDS_FacePosition.hxx"
87 #include "SMDS_SetIterator.hxx"
88 #include "SMDS_SpacePosition.hxx"
89 #include "SMDS_VertexPosition.hxx"
90 #include "SMESHDS_Document.hxx"
91 #include "SMESHDS_Group.hxx"
92 #include "SMESHDS_GroupOnGeom.hxx"
93 #include "SMESH_Algo_i.hxx"
94 #include "SMESH_File.hxx"
95 #include "SMESH_Group.hxx"
96 #include "SMESH_Group_i.hxx"
97 #include "SMESH_Hypothesis.hxx"
98 #include "SMESH_Hypothesis_i.hxx"
99 #include "SMESH_Mesh.hxx"
100 #include "SMESH_MeshEditor.hxx"
101 #include "SMESH_Mesh_i.hxx"
102 #include "SMESH_PreMeshInfo.hxx"
103 #include "SMESH_PythonDump.hxx"
104 #include "SMESH_ControlsDef.hxx"
106 // to pass CORBA exception through SMESH_TRY
107 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
108 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
110 #include CORBA_SERVER_HEADER(SMESH_Group)
111 #include CORBA_SERVER_HEADER(SMESH_Filter)
112 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
115 #include <GEOMImpl_Types.hxx>
116 #include <GEOM_Client.hxx>
118 #include <Basics_Utils.hxx>
119 #include <Basics_DirUtils.hxx>
121 #include <OpUtil.hxx>
122 #include <SALOMEDS_Tool.hxx>
123 #include <SALOME_Container_i.hxx>
124 #include <SALOME_LifeCycleCORBA.hxx>
125 #include <SALOME_NamingService.hxx>
126 #include <Utils_CorbaException.hxx>
127 #include <Utils_ExceptHandlers.hxx>
128 #include <Utils_SINGLETON.hxx>
129 #include <utilities.h>
131 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
132 #include CORBA_CLIENT_HEADER(SALOME_Session)
134 // helpers about SALOME::GenericObj
135 #include <SALOMEDS_wrap.hxx>
136 #include <SALOMEDS_Attributes_wrap.hxx>
137 #include <GEOM_wrap.hxx>
146 #include <boost/archive/text_oarchive.hpp>
147 #include <boost/archive/text_iarchive.hpp>
148 #include <boost/serialization/list.hpp>
149 #include <boost/serialization/string.hpp>
152 using SMESH::TPythonDump;
155 #define NUM_TMP_FILES 2
158 static int MYDEBUG = 0;
160 static int MYDEBUG = 0;
163 // Static variables definition
164 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
165 CORBA::ORB_var SMESH_Gen_i::myOrb;
166 PortableServer::POA_var SMESH_Gen_i::myPoa;
167 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
168 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
169 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
172 const int nbElemPerDiagonal = 10;
174 //=============================================================================
176 * GetServant [ static ]
178 * Get servant of the CORBA object
180 //=============================================================================
182 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
184 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
187 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
190 catch (PortableServer::POA::ObjectNotActive &ex)
192 INFOS("GetServant: ObjectNotActive");
195 catch (PortableServer::POA::WrongAdapter &ex)
197 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
200 catch (PortableServer::POA::WrongPolicy &ex)
202 INFOS("GetServant: WrongPolicy");
207 INFOS( "GetServant - Unknown exception was caught!!!" );
212 //=============================================================================
214 * SObjectToObject [ static ]
216 * Get CORBA object corresponding to the SALOMEDS::SObject
218 //=============================================================================
220 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
222 SALOMEDS::GenericAttribute_wrap anAttr;
223 CORBA::Object_var anObj;
224 if ( !theSObject->_is_nil() ) {
226 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
227 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
228 CORBA::String_var aValue = anIOR->Value();
229 if( strcmp( aValue, "" ) != 0 )
230 anObj = GetORB()->string_to_object( aValue );
234 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
240 //=============================================================================
244 * Get SALOME_NamingService object
246 //=============================================================================
248 SALOME_NamingService* SMESH_Gen_i::GetNS()
250 if ( myNS == NULL ) {
251 myNS = SINGLETON_<SALOME_NamingService>::Instance();
252 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
253 myNS->init_orb( GetORB() );
258 //=============================================================================
262 * Get SALOME_LifeCycleCORBA object
264 //=============================================================================
266 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
268 if ( myLCC == NULL ) {
269 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
274 //=============================================================================
276 * GetGeomEngine [ static ]
278 * Get GEOM::GEOM_Gen reference
280 //=============================================================================
282 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
284 GEOM::GEOM_Gen_ptr gen = GEOM::GEOM_Gen::_nil();
285 if ( !CORBA::is_nil( go ))
290 //=============================================================================
292 * SMESH_Gen_i::SMESH_Gen_i
294 * Default constructor: not for use
296 //=============================================================================
298 SMESH_Gen_i::SMESH_Gen_i()
302 //=============================================================================
304 * SMESH_Gen_i::SMESH_Gen_i
306 * Standard constructor, used with Container
308 //=============================================================================
310 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
311 PortableServer::POA_ptr poa,
312 PortableServer::ObjectId* contId,
313 const char* instanceName,
314 const char* interfaceName,
316 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName, false, checkNS )
319 myOrb = CORBA::ORB::_duplicate(orb);
320 myPoa = PortableServer::POA::_duplicate(poa);
323 _id = myPoa->activate_object( _thisObj );
325 myStudyContext = new StudyContext;
327 myIsEmbeddedMode = false;
328 myIsEnablePublish = true;
329 myShapeReader = NULL; // shape reader
331 myIsHistoricalPythonDump = true;
332 myToForgetMeshDataOnHypModif = false;
334 // set it in standalone mode only
335 //OSD::SetSignal( true );
337 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
338 // find out mode (embedded or standalone) here else
339 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
340 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
343 if ( SALOME_NamingService* ns = GetNS() )
345 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
346 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
347 if ( !session->_is_nil() )
349 CORBA::String_var str_host = session->getHostname();
350 CORBA::Long s_pid = session->getPID();
351 string my_host = Kernel_Utils::GetHostname();
353 long my_pid = (long)_getpid();
355 long my_pid = (long) getpid();
357 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
363 //=============================================================================
365 * SMESH_Gen_i::~SMESH_Gen_i
369 //=============================================================================
371 SMESH_Gen_i::~SMESH_Gen_i()
373 // delete hypothesis creators
374 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
375 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
377 // same creator can be mapped under different names
378 GenericHypothesisCreator_i* creator = (*itHyp).second;
382 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
383 if ( creator == (*itHyp2).second )
384 (*itHyp2).second = 0;
386 myHypCreatorMap.clear();
388 // Clear study contexts data
389 delete myStudyContext;
391 // delete shape reader
393 delete myShapeReader;
396 //=============================================================================
398 * SMESH_Gen_i::getHypothesisCreator
400 * Get hypothesis creator
402 //=============================================================================
404 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
405 const char* theLibName,
406 std::string& thePlatformLibName)
408 std::string aPlatformLibName;
409 /* It's Need to translate lib name for WIN32 or X platform */
410 if ( theLibName && theLibName[0] != '\0' )
412 int libNameLen = strlen(theLibName);
413 //check for old format "libXXXXXXX.so"
414 if (libNameLen > 7 &&
415 !strncmp( theLibName, "lib", 3 ) &&
416 !strcmp( theLibName+libNameLen-3, ".so" ))
420 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
421 #elif defined(__APPLE__)
422 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
424 aPlatformLibName = theLibName;
429 //try to use new format
431 aPlatformLibName = theLibName;
432 aPlatformLibName += ".dll";
433 #elif defined(__APPLE__)
434 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
436 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
440 thePlatformLibName = aPlatformLibName;
442 Unexpect aCatch(SALOME_SalomeException);
443 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
445 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
446 GenericHypothesisCreator_i* aCreator;
449 // check, if creator for this hypothesis type already exists
450 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
452 // load plugin library
453 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
456 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
458 const char* path = aPlatformLibName.c_str();
461 const char* path = aPlatformLibName.c_str();
463 LibHandle libHandle = LoadLib( path );
464 #if defined(WIN32) && defined(UNICODE)
469 // report any error, if occurred
471 const char* anError = dlerror();
472 throw(SALOME_Exception( anError ));
474 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
475 << aPlatformLibName));
479 // get method, returning hypothesis creator
480 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
481 GetHypothesisCreator procHandle =
482 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
485 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
486 << aPlatformLibName ));
487 UnLoadLib(libHandle);
490 // get hypothesis creator
491 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
492 aCreator = procHandle(theHypName);
495 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
496 << aPlatformLibName));
498 // map hypothesis creator to a hypothesis name
499 myHypCreatorMap[string(theHypName)] = aCreator;
504 return myHypCreatorMap[string(theHypName)];
507 catch (SALOME_Exception& S_ex)
509 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
514 //=============================================================================
516 * SMESH_Gen_i::createHypothesis
518 * Create hypothesis of given type
520 //=============================================================================
522 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
523 const char* theLibName)
525 SMESH_Hypothesis_i* myHypothesis_i = 0;
526 SMESH::SMESH_Hypothesis_var hypothesis_i;
527 std::string aPlatformLibName;
528 GenericHypothesisCreator_i* aCreator =
529 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
531 // create a new hypothesis object, store its ref. in studyContext
532 myHypothesis_i = aCreator->Create(myPoa, &myGen);
535 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
536 CORBA::String_var hypName = myHypothesis_i->GetName();
537 myHypCreatorMap[ hypName.in() ] = aCreator;
539 // activate the CORBA servant of hypothesis
540 hypothesis_i = myHypothesis_i->_this();
541 int nextId = RegisterObject( hypothesis_i );
542 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
543 else { (void)nextId; } // avoid "unused variable" warning in release mode
545 return hypothesis_i._retn();
548 //=============================================================================
550 * SMESH_Gen_i::createMesh
552 * Create empty mesh on shape
554 //=============================================================================
556 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
558 Unexpect aCatch(SALOME_SalomeException);
559 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
561 // Get or create the GEOM_Client instance
563 // create a new mesh object servant, store it in a map in study context
564 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
565 // create a new mesh object
566 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
567 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
569 // activate the CORBA servant of Mesh
570 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
571 int nextId = RegisterObject( mesh );
572 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
573 else { (void)nextId; } // avoid "unused variable" warning in release mode
576 catch (SALOME_Exception& S_ex) {
577 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
579 return SMESH::SMESH_Mesh::_nil();
582 //=============================================================================
584 * SMESH_Gen_i::GetShapeReader
588 //=============================================================================
590 GEOM_Client* SMESH_Gen_i::GetShapeReader()
592 // create shape reader if necessary
593 if ( !myShapeReader )
594 myShapeReader = new GEOM_Client(GetContainerRef());
595 ASSERT( myShapeReader );
596 return myShapeReader;
599 //=============================================================================
601 * SMESH_Gen_i::SetGeomEngine
603 * Set GEOM::GEOM_Gen reference
605 //=============================================================================
607 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
609 myGeomGen = GEOM::GEOM_Gen::_duplicate( geomcompo );
612 //=============================================================================
614 * SMESH_Gen_i::SetEmbeddedMode
618 //=============================================================================
620 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
622 myIsEmbeddedMode = theMode;
624 if ( !myIsEmbeddedMode ) {
625 //PAL10867: disable signals catching with "noexcepthandler" option
626 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
627 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
632 char* envDisableFPE = getenv("DISABLE_FPE");
633 if (envDisableFPE && atoi(envDisableFPE))
638 OSD::SetSignal( raiseFPE );
640 // else OSD::SetSignal() is called in GUI
644 //=============================================================================
646 * SMESH_Gen_i::IsEmbeddedMode
650 //=============================================================================
652 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
654 return myIsEmbeddedMode;
657 //=============================================================================
659 * SMESH_Gen_i::SetEnablePublish
661 * Set enable publishing in the study
663 //=============================================================================
665 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
667 myIsEnablePublish = theIsEnablePublish;
670 //=============================================================================
672 * SMESH_Gen_i::IsEnablePublish
674 * Check enable publishing
676 //=============================================================================
678 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
680 return myIsEnablePublish;
683 //=============================================================================
685 * SMESH_Gen_i::UpdateStudy
687 * Update study (needed at switching GEOM->SMESH)
689 //=============================================================================
691 void SMESH_Gen_i::UpdateStudy()
693 if ( !myStudyContext )
694 myStudyContext = new StudyContext;
696 SALOMEDS::Study_var aStudy = getStudyServant();
697 if ( !CORBA::is_nil( aStudy ) )
699 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
701 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
702 if( !GEOM_var->_is_nil() )
703 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
705 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
706 if( !GEOM_var->_is_nil() )
707 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
709 // NPAL16168, issue 0020210
710 // Let meshes update their data depending on GEOM groups that could change
711 CORBA::String_var compDataType = ComponentDataType();
712 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
713 if ( !me->_is_nil() ) {
714 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
715 for ( ; anIter->More(); anIter->Next() ) {
716 SALOMEDS::SObject_wrap so = anIter->Value();
717 CORBA::Object_var ior = SObjectToObject( so );
718 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
719 mesh->CheckGeomModif();
725 //================================================================================
727 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
729 //================================================================================
731 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
733 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
734 SALOMEDS::GenericAttribute_wrap attr;
735 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
737 SALOMEDS::AttributePixMap_wrap pm = attr;
738 CORBA::String_var ico = pm->GetPixMap();
739 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
744 //=================================================================================
745 // function : hasObjectInfo()
746 // purpose : shows if module provides information for its objects
747 //=================================================================================
749 bool SMESH_Gen_i::hasObjectInfo()
754 //=================================================================================
755 // function : getObjectInfo()
756 // purpose : returns an information for a given object by its entry
757 //=================================================================================
759 char* SMESH_Gen_i::getObjectInfo( const char* entry )
761 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
762 // for the rest, "module 'SMESH', ID=0:1:2:*"
766 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
767 CORBA::Object_var obj = SObjectToObject( so );
768 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
769 if ( isGeomModifIcon( mesh ))
771 txt << "The geometry was changed and the mesh needs to be recomputed";
776 CORBA::String_var compType = ComponentDataType();
777 txt << "module '" << compType << "', ID=" << entry;
779 return CORBA::string_dup( txt );
782 //=============================================================================
784 * SMESH_Gen_i::GetStudyContext
788 //=============================================================================
790 StudyContext* SMESH_Gen_i::GetStudyContext()
792 return myStudyContext;
795 //=============================================================================
797 * SMESH_Gen_i::CreateHypothesis
799 * Create hypothesis/algorithm of given type and publish it in the study
801 //=============================================================================
803 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
804 const char* theLibName )
806 Unexpect aCatch(SALOME_SalomeException);
807 // Create hypothesis/algorithm
808 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
810 // Publish hypothesis/algorithm in the study
811 if ( CanPublishInStudy( hyp ) ) {
812 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
813 if ( !aSO->_is_nil() ) {
814 // Update Python script
815 TPythonDump(this) << aSO << " = " << this << ".CreateHypothesis('"
816 << theHypName << "', '" << theLibName << "')";
823 //================================================================================
825 * \brief Return a hypothesis initialized by given average length.
826 * \param theHypType - hypothesis type name
827 * \param theLibName - plugin library name
828 * \param theAverageLength - average length
829 * \param theQuadDominated - is quad-dominated flag
830 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
832 //================================================================================
834 SMESH::SMESH_Hypothesis_ptr
835 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
836 const char* theLibName,
837 CORBA::Double theAverageLength,
838 CORBA::Boolean theQuadDominated)
840 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
841 theAverageLength, theQuadDominated };
843 SMESH::SMESH_Hypothesis_var hyp =
844 GetHypothesisParameterValues( theHypType, theLibName,
845 SMESH::SMESH_Mesh::_nil(),
846 GEOM::GEOM_Object::_nil(),
848 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
850 TPythonDump(this) << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
851 << theHypType << "', '"
852 << theLibName << "', "
853 << theAverageLength << ", "
854 << theQuadDominated << " )";
859 //================================================================================
861 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
862 * existing on the given geometry or to size of the geometry.
863 * \param theHypType - hypothesis type name
864 * \param theLibName - plugin library name
865 * \param theMesh - The mesh of interest
866 * \param theGeom - The shape to get parameter values from
867 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
868 * in a study and used to compute the mesh, or a temporary one created just to pass
871 //================================================================================
873 SMESH::SMESH_Hypothesis_ptr
874 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
875 const char* theLibName,
876 SMESH::SMESH_Mesh_ptr theMesh,
877 GEOM::GEOM_Object_ptr theGeom,
878 const SMESH::HypInitParams& theParams)
880 Unexpect aCatch(SALOME_SalomeException);
882 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
883 if ( byMesh && CORBA::is_nil( theMesh ) )
884 return SMESH::SMESH_Hypothesis::_nil();
885 if ( byMesh && CORBA::is_nil( theGeom ) )
886 return SMESH::SMESH_Hypothesis::_nil();
888 // -----------------------------------------------
889 // find hypothesis used to mesh theGeom
890 // -----------------------------------------------
892 // get mesh and shape
893 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
894 TopoDS_Shape shape = GeomObjectToShape( theGeom );
895 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
896 return SMESH::SMESH_Hypothesis::_nil();
897 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
899 // create a temporary hypothesis to know its dimension
900 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
901 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
903 return SMESH::SMESH_Hypothesis::_nil();
904 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
907 // look for a hypothesis of theHypType used to mesh the shape
908 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
911 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
912 int nbLocalHyps = aHypList->length();
913 for ( int i = 0; i < nbLocalHyps; i++ ) {
914 CORBA::String_var hypName = aHypList[i]->GetName();
915 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
916 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
918 // check super shapes
919 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
920 while ( nbLocalHyps == 0 && itShape.More() ) {
921 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
922 if ( ! CORBA::is_nil( geomObj )) {
923 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
924 nbLocalHyps = aHypList->length();
925 for ( int i = 0; i < nbLocalHyps; i++ )
926 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
927 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
933 // let the temporary hypothesis find out somehow parameter values by mesh
934 if ( hyp->SetParametersByMesh( mesh, shape ))
935 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
939 ::SMESH_Hypothesis::TDefaults dflts;
940 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
941 dflts._nbSegments = myGen.GetDefaultNbSegments();
942 dflts._elemLength = theParams.averageLength;
943 dflts._quadDominated = theParams.quadDominated;
944 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
947 dflts._diagonal = mesh->GetShapeDiagonalSize();
949 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
950 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
951 dflts._shape = &shape;
954 // let the hypothesis initialize it's values
955 if ( hyp->SetParametersByDefaults( dflts, mesh ))
956 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
959 return SMESH::SMESH_Hypothesis::_nil();
962 //=============================================================================
964 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
965 * \param [in] theHyp - the hypothesis of interest
966 * \param [out] theMesh - the sole mesh using \a theHyp
967 * \param [out] theShape - the sole geometry \a theHyp is assigned to
968 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
970 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
971 * considered as SAME sub-mesh => result is \c true.
972 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
973 * a shape to which an hyp being edited is assigned.
975 //=============================================================================
977 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
978 SMESH::SMESH_Mesh_out theMesh,
979 GEOM::GEOM_Object_out theShape)
981 if ( CORBA::is_nil( theHyp ))
984 // get Mesh component SO
985 CORBA::String_var compDataType = ComponentDataType();
986 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
987 if ( CORBA::is_nil( comp ))
990 // look for child SO of meshes
991 SMESH::SMESH_Mesh_var foundMesh;
992 TopoDS_Shape foundShape;
994 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
995 for ( ; meshIter->More() && isSole; meshIter->Next() )
997 SALOMEDS::SObject_wrap curSO = meshIter->Value();
998 CORBA::Object_var obj = SObjectToObject( curSO );
999 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1003 // look for a sole shape where theHyp is assigned
1004 bool isHypFound = false;
1005 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1006 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1007 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1009 const THypList& hyps = s2hypsIt.Value();
1010 THypList::const_iterator h = hyps.begin();
1011 for ( ; h != hyps.end(); ++h )
1012 if ( (*h)->GetID() == theHyp->GetId() )
1014 if ( h != hyps.end()) // theHyp found
1017 if ( ! foundShape.IsNull() &&
1018 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1020 foundShape.Nullify();
1024 foundShape = s2hypsIt.Key();
1026 } // loop on assigned hyps
1028 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1030 if ( !foundMesh->_is_nil() ) // not a sole mesh
1032 if ( !foundMesh->HasShapeToMesh() ||
1033 !mesh_i ->HasShapeToMesh() )
1035 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1039 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1040 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1041 isSole = s1->IsSame( s2 );
1044 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1050 ! foundMesh->_is_nil() &&
1051 ! foundShape.IsNull() )
1053 theMesh = foundMesh._retn();
1054 theShape = ShapeToGeomObject( foundShape );
1055 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1060 //=============================================================================
1062 * Set number of segments per diagonal of boundary box of geometry by which
1063 * default segment length of appropriate 1D hypotheses is defined
1065 //=============================================================================
1067 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1069 if ( theNbSegments > 0 )
1070 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1072 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1075 //=============================================================================
1077 * \brief Set default number of segments per edge
1079 //=============================================================================
1081 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1083 if ( theNbSegments > 0 )
1084 myGen.SetDefaultNbSegments( int(theNbSegments) );
1086 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1089 //=============================================================================
1091 * Set an option value
1093 //=============================================================================
1095 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1097 if ( name && value && strlen( value ) > 0 )
1100 if ( strcmp(name, "historical_python_dump") == 0 )
1102 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1103 msgToGUI = "preferences/SMESH/historical_python_dump/";
1104 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1106 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1108 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1109 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1110 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1112 else if ( strcmp(name, "default_grp_color") == 0 )
1116 // color must be presented as a string of following form:
1117 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1118 str = str.substr(1);
1119 for ( size_t i = 0; i < str.length()/2; i++ )
1120 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1121 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1123 else if ( value ) { // rgb color ("255,170,0", for example)
1124 string tempValue( value );
1125 char* colorValue = strtok( &tempValue[0], "," );
1126 while ( colorValue != NULL ) {
1127 int c_value = atoi( colorValue );
1128 if ( c_value >= 0 && c_value <= 255 )
1129 color.push_back( c_value );
1130 colorValue = strtok( NULL, "," );
1133 if ( color.size() == 3 ) { // color must have three valid component
1134 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1135 myDefaultGroupColor = value;
1136 msgToGUI = "preferences/SMESH/default_grp_color/";
1141 // update preferences in case if SetOption() is invoked from python console
1142 if ( !msgToGUI.empty() )
1144 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1145 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1146 if ( !CORBA::is_nil( session ) )
1147 session->emitMessageOneWay(msgToGUI.c_str());
1152 //=============================================================================
1154 * Return an option value
1156 //=============================================================================
1158 char* SMESH_Gen_i::GetOption(const char* name)
1162 if ( strcmp(name, "historical_python_dump") == 0 )
1164 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1166 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1168 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1170 if ( strcmp(name, "default_grp_color") == 0 )
1172 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1175 return CORBA::string_dup( "" );
1178 //=============================================================================
1180 * SMESH_Gen_i::CreateMesh
1182 * Create empty mesh on a shape and publish it in the study
1184 //=============================================================================
1186 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1188 Unexpect aCatch(SALOME_SalomeException);
1189 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1191 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1193 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1194 ASSERT( meshServant );
1195 meshServant->SetShape( theShapeObject );
1197 // publish mesh in the study
1198 if ( CanPublishInStudy( mesh ) ) {
1199 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1200 aStudyBuilder->NewCommand(); // There is a transaction
1201 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1202 aStudyBuilder->CommitCommand();
1203 if ( !aSO->_is_nil() ) {
1204 // Update Python script
1205 TPythonDump(this) << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1209 return mesh._retn();
1212 //=============================================================================
1214 * SMESH_Gen_i::CreateEmptyMesh
1218 //=============================================================================
1220 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1222 Unexpect aCatch(SALOME_SalomeException);
1223 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1225 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1227 // publish mesh in the study
1228 if ( CanPublishInStudy( mesh ) ) {
1229 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1230 aStudyBuilder->NewCommand(); // There is a transaction
1231 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1232 aStudyBuilder->CommitCommand();
1233 if ( !aSO->_is_nil() ) {
1234 // Update Python script
1235 TPythonDump(this) << aSO << " = " << this << ".CreateEmptyMesh()";
1239 return mesh._retn();
1244 //================================================================================
1246 * \brief Throw an exception in case if the file can't be read
1248 //================================================================================
1250 void checkFileReadable( const char* theFileName )
1252 SMESH_File f ( theFileName );
1255 if ( !f.error().empty() )
1256 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1258 THROW_SALOME_CORBA_EXCEPTION
1259 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1260 SALOME::BAD_PARAM );
1265 //=============================================================================
1267 * SMESH_Gen_i::CreateMeshFromUNV
1269 * Create mesh and import data from UNV file
1271 //=============================================================================
1273 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1275 Unexpect aCatch(SALOME_SalomeException);
1277 checkFileReadable( theFileName );
1279 SMESH::SMESH_Mesh_var aMesh = createMesh();
1281 // publish mesh in the study
1282 if ( CanPublishInStudy( aMesh ) ) {
1283 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1284 aStudyBuilder->NewCommand(); // There is a transaction
1285 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1286 aStudyBuilder->CommitCommand();
1287 if ( !aSO->_is_nil() ) {
1288 // Update Python script
1289 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1293 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1295 aServant->ImportUNVFile( theFileName );
1297 // Dump creation of groups
1298 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1300 aServant->GetImpl().GetMeshDS()->Modified();
1301 return aMesh._retn();
1304 //=============================================================================
1306 * SMESH_Gen_i::CreateMeshFromMED
1308 * Create mesh and import data from MED file
1310 //=============================================================================
1312 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1313 SMESH::DriverMED_ReadStatus& theStatus,
1314 const char* theCommandNameForPython,
1315 const char* theFileNameForPython)
1318 char bname[ _MAX_FNAME ];
1319 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1320 string aFileName = bname;
1322 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1324 // Retrieve mesh names from the file
1325 DriverMED_R_SMESHDS_Mesh myReader;
1326 myReader.SetFile( theFileName );
1327 myReader.SetMeshId( -1 );
1328 Driver_Mesh::Status aStatus;
1329 list<string> aNames = myReader.GetMeshNames(aStatus);
1330 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1331 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1333 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1336 TPythonDump aPythonDump(this);
1337 aPythonDump << "([";
1339 if (theStatus == SMESH::DRS_OK) {
1340 SALOMEDS::StudyBuilder_var aStudyBuilder;
1341 aStudyBuilder = getStudyServant()->NewBuilder();
1342 aStudyBuilder->NewCommand(); // There is a transaction
1344 aResult->length( aNames.size() );
1347 // Iterate through all meshes and create mesh objects
1348 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1351 if (i > 0) aPythonDump << ", ";
1354 SMESH::SMESH_Mesh_var mesh = createMesh();
1356 // publish mesh in the study
1357 SALOMEDS::SObject_wrap aSO;
1358 if ( CanPublishInStudy( mesh ) )
1359 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1360 // - as names of meshes are stored in MED file, we use them for data publishing
1361 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1362 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1365 if ( !aSO->_is_nil() ) {
1368 aPythonDump << "mesh_" << i;
1371 // Read mesh data (groups are published automatically by ImportMEDFile())
1372 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1373 ASSERT( meshServant );
1374 SMESH::DriverMED_ReadStatus status1 =
1375 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1376 if (status1 > theStatus)
1377 theStatus = status1;
1379 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1380 meshServant->GetImpl().GetMeshDS()->Modified();
1382 if ( !aStudyBuilder->_is_nil() )
1383 aStudyBuilder->CommitCommand();
1386 // Update Python script
1387 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1389 // Dump creation of groups
1390 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1391 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1393 return aResult._retn();
1396 //================================================================================
1398 * \brief Create meshes by reading a MED file
1400 //================================================================================
1402 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1403 SMESH::DriverMED_ReadStatus& theStatus)
1405 Unexpect aCatch(SALOME_SalomeException);
1406 checkFileReadable( theFileName );
1408 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus,
1409 "CreateMeshesFromMED", theFileName);
1413 //=============================================================================
1415 * SMESH_Gen_i::CreateMeshFromSAUV
1417 * Create mesh and import data from SAUV file
1419 //=============================================================================
1421 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1422 SMESH::DriverMED_ReadStatus& theStatus)
1424 Unexpect aCatch(SALOME_SalomeException);
1425 checkFileReadable( theFileName );
1427 std::string sauvfilename(theFileName);
1428 std::string medfilename(theFileName);
1429 medfilename += ".med";
1432 cmd = "%PYTHONBIN% ";
1437 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1439 system(cmd.c_str());
1440 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(),
1442 "CreateMeshesFromSAUV",
1443 sauvfilename.c_str());
1445 cmd = "%PYTHONBIN% ";
1450 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1452 system(cmd.c_str());
1456 //=============================================================================
1458 * SMESH_Gen_i::CreateMeshFromSTL
1460 * Create mesh and import data from STL file
1462 //=============================================================================
1464 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1466 Unexpect aCatch(SALOME_SalomeException);
1467 checkFileReadable( theFileName );
1469 SMESH::SMESH_Mesh_var aMesh = createMesh();
1472 char bname[ _MAX_FNAME ];
1473 _splitpath( theFileName, NULL, NULL, bname, NULL );
1474 string aFileName = bname;
1476 string aFileName = basename( const_cast<char *>(theFileName) );
1478 // publish mesh in the study
1479 if ( CanPublishInStudy( aMesh ) ) {
1480 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1481 aStudyBuilder->NewCommand(); // There is a transaction
1482 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1483 aStudyBuilder->CommitCommand();
1484 if ( !aSO->_is_nil() ) {
1485 // Update Python script
1486 TPythonDump(this) << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1490 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1492 aServant->ImportSTLFile( theFileName );
1493 aServant->GetImpl().GetMeshDS()->Modified();
1494 return aMesh._retn();
1497 //================================================================================
1499 * \brief Create meshes and import data from the CGSN file
1501 //================================================================================
1503 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1504 SMESH::DriverMED_ReadStatus& theStatus)
1506 Unexpect aCatch(SALOME_SalomeException);
1507 checkFileReadable( theFileName );
1509 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1512 // Retrieve nb meshes from the file
1513 DriverCGNS_Read myReader;
1514 myReader.SetFile( theFileName );
1515 Driver_Mesh::Status aStatus;
1516 int nbMeshes = myReader.GetNbMeshes(aStatus);
1517 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1519 aResult->length( nbMeshes );
1521 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1524 TPythonDump aPythonDump(this);
1525 aPythonDump << "([";
1527 if (theStatus == SMESH::DRS_OK)
1529 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1530 aStudyBuilder->NewCommand(); // There is a transaction
1534 // Iterate through all meshes and create mesh objects
1535 for ( ; i < nbMeshes; ++i )
1538 if (i > 0) aPythonDump << ", ";
1541 SMESH::SMESH_Mesh_var mesh = createMesh();
1542 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1544 // Read mesh data (groups are published automatically by ImportMEDFile())
1545 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1546 ASSERT( meshServant );
1548 SMESH::DriverMED_ReadStatus status1 =
1549 meshServant->ImportCGNSFile( theFileName, i, meshName );
1550 if (status1 > theStatus)
1551 theStatus = status1;
1553 meshServant->GetImpl().GetMeshDS()->Modified();
1554 // publish mesh in the study
1555 SALOMEDS::SObject_wrap aSO;
1556 if ( CanPublishInStudy( mesh ) )
1557 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1560 if ( !aSO->_is_nil() ) {
1564 aPythonDump << "mesh_" << i;
1567 aStudyBuilder->CommitCommand();
1570 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1572 // Dump creation of groups
1573 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1574 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1576 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1579 return aResult._retn();
1582 //================================================================================
1584 * \brief Create a mesh and import data from a GMF file
1586 //================================================================================
1588 SMESH::SMESH_Mesh_ptr
1589 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1590 CORBA::Boolean theMakeRequiredGroups,
1591 SMESH::ComputeError_out theError)
1593 Unexpect aCatch(SALOME_SalomeException);
1594 checkFileReadable( theFileName );
1596 SMESH::SMESH_Mesh_var aMesh = createMesh();
1598 char bname[ _MAX_FNAME ];
1599 _splitpath( theFileName, NULL, NULL, bname, NULL );
1600 string aFileName = bname;
1602 string aFileName = basename( const_cast<char *>(theFileName) );
1604 // publish mesh in the study
1605 if ( CanPublishInStudy( aMesh ) ) {
1606 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1607 aStudyBuilder->NewCommand(); // There is a transaction
1608 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1609 aStudyBuilder->CommitCommand();
1610 if ( !aSO->_is_nil() ) {
1611 // Update Python script
1612 TPythonDump(this) << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1613 << theFileName << "', "
1614 << theMakeRequiredGroups << " )";
1617 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1619 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1620 aServant->GetImpl().GetMeshDS()->Modified();
1621 return aMesh._retn();
1625 //=============================================================================
1627 * SMESH_Gen_i::IsReadyToCompute
1629 * Return true if mesh contains enough data to be computed
1631 //=============================================================================
1633 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1634 GEOM::GEOM_Object_ptr theShapeObject )
1636 Unexpect aCatch(SALOME_SalomeException);
1637 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1639 if ( CORBA::is_nil( theShapeObject ) )
1640 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1641 SALOME::BAD_PARAM );
1642 if ( CORBA::is_nil( theMesh ) )
1643 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1644 SALOME::BAD_PARAM );
1647 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1648 ASSERT( meshServant );
1649 if ( meshServant ) {
1650 // get local TopoDS_Shape
1651 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1652 // call implementation
1653 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1654 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1657 catch ( SALOME_Exception& S_ex ) {
1658 INFOS( "catch exception "<< S_ex.what() );
1663 //================================================================================
1665 * \brief Find SObject for an algo
1667 //================================================================================
1669 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1672 SALOMEDS::Study_var aStudy = getStudyServant();
1673 if ( !aStudy->_is_nil() ) {
1674 // find algo in the study
1675 CORBA::String_var compDataType = ComponentDataType();
1676 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1677 if ( !father->_is_nil() ) {
1678 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1679 for ( ; itBig->More(); itBig->Next() ) {
1680 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1681 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1682 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1683 for ( ; algoIt->More(); algoIt->Next() ) {
1684 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1685 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1686 if ( !CORBA::is_nil( algoIOR )) {
1687 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1688 if ( impl && impl->GetImpl() == algo )
1689 return algoSO._retn();
1691 } // loop on algo SO's
1694 } // SMESH component iterator
1698 return SALOMEDS::SObject::_nil();
1701 //================================================================================
1703 * \brief Return errors of mesh computation
1705 //================================================================================
1707 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1708 GEOM::GEOM_Object_ptr theSubObject )
1710 Unexpect aCatch(SALOME_SalomeException);
1711 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1713 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1714 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1716 if ( CORBA::is_nil( theMesh ) )
1717 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1719 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1721 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1724 if(theMesh->HasShapeToMesh())
1725 shape = GeomObjectToShape( theSubObject );
1727 shape = SMESH_Mesh::PseudoShape();
1729 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1731 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1734 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1735 const bool includeSelf = true, complexShapeFirst = true;
1736 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1738 while ( smIt->more() )
1741 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1743 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1744 if ( error && !error->IsOK() )
1746 if ( !( error->myAlgo ) &&
1747 !( error->myAlgo = sm->GetAlgo() ))
1749 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1750 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1751 errStruct.comment = error->myComment.c_str();
1752 errStruct.subShapeID = sm->GetId();
1753 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1754 if ( !algoSO->_is_nil() ) {
1755 CORBA::String_var algoName = algoSO->GetName();
1756 errStruct.algoName = algoName;
1759 errStruct.algoName = error->myAlgo->GetName();
1761 errStruct.hasBadMesh = error->HasBadElems();
1764 error_array->length( nbErr );
1767 catch ( SALOME_Exception& S_ex ) {
1768 INFOS( "catch exception "<< S_ex.what() );
1771 return error_array._retn();
1774 //================================================================================
1776 * \brief Return mesh elements preventing computation of a subshape
1778 //================================================================================
1780 SMESH::MeshPreviewStruct*
1781 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1782 CORBA::Short theSubShapeID )
1784 Unexpect aCatch(SALOME_SalomeException);
1785 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1787 if ( CORBA::is_nil( theMesh ) )
1788 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1790 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1793 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1795 // mesh implementation
1796 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1797 // submesh by subshape id
1798 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1801 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1802 if ( error && error->HasBadElems() )
1804 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1805 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1807 // get nodes of elements and count elements
1808 TNode2LocalIDMap mapNode2LocalID;
1809 list< TNodeLocalID > connectivity;
1810 int i, nbElements = 0, nbConnNodes = 0;
1812 const list<const SMDS_MeshElement*>& badElems =
1813 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1814 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1815 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1816 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1818 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1819 while ( nIt->more() )
1820 connectivity.push_back
1821 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1823 // fill node coords and assign local ids to the nodes
1824 int nbNodes = mapNode2LocalID.size();
1825 result->nodesXYZ.length( nbNodes );
1826 TNodeLocalID node2ID = mapNode2LocalID.begin();
1827 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1828 node2ID->second = i;
1829 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1830 result->nodesXYZ[i].x = node->X();
1831 result->nodesXYZ[i].y = node->Y();
1832 result->nodesXYZ[i].z = node->Z();
1834 // fill connectivity
1835 result->elementConnectivities.length( nbConnNodes );
1836 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1837 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1838 result->elementConnectivities[i] = (*connIt)->second;
1840 // fill element types
1841 result->elementTypes.length( nbElements );
1842 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1844 const SMDS_MeshElement* elem = *elemIt;
1845 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1846 result->elementTypes[i].isPoly = elem->IsPoly();
1847 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1853 catch ( SALOME_Exception& S_ex ) {
1854 INFOS( "catch exception "<< S_ex.what() );
1857 return result._retn();
1860 //================================================================================
1862 * \brief Create a group of elements preventing computation of a sub-shape
1864 //================================================================================
1866 SMESH::ListOfGroups*
1867 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1868 CORBA::Short theSubShapeID,
1869 const char* theGroupName )
1871 Unexpect aCatch(SALOME_SalomeException);
1873 SMESH::ListOfGroups_var groups;
1875 if ( CORBA::is_nil( theMesh ) )
1876 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1879 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1881 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1882 TPythonDump(this) << groups << " = " << this
1883 << ".MakeGroupsOfBadInputElements( "
1884 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1887 catch ( SALOME_Exception& S_ex ) {
1888 INFOS( "catch exception "<< S_ex.what() );
1890 return groups._retn();
1893 //================================================================================
1895 * \brief Returns errors of hypotheses definition
1896 * \param theMesh - the mesh
1897 * \param theSubObject - the main or sub- shape
1898 * \retval SMESH::algo_error_array* - sequence of errors
1900 //================================================================================
1902 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1903 GEOM::GEOM_Object_ptr theSubObject )
1905 Unexpect aCatch(SALOME_SalomeException);
1906 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1908 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1909 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1911 if ( CORBA::is_nil( theMesh ) )
1912 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1914 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1916 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1917 ASSERT( meshServant );
1918 if ( meshServant ) {
1919 TopoDS_Shape myLocShape;
1920 if(theMesh->HasShapeToMesh())
1921 myLocShape = GeomObjectToShape( theSubObject );
1923 myLocShape = SMESH_Mesh::PseudoShape();
1925 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1926 list< ::SMESH_Gen::TAlgoStateError > error_list;
1927 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1928 // call ::SMESH_Gen::GetAlgoState()
1929 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1930 error_array->length( error_list.size() );
1932 for ( error = error_list.begin(); error != error_list.end(); ++error )
1934 // fill AlgoStateError structure
1935 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1936 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1937 errStruct.algoDim = error->_algoDim;
1938 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1939 errStruct.algoName = "";
1940 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1941 if ( !algoSO->_is_nil() ) {
1942 CORBA::String_var algoName = algoSO->GetName();
1943 errStruct.algoName = algoName.in();
1948 catch ( SALOME_Exception& S_ex ) {
1949 INFOS( "catch exception "<< S_ex.what() );
1951 return error_array._retn();
1954 //=============================================================================
1956 * SMESH_Gen_i::GetSubShapesId
1958 * Get sub-shapes unique ID's list
1960 //=============================================================================
1963 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1964 const SMESH::object_array& theListOfSubShapeObject )
1966 Unexpect aCatch(SALOME_SalomeException);
1967 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1969 SMESH::long_array_var shapesId = new SMESH::long_array;
1972 if ( CORBA::is_nil( theMainShapeObject ) )
1973 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1977 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1978 TopTools_IndexedMapOfShape myIndexToShape;
1979 TopExp::MapShapes(myMainShape,myIndexToShape);
1981 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1983 GEOM::GEOM_Object_var aShapeObject
1984 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1985 if ( CORBA::is_nil( aShapeObject ) )
1986 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1987 SALOME::BAD_PARAM );
1989 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1990 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1992 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1993 setId.insert(myIndexToShape.FindIndex(F));
1994 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1996 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1998 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1999 setId.insert(myIndexToShape.FindIndex(E));
2000 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
2002 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
2004 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
2005 setId.insert(myIndexToShape.FindIndex(V));
2006 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
2009 shapesId->length(setId.size());
2010 set<int>::iterator iind;
2012 for (iind = setId.begin(); iind != setId.end(); iind++)
2014 if(MYDEBUG) SCRUTE((*iind));
2015 shapesId[i] = (*iind);
2016 if(MYDEBUG) SCRUTE(shapesId[i]);
2020 catch (SALOME_Exception& S_ex)
2022 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2025 return shapesId._retn();
2028 //=============================================================================
2030 * SMESH_Gen_i::Compute
2032 * Compute mesh on a shape
2034 //=============================================================================
2036 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2037 GEOM::GEOM_Object_ptr theShapeObject )
2040 Unexpect aCatch(SALOME_SalomeException);
2041 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2043 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2044 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2045 SALOME::BAD_PARAM );
2047 if ( CORBA::is_nil( theMesh ) )
2048 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2049 SALOME::BAD_PARAM );
2051 // Update Python script
2052 TPythonDump(this) << "isDone = " << this << ".Compute( "
2053 << theMesh << ", " << theShapeObject << ")";
2057 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2058 ASSERT( meshServant );
2059 if ( meshServant ) {
2060 if ( isGeomModifIcon( theMesh ))
2061 meshServant->Clear();
2063 meshServant->Load();
2064 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2065 meshServant->CheckGeomModif();
2066 // get local TopoDS_Shape
2067 TopoDS_Shape myLocShape;
2068 if(theMesh->HasShapeToMesh())
2069 myLocShape = GeomObjectToShape( theShapeObject );
2071 myLocShape = SMESH_Mesh::PseudoShape();
2072 // call implementation compute
2073 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2074 myGen.PrepareCompute( myLocMesh, myLocShape );
2075 int how = ::SMESH_Gen::COMPACT_MESH;
2076 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2077 how |= ::SMESH_Gen::SHAPE_ONLY;
2078 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2079 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2080 myLocMesh.GetMeshDS()->Modified();
2081 UpdateIcons( theMesh );
2083 HighLightInvalid( theMesh, /*isInvalid=*/false );
2087 catch ( std::bad_alloc& ) {
2088 INFOS( "Compute(): lack of memory" );
2090 catch ( SALOME_Exception& S_ex ) {
2091 INFOS( "Compute(): catch exception "<< S_ex.what() );
2094 INFOS( "Compute(): unknown exception " );
2099 //=============================================================================
2101 * SMESH_Gen_i::CancelCompute
2103 * Cancel Compute mesh on a shape
2105 //=============================================================================
2107 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2108 GEOM::GEOM_Object_ptr theShapeObject )
2110 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2112 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2113 TopoDS_Shape myLocShape;
2114 if(theMesh->HasShapeToMesh())
2115 myLocShape = GeomObjectToShape( theShapeObject );
2117 myLocShape = SMESH_Mesh::PseudoShape();
2118 myGen.CancelCompute( myLocMesh, myLocShape);
2122 //=============================================================================
2124 * SMESH_Gen_i::Precompute
2126 * Compute mesh as preview till indicated dimension on shape
2128 //=============================================================================
2130 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2131 GEOM::GEOM_Object_ptr theShapeObject,
2132 SMESH::Dimension theDimension,
2133 SMESH::long_array& theShapesId)
2135 Unexpect aCatch(SALOME_SalomeException);
2136 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2138 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2139 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2140 SALOME::BAD_PARAM );
2142 if ( CORBA::is_nil( theMesh ) )
2143 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2144 SALOME::BAD_PARAM );
2146 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2149 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2150 meshServant->Load();
2151 ASSERT( meshServant );
2152 if ( meshServant ) {
2153 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2154 meshServant->CheckGeomModif();
2155 // get local TopoDS_Shape
2156 TopoDS_Shape myLocShape;
2157 if(theMesh->HasShapeToMesh())
2158 myLocShape = GeomObjectToShape( theShapeObject );
2160 return result._retn();
2162 // call implementation compute
2163 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2165 ::MeshDimension aDim = (MeshDimension)theDimension;
2166 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2168 int nbShapeId = shapeIds.size();
2169 theShapesId.length( nbShapeId );
2170 // iterates on shapes and collect mesh entities into mesh preview
2171 TSetOfInt::const_iterator idIt = shapeIds.begin();
2172 TSetOfInt::const_iterator idEnd = shapeIds.end();
2173 std::map< int, int > mapOfShIdNb;
2174 std::set< SMESH_TLink > setOfEdge;
2175 std::list< SMDSAbs_ElementType > listOfElemType;
2176 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2177 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2178 TNode2LocalIDMap mapNode2LocalID;
2179 list< TNodeLocalID > connectivity;
2180 int i, nbConnNodes = 0;
2181 std::set< const SMESH_subMesh* > setOfVSubMesh;
2182 // iterates on shapes
2183 for ( ; idIt != idEnd; idIt++ )
2185 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2187 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2188 if ( !sm || !sm->IsMeshComputed() )
2191 const TopoDS_Shape& aSh = sm->GetSubShape();
2192 const int shDim = myGen.GetShapeDim( aSh );
2193 if ( shDim < 1 || shDim > theDimension )
2196 mapOfShIdNb[ *idIt ] = 0;
2197 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2199 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2200 if ( !smDS ) continue;
2202 if ( theDimension == SMESH::DIM_2D )
2204 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2205 while ( faceIt->more() )
2207 const SMDS_MeshElement* face = faceIt->next();
2208 int aNbNode = face->NbNodes();
2210 aNbNode /= 2; // do not take into account additional middle nodes
2212 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2213 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2215 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2216 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2218 listOfElemType.push_back( SMDSAbs_Edge );
2219 connectivity.push_back
2220 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2221 connectivity.push_back
2222 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2228 else if ( theDimension == SMESH::DIM_1D )
2230 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2231 while ( nodeIt->more() )
2233 listOfElemType.push_back( SMDSAbs_Node );
2234 connectivity.push_back
2235 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2237 // add corner nodes by first vertex from edge
2238 SMESH_subMeshIteratorPtr edgeSmIt =
2239 sm->getDependsOnIterator(/*includeSelf*/false,
2240 /*complexShapeFirst*/false);
2241 while ( edgeSmIt->more() )
2243 SMESH_subMesh* vertexSM = edgeSmIt->next();
2244 // check that vertex is not already treated
2245 if ( !setOfVSubMesh.insert( vertexSM ).second )
2247 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2250 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2251 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2252 while ( nodeIt->more() )
2254 listOfElemType.push_back( SMDSAbs_Node );
2255 connectivity.push_back
2256 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2262 // fill node coords and assign local ids to the nodes
2263 int nbNodes = mapNode2LocalID.size();
2264 result->nodesXYZ.length( nbNodes );
2265 TNodeLocalID node2ID = mapNode2LocalID.begin();
2266 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2267 node2ID->second = i;
2268 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2269 result->nodesXYZ[i].x = node->X();
2270 result->nodesXYZ[i].y = node->Y();
2271 result->nodesXYZ[i].z = node->Z();
2273 // fill connectivity
2274 result->elementConnectivities.length( nbConnNodes );
2275 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2276 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2277 result->elementConnectivities[i] = (*connIt)->second;
2280 // fill element types
2281 result->elementTypes.length( listOfElemType.size() );
2282 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2283 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2284 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2286 SMDSAbs_ElementType elemType = *typeIt;
2287 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2288 result->elementTypes[i].isPoly = false;
2289 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2292 // correct number of shapes
2293 theShapesId.length( mapOfShIdNb.size() );
2297 catch ( std::bad_alloc& ) {
2298 INFOS( "Precompute(): lack of memory" );
2300 catch ( SALOME_Exception& S_ex ) {
2301 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2304 INFOS( "Precompute(): unknown exception " );
2306 return result._retn();
2310 //=============================================================================
2312 * SMESH_Gen_i::Evaluate
2314 * Evaluate mesh on a shape
2316 //=============================================================================
2318 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2319 GEOM::GEOM_Object_ptr theShapeObject)
2320 // SMESH::long_array& theNbElems)
2322 Unexpect aCatch(SALOME_SalomeException);
2323 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2325 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2326 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
2328 if ( CORBA::is_nil( theMesh ) )
2329 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2331 SMESH::long_array_var nbels = new SMESH::long_array;
2332 nbels->length(SMESH::Entity_Last);
2333 int i = SMESH::Entity_Node;
2334 for (; i < SMESH::Entity_Last; i++)
2337 // Update Python script
2338 TPythonDump(this) << "theNbElems = " << this << ".Evaluate( "
2339 << theMesh << ", " << theShapeObject << ")";
2343 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2344 ASSERT( meshServant );
2345 if ( meshServant ) {
2346 meshServant->Load();
2347 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2348 meshServant->CheckGeomModif();
2349 // get local TopoDS_Shape
2350 TopoDS_Shape myLocShape;
2351 if(theMesh->HasShapeToMesh())
2352 myLocShape = GeomObjectToShape( theShapeObject );
2354 myLocShape = SMESH_Mesh::PseudoShape();
2355 // call implementation compute
2356 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2357 MapShapeNbElems aResMap;
2358 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2359 MapShapeNbElemsItr anIt = aResMap.begin();
2360 for(; anIt!=aResMap.end(); anIt++) {
2361 const vector<int>& aVec = (*anIt).second;
2362 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2363 int nbElem = aVec[i];
2364 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2366 SMESH_subMesh* sm = anIt->first;
2367 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2368 const SMESH_Algo* algo = sm->GetAlgo();
2369 if ( (algo && !error.get()) || error->IsOK() )
2370 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2374 nbels[i] += aVec[i];
2378 return nbels._retn();
2381 catch ( std::bad_alloc& ) {
2382 INFOS( "Evaluate(): lack of memory" );
2384 catch ( SALOME_Exception& S_ex ) {
2385 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2388 INFOS( "Evaluate(): unknown exception " );
2391 return nbels._retn();
2394 //================================================================================
2396 * \brief Return geometrical object the given element is built on
2397 * \param theMesh - the mesh the element is in
2398 * \param theElementID - the element ID
2399 * \param theGeomName - the name of the result geom object if it is not yet published
2400 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2402 //================================================================================
2404 GEOM::GEOM_Object_ptr
2405 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2406 CORBA::Long theElementID,
2407 const char* theGeomName)
2409 Unexpect aCatch(SALOME_SalomeException);
2411 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2412 if ( !geom->_is_nil() ) {
2413 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2414 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2416 // try to find the corresponding SObject
2417 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2418 if ( SObj->_is_nil() ) // submesh can be not found even if published
2420 // try to find published submesh
2421 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2422 if ( !geom->IsMainShape() && list->length() == 1 ) {
2423 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2424 SALOMEDS::ChildIterator_wrap it;
2425 if ( !mainSO->_is_nil() ) {
2426 it = getStudyServant()->NewChildIterator( mainSO );
2428 if ( !it->_is_nil() ) {
2429 for ( it->InitEx(true); it->More(); it->Next() ) {
2430 SALOMEDS::SObject_wrap so = it->Value();
2431 CORBA::Object_var obj = SObjectToObject( so );
2432 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2433 if ( !subGeom->_is_nil() ) {
2434 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2435 if ( subList->length() == 1 && list[0] == subList[0] ) {
2445 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2446 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2448 // return only published geometry
2449 if ( !SObj->_is_nil() ) {
2450 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2451 CORBA::Object_var obj = SObjectToObject( SObj );
2452 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2456 return GEOM::GEOM_Object::_nil();
2459 //================================================================================
2461 * \brief Return geometrical object the given element is built on.
2462 * \param theMesh - the mesh the element is in
2463 * \param theElementID - the element ID
2464 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2466 //================================================================================
2468 GEOM::GEOM_Object_ptr
2469 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2470 CORBA::Long theElementID)
2472 Unexpect aCatch(SALOME_SalomeException);
2473 if ( CORBA::is_nil( theMesh ) )
2474 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2476 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2477 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2479 // get a core mesh DS
2480 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2481 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2483 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2484 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2485 // find the element in mesh
2486 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2487 // find a shape id by the element
2488 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2489 // get a geom object by the shape id
2490 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2491 if ( geom->_is_nil() ) {
2492 // try to find a published sub-shape
2493 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2494 SALOMEDS::ChildIterator_wrap it;
2495 if ( !mainSO->_is_nil() ) {
2496 it = getStudyServant()->NewChildIterator( mainSO );
2498 if ( !it->_is_nil() ) {
2499 for ( it->InitEx(true); it->More(); it->Next() ) {
2500 SALOMEDS::SObject_wrap so = it->Value();
2501 CORBA::Object_var obj = SObjectToObject( so );
2502 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2503 if ( !subGeom->_is_nil() ) {
2504 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2505 if ( subList->length() == 1 && shapeID == subList[0] ) {
2513 if ( geom->_is_nil() ) {
2515 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2516 if ( !op->_is_nil() )
2517 geom = op->GetSubShape( mainShape, shapeID );
2522 if ( !geom->_is_nil() ) {
2523 GeomObjectToShape( geom ); // let geom client remember the found shape
2524 return geom._retn();
2529 return GEOM::GEOM_Object::_nil();
2532 //================================================================================
2534 * SMESH_Gen_i::Concatenate
2536 * Concatenate the given meshes into one mesh
2538 //================================================================================
2540 SMESH::SMESH_Mesh_ptr
2541 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2542 CORBA::Boolean theUniteIdenticalGroups,
2543 CORBA::Boolean theMergeNodesAndElements,
2544 CORBA::Double theMergeTolerance,
2545 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2547 return ConcatenateCommon(theMeshesArray,
2548 theUniteIdenticalGroups,
2549 theMergeNodesAndElements,
2555 //================================================================================
2557 * SMESH_Gen_i::ConcatenateWithGroups
2559 * Concatenate the given meshes into one mesh
2560 * Create the groups of all elements from initial meshes
2562 //================================================================================
2564 SMESH::SMESH_Mesh_ptr
2565 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2566 CORBA::Boolean theUniteIdenticalGroups,
2567 CORBA::Boolean theMergeNodesAndElements,
2568 CORBA::Double theMergeTolerance,
2569 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2571 return ConcatenateCommon(theMeshesArray,
2572 theUniteIdenticalGroups,
2573 theMergeNodesAndElements,
2579 //================================================================================
2581 * SMESH_Gen_i::ConcatenateCommon
2583 * Concatenate the given meshes into one mesh
2585 //================================================================================
2587 SMESH::SMESH_Mesh_ptr
2588 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2589 CORBA::Boolean theUniteIdenticalGroups,
2590 CORBA::Boolean theMergeNodesAndElements,
2591 CORBA::Double theMergeTolerance,
2592 CORBA::Boolean theCommonGroups,
2593 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2595 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump(this) );
2596 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2598 // create mesh if theMeshToAppendTo not provided
2599 SMESH::SMESH_Mesh_var newMesh;
2600 if ( CORBA::is_nil( theMeshToAppendTo ))
2601 newMesh = CreateEmptyMesh();
2603 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2604 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2605 if ( !newImpl ) return newMesh._retn();
2608 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2609 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2611 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2612 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2613 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2614 TGroupsMap groupsMap;
2615 TListOfNewGroups listOfNewGroups;
2617 if ( !CORBA::is_nil( theMeshToAppendTo ))
2619 // fill groupsMap with existing groups
2620 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2621 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2623 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2624 if ( !group->_is_nil() )
2626 CORBA::String_var name = group->GetName();
2627 SMESH::ElementType type = group->GetType();
2628 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2633 ::SMESH_MeshEditor newEditor( &locMesh );
2634 ::SMESH_MeshEditor::ElemFeatures elemType;
2636 // loop on sub-meshes
2637 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2639 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2640 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2641 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2642 if ( !initImpl ) continue;
2643 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2647 // assure that IDs increment by one during iteration
2648 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2649 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2650 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2651 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2653 initMeshDS->Modified();
2654 initMeshDS->CompactMesh();
2657 // remember nb of elements before filling in
2658 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2662 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2663 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2664 while ( elemIt->more() )
2666 SMESH_NodeXYZ node = elemIt->next();
2667 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2672 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2673 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2675 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2676 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2677 while ( elemIt->more() )
2679 const SMDS_MeshElement* elem = elemIt->next();
2680 elemType.myNodes.resize( elem->NbNodes() );
2682 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2683 for ( int k = 0; itNodes->more(); k++)
2685 const SMDS_MeshNode* node = itNodes->next();
2686 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2689 // creates a corresponding element on existent nodes in new mesh
2690 newElems[ elem->GetID() ] =
2691 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2693 newEditor.ClearLastCreated(); // forget the history
2696 // create groups of just added elements
2697 SMESH::SMESH_Group_var newGroup;
2698 SMESH::ElementType groupType;
2699 if ( theCommonGroups )
2702 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2703 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2704 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2705 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2708 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2710 for( groupType = SMESH::NODE;
2711 groupType < SMESH::NB_ELEMENT_TYPES;
2712 groupType = (SMESH::ElementType)( groupType + 1 ))
2714 if ( curState[ groupType ] <= prevState[ groupType ])
2715 continue; // no elements of groupType added from the i-th mesh
2717 // make a group name
2718 std::string groupName = "Gr";
2719 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2721 CORBA::String_var name = meshSO->GetName();
2725 groupName += typeNames[ groupType ];
2727 // make and fill a group
2728 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2729 std::vector< const SMDS_MeshElement* > & elemVec =
2730 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2731 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2733 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2735 for ( size_t j = 0; j < elemVec.size(); ++j )
2737 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2738 grpDS->Add( elemVec[j] );
2742 listOfNewGroups.clear();
2743 listOfNewGroups.push_back( newGroup );
2744 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2749 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2753 SMESH::SMESH_GroupBase_ptr group;
2754 CORBA::String_var groupName;
2755 SMESH::long_array_var newIDs = new SMESH::long_array();
2757 // loop on groups of a source mesh
2758 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2759 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2761 group = listOfGroups[iG];
2762 groupType = group->GetType();
2763 groupName = group->GetName();
2764 std::string name = groupName.in();
2766 // convert a list of IDs
2767 newIDs->length( group->Size() );
2768 std::vector< const SMDS_MeshElement* > & elemVec =
2769 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2770 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2772 while ( itGrElems->more() )
2774 const SMDS_MeshElement* elem = itGrElems->next();
2775 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2777 newIDs[ nbElems++ ] = newElem->GetID();
2779 newIDs->length( nbElems );
2781 // check that a current group name and type don't have identical ones in final mesh
2782 listOfNewGroups.clear();
2783 TNameAndType nameAndType( name, groupType );
2784 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2785 if ( anIter == groupsMap.end() )
2787 // add a new group in the mesh
2788 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2789 newGroup->Add( newIDs );
2791 listOfNewGroups.push_back( newGroup );
2792 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2794 else if ( theUniteIdenticalGroups )
2796 // unite identical groups
2797 TListOfNewGroups& aNewGroups = anIter->second;
2798 aNewGroups.front()->Add( newIDs );
2802 // rename identical groups
2803 newGroup = newImpl->CreateGroup( groupType, groupName );
2804 newGroup->Add( newIDs );
2806 TListOfNewGroups& newGroups = anIter->second;
2807 std::string newGroupName;
2808 if ( newGroups.size() == 1 )
2810 newGroupName = name + "_1";
2811 newGroups.front()->SetName( newGroupName.c_str() );
2813 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2814 newGroup->SetName( newGroupName.c_str() );
2815 newGroups.push_back( newGroup );
2818 } // if an IDSource is a mesh
2821 if ( theMergeNodesAndElements ) // merge nodes
2823 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2824 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2825 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2826 /*SeparateCornersAndMedium=*/ false );
2827 newEditor.MergeNodes( groupsOfNodes );
2829 newEditor.MergeEqualElements();
2832 // Update Python script
2833 pythonDump << newMesh << " = " << this
2834 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2835 << theMeshesArray << ", "
2836 << theUniteIdenticalGroups << ", "
2837 << theMergeNodesAndElements << ", "
2838 << TVar( theMergeTolerance ) << ", "
2839 << theMeshToAppendTo << " )";
2841 pPythonDump.reset(); // enable python dump from GetGroups()
2843 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2844 if ( !newMesh->_is_nil() )
2846 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2849 // IPAL21468 Change icon of compound because it need not be computed.
2850 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2851 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2853 newMeshDS->Modified();
2855 return newMesh._retn();
2858 //================================================================================
2860 * \brief Create a mesh by copying a part of another mesh
2861 * \param meshPart - a part of mesh to copy
2862 * \param toCopyGroups - to create in the new mesh groups
2863 * the copied elements belongs to
2864 * \param toKeepIDs - to preserve IDs of the copied elements or not
2865 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2867 //================================================================================
2869 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2870 const char* meshName,
2871 CORBA::Boolean toCopyGroups,
2872 CORBA::Boolean toKeepIDs)
2874 Unexpect aCatch(SALOME_SalomeException);
2876 TPythonDump* pyDump = new TPythonDump(this); // prevent dump from CreateMesh()
2877 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2879 // 1. Get source mesh
2881 if ( CORBA::is_nil( meshPart ))
2882 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2884 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2885 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2887 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2889 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2891 // 2. Make a new mesh
2893 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2894 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2896 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2897 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2898 if ( !meshSO->_is_nil() )
2900 SetName( meshSO, meshName, "Mesh" );
2901 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2903 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2904 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2905 ::SMESH_MeshEditor::ElemFeatures elemType;
2907 // 3. Get elements to copy
2909 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2910 TIDSortedElemSet srcElems;
2911 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2912 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2915 srcElemIt = srcMeshDS->elementsIterator();
2916 srcNodeIt = srcMeshDS->nodesIterator();
2920 SMESH::long_array_var ids = meshPart->GetIDs();
2921 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2923 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2924 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2925 srcElems.insert( elem );
2929 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2930 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2931 srcElems.insert( elem );
2933 if ( srcElems.empty() )
2934 return newMesh._retn();
2936 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2937 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2942 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2943 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2944 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2946 const SMDS_MeshNode *nSrc, *nTgt;
2947 vector< const SMDS_MeshNode* > nodes;
2948 while ( srcElemIt->more() )
2950 const SMDS_MeshElement * elem = srcElemIt->next();
2952 nodes.resize( elem->NbNodes());
2953 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2955 for ( iN = 0; nIt->more(); ++iN )
2957 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2958 nTgt = newMeshDS->FindNode( nSrc->GetID());
2960 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2965 for ( iN = 0; nIt->more(); ++iN )
2967 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2968 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2970 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2971 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2975 if ( elem->GetType() != SMDSAbs_Node )
2977 elemType.Init( elem, /*basicOnly=*/false );
2978 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2980 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2981 if ( toCopyGroups && !toKeepIDs )
2982 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2984 } // while ( srcElemIt->more() )
2986 // 4(b). Copy free nodes
2988 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2990 while ( srcNodeIt->more() )
2992 nSrc = srcNodeIt->next();
2993 if ( nSrc->NbInverseElements() == 0 )
2996 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2998 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3005 int nbNewGroups = 0;
3008 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3009 while ( gIt->more() )
3011 SMESH_Group* group = gIt->next();
3012 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3014 // Check group type. We copy nodal groups containing nodes of copied element
3015 SMDSAbs_ElementType groupType = groupDS->GetType();
3016 if ( groupType != SMDSAbs_Node &&
3017 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3018 continue; // group type differs from types of meshPart
3020 // Find copied elements in the group
3021 vector< const SMDS_MeshElement* > groupElems;
3022 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3025 const SMDS_MeshElement* foundElem;
3026 if ( groupType == SMDSAbs_Node )
3028 while ( eIt->more() )
3029 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3030 groupElems.push_back( foundElem );
3034 while ( eIt->more() )
3035 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3036 groupElems.push_back( foundElem );
3041 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3042 if ( e2eMap.empty() ) continue;
3043 int minID = e2eMap.begin()->first->GetID();
3044 int maxID = e2eMap.rbegin()->first->GetID();
3045 TE2EMap::iterator e2e;
3046 while ( eIt->more() && groupElems.size() < e2eMap.size())
3048 const SMDS_MeshElement* e = eIt->next();
3049 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3050 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3051 groupElems.push_back( e2e->second );
3055 if ( !groupElems.empty() )
3057 SMESH::SMESH_Group_var newGroupObj =
3058 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3059 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3061 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3062 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3063 for ( unsigned i = 0; i < groupElems.size(); ++i )
3064 smdsGroup.Add( groupElems[i] );
3072 newMeshDS->Modified();
3074 *pyDump << newMesh << " = " << this
3075 << ".CopyMesh( " << meshPart << ", "
3076 << "'" << meshName << "', "
3077 << toCopyGroups << ", "
3078 << toKeepIDs << ")";
3080 pyDumpDeleter.reset(); // allow dump in GetGroups()
3082 if ( nbNewGroups > 0 ) // dump created groups
3083 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3085 return newMesh._retn();
3089 namespace // utils for CopyMeshWithGeom()
3091 typedef std::map< std::string, std::string > TStr2StrMap;
3092 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3093 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3094 typedef std::map< std::string, int > TName2IndexMap;
3096 //================================================================================
3098 * \brief Return a new sub-shape corresponding to an old one
3100 //================================================================================
3104 SMESH_Mesh_i* mySrcMesh_i;
3105 SMESH_Mesh_i* myNewMesh_i;
3106 SMESH_Gen_i* myGen_i;
3110 TStr2StrMap myOld2NewEntryMap; // map of study entries
3112 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3113 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3114 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3117 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3119 // not directly relating to shape search
3120 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3122 //================================================================================
3124 * \brief Constructor
3126 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3127 SMESH_Mesh_i* newMesh_i,
3128 SMESH_Gen_i* smeshGen_i )
3129 : mySrcMesh_i( srcMesh_i ),
3130 myNewMesh_i( newMesh_i ),
3131 myGen_i ( smeshGen_i ),
3132 myToPublish( smeshGen_i->IsEnablePublish() ),
3133 myGIPMapDone( false )
3135 // retrieve from the study shape mapping made thanks to
3136 // "Set presentation parameters and sub-shapes from arguments" option
3138 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3139 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3140 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3141 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3142 if ( newSO->_is_nil() )
3144 myToPublish = false;
3147 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3149 CORBA::String_var oldEntry = oldSO->GetID();
3150 CORBA::String_var newEntry = newSO->GetID();
3151 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3152 std::string( newEntry.in() )));
3153 std::string newMainEntry = newEntry.in();
3155 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3156 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3157 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3158 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3159 /*groupsOnly=*/false );
3160 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3162 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3163 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3164 bool refFound = false;
3165 for ( ; anIter->More(); anIter->Next() )
3167 SALOMEDS::SObject_wrap so = anIter->Value();
3168 if ( so->ReferencedObject( oldSO.inout() ))
3170 oldEntry = oldSO->GetID();
3171 newEntry = newSO->GetID();
3172 if (( refFound = ( newMainEntry != oldEntry.in() )))
3173 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3174 std::string( newEntry.in() )));
3179 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3180 if ( father->_is_equivalent( mainShapeNew ))
3182 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3183 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3184 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3185 CORBA::String_var name = newSO->GetName();
3187 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3193 //================================================================================
3195 * \brief Find a new sub-shape corresponding to an old one
3197 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3200 return GEOM::GEOM_Object::_duplicate( oldShape );
3202 GEOM::GEOM_Object_var newShape;
3204 if ( CORBA::is_nil( oldShape ))
3205 return newShape._retn();
3207 if ( !isChildOfOld( oldShape ))
3208 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3210 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3211 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3213 // try to find by entry or name
3216 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3217 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3218 if ( o2nID != myOld2NewEntryMap.end() )
3220 newShape = getShapeByEntry( o2nID->second );
3222 if ( newShape->_is_nil() )
3224 CORBA::String_var name = oldShape->GetName();
3225 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3226 if ( n2ind != myName2SubshapeIndex.end() )
3228 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3229 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3230 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3231 if ( oldIndices->length() == 0 ||
3232 newIndices->length() == 0 ||
3233 getShapeType( myNewMesh_i, newIndices[0] ) !=
3234 getShapeType( mySrcMesh_i, oldIndices[0] ))
3235 newShape = GEOM::GEOM_Object::_nil();
3240 if ( newShape->_is_nil() )
3242 // try to construct a new sub-shape using myGIPMap
3244 std::vector< int > newIndices;
3245 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3246 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3248 findNewIDs( oldIndices[i], newIndices );
3250 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3253 newShape = getInPlace( oldShape );
3255 if ( !newIndices.empty() && newShape->_is_nil() )
3257 // search for a sub-shape with same ids
3258 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3259 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3260 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3261 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3263 if ( newShape->_is_nil() )
3266 // create a new shape
3267 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3269 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3271 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3272 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3274 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3275 newIndicesList->length( newIndices.size() );
3276 for ( size_t i = 0; i < newIndices.size(); ++i )
3277 newIndicesList[ i ] = newIndices[ i ];
3278 grOp->UnionIDs( newShape, newIndicesList );
3282 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3283 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3292 if ( !newShape->_is_nil() && myToPublish )
3294 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3295 if ( !newEntry.in() || !newEntry.in()[0] )
3297 CORBA::String_var name = oldShape->GetName();
3298 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3299 newEntry = newShape->GetStudyEntry();
3300 oldEntry = oldShape->GetStudyEntry();
3301 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3302 std::string( newEntry.in() )));
3306 return newShape._retn();
3309 //================================================================================
3311 * \brief Return a study entry of a new shape by study entry of the old one
3313 std::string FindNew( const std::string & oldEntry )
3318 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3319 if ( o2nID != myOld2NewEntryMap.end() )
3320 return o2nID->second;
3322 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3323 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3326 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3327 if ( newShape->_is_nil() )
3328 return std::string();
3330 CORBA::String_var newEntry = newShape->GetStudyEntry();
3331 return newEntry.in();
3334 //================================================================================
3336 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3337 * Return zero if not found or there are more than one new ID
3339 int FindNew( int oldID )
3348 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3350 if ( myGIPMap[ oldID ].length() == 1 )
3352 newID = myGIPMap[ oldID ][ 0 ];
3354 else if ( myGIPMap[ oldID ].length() > 1 &&
3355 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3357 // select a meshed VERTEX
3358 SMESH_subMesh* newSM;
3359 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3360 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3361 ( !newSM->IsEmpty() ))
3362 newID = myGIPMap[ oldID ][ i ];
3368 //================================================================================
3370 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3371 * Return zero if the old shape is not kept as is in the new shape.
3373 int FindNewNotChanged( SMESH_subMesh* oldSM )
3376 return oldSM->GetId();
3378 int newID = FindNew( oldSM->GetId() );
3382 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3386 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3387 // one new sub-shape of the same type.
3389 if ( oldSM->DependsOn().size() !=
3390 newSM->DependsOn().size() )
3393 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3394 while ( srcSMIt->more() )
3396 oldSM = srcSMIt->next();
3397 int newSubID = FindNew( oldSM->GetId() );
3398 if ( getShapeType( myNewMesh_i, newSubID ) !=
3399 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3405 //================================================================================
3407 * \brief Return shape by study entry
3409 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3411 GEOM::GEOM_Object_var shape;
3412 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3413 if ( !so->_is_nil() )
3415 CORBA::Object_var obj = so->GetObject();
3416 shape = GEOM::GEOM_Object::_narrow( obj );
3418 return shape._retn();
3421 //================================================================================
3423 * \brief Fill myGIPMap by calling GetInPlaceMap()
3427 if ( !myGIPMapDone )
3429 myGIPMapDone = true;
3431 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3432 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3433 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3434 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3437 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3441 myGIPMap = new GEOM::ListOfListOfLong();
3446 //================================================================================
3448 * \brief Get new sub-shape by calling GetInPlace()
3450 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3452 GEOM::GEOM_Object_var newShape;
3454 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3455 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3456 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3459 newShape = op->GetInPlace( mainShapeNew, oldShape );
3464 return newShape._retn();
3467 //================================================================================
3469 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3470 * number of found IDs
3472 int findNewIDs( int oldID, std::vector< int >& newIDs )
3474 size_t prevNbIDs = newIDs.size();
3476 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3478 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3479 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3481 return newIDs.size() - prevNbIDs;
3484 //================================================================================
3486 * \brief Check if an object relates to the old shape
3488 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3490 if ( CORBA::is_nil( oldShape ))
3492 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3493 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3494 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3495 mainShapeOld1->_is_equivalent( oldShape ));
3498 //================================================================================
3500 * \brief Return shape type by shape ID
3502 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3504 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3505 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3506 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3509 //================================================================================
3511 * \brief Store a source sub-shape for which a counterpart not found and
3512 * a smesh object invalid due to that
3514 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3515 SALOMEDS::SObject_wrap smeshSO )
3517 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3518 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3520 CORBA::String_var smeshEntry = smeshSO->GetID();
3521 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3525 //================================================================================
3527 * \brief Store a source sub-shape for which a counterpart not found and
3528 * a smesh object invalid due to that
3530 void AddInvalid( std::string geomEntry,
3531 SALOMEDS::SObject_wrap smeshSO )
3533 if ( !geomEntry.empty() )
3535 CORBA::String_var smeshEntry = smeshSO->GetID();
3536 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3540 //================================================================================
3542 * \brief Store a source sub-shape for which a counterpart not found and
3543 * a smesh object invalid due to that
3545 void AddInvalid( int oldGeomID,
3546 SALOMEDS::SObject_wrap smeshSO )
3548 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3549 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3552 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3553 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3555 SMESH_Comment geomName( typeName[ shapeType ]);
3556 geomName << " #" << oldGeomID;
3558 CORBA::String_var smeshEntry = smeshSO->GetID();
3559 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3562 //================================================================================
3564 * \brief Return entries of a source sub-shape for which a counterpart not found and
3565 * of smesh objects invalid due to that
3567 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3568 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3571 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3572 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3574 nbSO += 1 + entry2entrySet->second.size();
3576 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3577 theInvalidEntries->length ( nbSO );
3578 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3580 entry2entrySet = myInvalidMap.begin();
3581 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3583 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3585 std::set< std::string > & entrySet = entry2entrySet->second;
3586 std::set< std::string >::iterator entry = entrySet.begin();
3587 for ( ; entry != entrySet.end(); ++entry )
3589 theInvalidEntries[ iEntry++ ] = entry->c_str();
3591 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3592 if ( !so->_is_nil() )
3593 theInvalidMeshSObjects[ iSO++ ] = so;
3598 }; // struct ShapeMapper
3600 //================================================================================
3602 * \brief Append an item to a CORBA sequence
3604 template < class CORBA_seq, class ITEM >
3605 void append( CORBA_seq& seq, ITEM item )
3607 if ( !CORBA::is_nil( item ))
3609 seq->length( 1 + seq->length() );
3610 seq[ seq->length() - 1 ] = item;
3613 } // namespace // utils for CopyMeshWithGeom()
3615 //================================================================================
3617 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3618 * \param [in] sourceMesh - a mesh to copy
3619 * \param [in] newGeometry - a new geometry
3620 * \param [in] toCopyGroups - to create groups in the new mesh
3621 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3622 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3623 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3624 * \param [out] newMesh - return a new mesh
3625 * \param [out] newGroups - return new groups
3626 * \param [out] newSubmeshes - return new sub-meshes
3627 * \param [out] newHypotheses - return new algorithms and hypotheses
3628 * \param [out] invalidEntries - return study entries of objects whose
3629 * counterparts are not found in the newGeometry, followed by entries
3630 * of mesh sub-objects that are invalid because they depend on a not found
3631 * preceding sub-shape
3632 * \return CORBA::Boolean - is a success
3634 //================================================================================
3636 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3637 GEOM::GEOM_Object_ptr theNewGeometry,
3638 const char* theMeshName,
3639 CORBA::Boolean theToCopyGroups,
3640 CORBA::Boolean theToReuseHypotheses,
3641 CORBA::Boolean theToCopyElements,
3642 SMESH::SMESH_Mesh_out theNewMesh,
3643 SMESH::ListOfGroups_out theNewGroups,
3644 SMESH::submesh_array_out theNewSubmeshes,
3645 SMESH::ListOfHypothesis_out theNewHypotheses,
3646 SMESH::string_array_out theInvalidEntries)
3648 if ( CORBA::is_nil( theSourceMesh ) ||
3649 CORBA::is_nil( theNewGeometry ))
3650 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3652 if ( !theSourceMesh->HasShapeToMesh() )
3653 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3658 TPythonDump pyDump(this); // prevent dump from CreateMesh()
3660 theNewMesh = CreateMesh( theNewGeometry );
3661 theNewGroups = new SMESH::ListOfGroups();
3662 theNewSubmeshes = new SMESH::submesh_array();
3663 theNewHypotheses = new SMESH::ListOfHypothesis();
3664 theInvalidEntries = new SMESH::string_array();
3666 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3668 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3669 GEOM::GEOM_Object_var geom, newGeom;
3670 SALOMEDS::SObject_wrap so;
3672 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3673 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3676 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3678 // treat hypotheses of mesh and sub-meshes
3679 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3680 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3682 bool isSubMesh = ( iSM < smList->length() );
3685 // create a new sub-mesh
3686 SMESH::SMESH_subMesh_var newSM;
3687 geom = smList[iSM]->GetSubShape();
3688 so = ObjectToSObject( smList[iSM] );
3689 CORBA::String_var name;
3690 if ( !so->_is_nil() )
3691 name = so->GetName();
3692 newGeom = shapeMapper.FindNew( geom );
3693 if ( newGeom->_is_nil() )
3695 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3696 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3701 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3703 append( theNewSubmeshes, newSM );
3705 if ( newGeom->_is_nil() )
3706 continue; // don't assign hypotheses
3710 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3712 so = ObjectToSObject( theNewMesh );
3713 SetName( so, theMeshName, "Mesh" );
3716 // assign hypotheses
3717 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3718 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3720 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3721 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3723 // get geometry hyp depends on
3724 std::vector< std::string > entryArray;
3725 std::vector< int > subIDArray;
3726 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3728 if ( !theToReuseHypotheses || dependsOnGeom )
3730 // create a new hypothesis
3731 CORBA::String_var type = hyp->GetName();
3732 CORBA::String_var lib = hyp->GetLibName();
3733 CORBA::String_var data = hyp_i->SaveTo();
3736 hyp = CreateHypothesis( type, lib );
3737 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3738 hyp_i->LoadFrom( data.in() );
3739 append( theNewHypotheses, hyp );
3743 // update geometry hyp depends on
3744 if ( dependsOnGeom )
3746 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3748 if ( !entryArray[ iGeo ].empty() )
3750 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3751 if ( newEntry.empty() )
3754 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3755 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3757 entryArray[ iGeo ] = newEntry;
3760 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3762 if ( subIDArray[ iGeo ] > 0 )
3764 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3768 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3769 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3771 subIDArray[ iGeo ] = newID;
3774 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3778 CORBA::String_var errorText;
3779 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3780 if ( errorText.in()[0] )
3783 } // loop on hypotheses
3784 } // loop on sub-meshes and mesh
3787 // copy mesh elements, keeping IDs
3788 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3789 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3791 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3792 ::SMESH_MeshEditor::ElemFeatures elemData;
3794 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3795 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3796 /*vertexLast=*/false);
3797 while ( srcSMIt->more() )
3799 SMESH_subMesh* srcSM = srcSMIt->next();
3800 if ( srcSM->IsEmpty() )
3801 continue; // not yet computed
3802 int newID = shapeMapper.FindNewNotChanged( srcSM );
3806 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3807 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3808 while ( nIt->more() )
3810 SMESH_NodeXYZ node( nIt->next() );
3811 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3813 const SMDS_PositionPtr pos = node->GetPosition();
3814 const double* uv = pos->GetParameters();
3815 switch ( pos->GetTypeOfPosition() )
3817 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3818 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3819 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3820 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3824 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3825 while( eIt->more() )
3827 const SMDS_MeshElement* e = eIt->next();
3828 elemData.Init( e, /*basicOnly=*/false );
3829 elemData.SetID( e->GetID() );
3830 elemData.myNodes.resize( e->NbNodes() );
3831 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3833 for ( iN = 0; nnIt->more(); ++iN )
3835 const SMDS_MeshNode* srcNode = nnIt->next();
3836 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3837 if ( !elemData.myNodes[ iN ])
3840 if ( iN == elemData.myNodes.size() )
3841 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3842 newMeshDS->SetMeshElementOnShape( newElem, newID );
3844 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3845 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3848 newMeshDS->Modified();
3854 TStr2StrMap old2newGroupMap;
3856 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3858 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3859 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3860 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3862 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3863 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3864 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3866 CORBA::String_var name = groups[ i ]->GetName();
3867 SMESH::ElementType elemType = groups[ i ]->GetType();
3869 SMESH::SMESH_GroupBase_var newGroup;
3871 if ( !stdlGroup->_is_nil() )
3873 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3875 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3876 const bool isElem = ( elemType != SMESH::NODE );
3877 CORBA::ULong iE = 0;
3878 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3879 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3881 if ( iE < elemIDs->length() )
3883 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3884 stdlGroup->Add( elemIDs );
3885 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3889 else if ( !geomGroup->_is_nil() )
3891 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3892 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3893 if ( newGeom->_is_nil() )
3895 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3896 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3901 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3904 else if ( !fltrGroup->_is_nil() )
3906 // replace geometry in a filter
3907 SMESH::Filter_var filter = fltrGroup->GetFilter();
3908 SMESH::Filter::Criteria_var criteria;
3909 filter->GetCriteria( criteria.out() );
3911 bool isMissingGroup = false;
3912 std::vector< std::string > badEntries;
3914 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3916 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3917 switch ( criteria[ iCr ].Type )
3919 case SMESH::FT_BelongToMeshGroup:
3921 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3922 btgg->SetGroupID( thresholdID );
3923 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3924 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3925 if ( refGroupSO->_is_nil() )
3927 CORBA::String_var refID = refGroupSO->GetID();
3928 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3929 if ( o2nID == old2newGroupMap.end() )
3931 isMissingGroup = true; // corresponding new group not yet created
3934 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3936 if ( o2nID->second.empty() ) // new referred group is invalid
3937 badEntries.push_back( refID.in() );
3940 case SMESH::FT_BelongToGeom:
3941 case SMESH::FT_BelongToPlane:
3942 case SMESH::FT_BelongToCylinder:
3943 case SMESH::FT_BelongToGenSurface:
3944 case SMESH::FT_LyingOnGeom:
3946 std::string newID = shapeMapper.FindNew( thresholdID );
3947 criteria[ iCr ].ThresholdID = newID.c_str();
3948 if ( newID.empty() )
3949 badEntries.push_back( thresholdID );
3952 case SMESH::FT_ConnectedElements:
3954 if ( thresholdID && thresholdID[0] )
3956 std::string newID = shapeMapper.FindNew( thresholdID );
3957 criteria[ iCr ].ThresholdID = newID.c_str();
3958 if ( newID.empty() )
3959 badEntries.push_back( thresholdID );
3965 } // loop on criteria
3967 if ( isMissingGroup && i < nbGroups )
3969 // to treat the group again
3970 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3974 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3975 newFilter->SetCriteria( criteria );
3977 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3978 newFilter->UnRegister();
3980 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3981 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3982 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3984 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3986 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3989 if ( !badEntries.empty() )
3992 } // treat a group on filter
3994 append( theNewGroups, newGroup );
3996 // fill old2newGroupMap
3997 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3998 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3999 if ( !srcSO->_is_nil() )
4001 CORBA::String_var srcID, newID("");
4002 srcID = srcSO->GetID();
4003 if ( !newSO->_is_nil() )
4004 newID = newSO->GetID();
4005 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4006 std::string( newID.in() )));
4009 if ( newGroup->_is_nil() )
4014 newMeshDS->CompactMesh();
4017 if ( !theMeshName || !theMeshName[0] )
4019 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4020 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4021 CORBA::String_var oldName = soOld->GetName();
4022 SetName( soNew, oldName.in(), "Mesh" );
4024 // mark invalid objects
4025 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4027 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4028 highLightInvalid( invalidSObjects[i].in(), true );
4031 << theNewMesh << ", "
4032 << theNewGroups << ", "
4033 << *theNewSubmeshes.ptr() << ", "
4034 << *theNewHypotheses.ptr() << ", "
4035 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4036 << theSourceMesh << ", "
4037 << theNewGeometry << ", "
4038 << "'" << theMeshName << "', "
4039 << theToCopyGroups << ", "
4040 << theToReuseHypotheses << ", "
4041 << theToCopyElements << " )";
4043 SMESH_CATCH( SMESH::throwCorbaException );
4048 //================================================================================
4050 * \brief Get version of MED format being used.
4052 //================================================================================
4054 char* SMESH_Gen_i::GetMEDFileVersion()
4056 MED::TInt majeur, mineur, release;
4057 majeur = mineur = release = 0;
4058 MED::GetVersionRelease(majeur, mineur, release);
4059 std::ostringstream version;
4060 version << majeur << "." << mineur << "." << release;
4061 return CORBA::string_dup( version.str().c_str() );
4064 //================================================================================
4066 * SMESH_Gen_i::GetMEDVersion
4068 * Get MED version of the file by its name
4070 //================================================================================
4072 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4074 std::string version = MED::GetMEDVersion( theFileName );
4075 return CORBA::string_dup( version.c_str() );
4078 //================================================================================
4080 * SMESH_Gen_i::CheckCompatibility
4082 * Check compatibility of file with MED format being used, read only.
4084 //================================================================================
4086 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4088 return MED::CheckCompatibility( theFileName );
4091 //================================================================================
4093 * SMESH_Gen_i::CheckWriteCompatibility
4095 * Check compatibility of file with MED format being used, for append on write.
4097 //================================================================================
4099 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4101 return MED::CheckCompatibility( theFileName, true );
4104 //================================================================================
4106 * SMESH_Gen_i::GetMeshNames
4108 * Get names of meshes defined in file with the specified name
4110 //================================================================================
4111 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4114 SMESH::string_array_var aResult = new SMESH::string_array();
4115 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4117 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4119 aResult->length( aNbMeshes );
4120 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4121 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4122 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4125 return aResult._retn();
4128 //=============================================================================
4132 * Save SMESH module's data
4134 //=============================================================================
4136 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4141 Kernel_Utils::Localizer loc;
4143 if (!myStudyContext)
4146 // Store study contents as a set of python commands
4149 SALOMEDS::Study_var aStudy = getStudyServant();
4151 // Declare a byte stream
4152 SALOMEDS::TMPFile_var aStreamFile;
4154 // Obtain a temporary dir
4155 TCollection_AsciiString tmpDir =
4156 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4158 // Create a sequence of files processed
4159 SALOMEDS_Tool::ListOfFiles aFileSeq;
4160 aFileSeq.reserve( NUM_TMP_FILES );
4162 TCollection_AsciiString aStudyName( "" );
4164 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4166 // Set names of temporary files
4167 TCollection_AsciiString filename =
4168 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4169 TCollection_AsciiString meshfile =
4170 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4171 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4172 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4173 filename = tmpDir + filename;
4174 meshfile = tmpDir + meshfile;
4177 HDFdataset* aDataset;
4178 HDFgroup* aTopGroup;
4180 HDFgroup* aSubGroup;
4181 HDFgroup* aSubSubGroup;
4182 hdf_size aSize[ 1 ];
4185 //Remove the files if they exist: BugID: 11225
4186 #ifndef WIN32 /* unix functionality */
4187 TCollection_AsciiString cmd("rm -f \"");
4189 TCollection_AsciiString cmd("del /F \"");
4199 system(cmd.ToCString());
4201 // MED writer to be used by storage process
4202 DriverMED_W_SMESHDS_Mesh myWriter;
4203 myWriter.SetFile( meshfile.ToCString() );
4206 // SetStoreName() to groups before storing hypotheses to let them refer to
4207 // groups using "store name", which is "Group <group_persistent_id>"
4209 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4210 for ( ; itBig->More(); itBig->Next() ) {
4211 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4212 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4213 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4214 if ( !CORBA::is_nil( anObject ) ) {
4215 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4216 if ( !myMesh->_is_nil() ) {
4217 myMesh->Load(); // load from study file if not yet done
4218 TPythonDump pd(this); // not to dump GetGroups()
4219 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4220 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4222 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4225 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4226 int anId = myStudyContext->findId( string( objStr.in() ) );
4228 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4229 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4230 aGrpBaseDS->SetStoreName( grpName );
4240 // ---> create HDF file
4241 aFile = new HDFfile( (char*) filename.ToCString() );
4242 aFile->CreateOnDisk();
4244 // --> iterator for top-level objects
4245 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4246 for ( ; itBig->More(); itBig->Next() ) {
4247 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4249 // --> hypotheses root branch (only one for the study)
4250 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4251 // create hypotheses root HDF group
4252 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4253 aTopGroup->CreateOnDisk();
4255 // iterator for all hypotheses
4256 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4257 for ( ; it->More(); it->Next() ) {
4258 SALOMEDS::SObject_wrap mySObject = it->Value();
4259 CORBA::Object_var anObject = SObjectToObject( mySObject );
4260 if ( !CORBA::is_nil( anObject ) ) {
4261 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4262 if ( !myHyp->_is_nil() ) {
4263 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4265 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4266 std::string hypname = hn.in();
4267 std::string libname = ln.in();
4269 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4270 // WIN32 and ".so" for X-system) must be deleted
4271 int libname_len = libname.length();
4273 if( libname_len > 4 )
4274 libname.resize( libname_len - 4 );
4276 // PAL17753 (Regression: missing hypothesis in restored study)
4277 // "lib" also should be removed from the beginning
4278 if( libname_len > 6 )
4279 libname = libname.substr( 3, libname_len - 3 - 3 );
4281 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4282 CORBA::String_var hypdata = myImpl->SaveTo();
4283 int id = myStudyContext->findId( string( objStr.in() ));
4285 // for each hypothesis create HDF group basing on its id
4286 char hypGrpName[30];
4287 sprintf( hypGrpName, "Hypothesis %d", id );
4288 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4289 aGroup->CreateOnDisk();
4290 // --> type name of hypothesis
4291 aSize[ 0 ] = hypname.length() + 1;
4292 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4293 aDataset->CreateOnDisk();
4294 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4295 aDataset->CloseOnDisk();
4296 // --> server plugin library name of hypothesis
4297 aSize[ 0 ] = libname.length() + 1;
4298 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4299 aDataset->CreateOnDisk();
4300 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4301 aDataset->CloseOnDisk();
4302 // --> persistent data of hypothesis
4303 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4304 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4305 aDataset->CreateOnDisk();
4306 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4307 aDataset->CloseOnDisk();
4308 // close hypothesis HDF group
4309 aGroup->CloseOnDisk();
4314 // close hypotheses root HDF group
4315 aTopGroup->CloseOnDisk();
4317 // --> algorithms root branch (only one for the study)
4318 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4319 // create algorithms root HDF group
4320 aTopGroup = new HDFgroup( "Algorithms", aFile );
4321 aTopGroup->CreateOnDisk();
4323 // iterator for all algorithms
4324 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4325 for ( ; it->More(); it->Next() ) {
4326 SALOMEDS::SObject_wrap mySObject = it->Value();
4327 CORBA::Object_var anObject = SObjectToObject( mySObject );
4328 if ( !CORBA::is_nil( anObject ) ) {
4329 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4330 if ( !myHyp->_is_nil() ) {
4331 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4333 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4334 std::string hypname = hn.in();
4335 std::string libname = ln.in();
4337 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4338 // WIN32 and ".so" for X-system) must be deleted
4339 int libname_len = libname.length();
4341 if( libname_len > 4 )
4342 libname.resize( libname_len - 4 );
4344 // PAL17753 (Regression: missing hypothesis in restored study)
4345 // "lib" also should be removed from the beginning
4346 if( libname_len > 6 )
4347 libname = libname.substr( 3, libname_len - 3 - 3 );
4349 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4350 CORBA::String_var hypdata = myImpl->SaveTo();
4351 int id = myStudyContext->findId( string( objStr.in() ) );
4353 // for each algorithm create HDF group basing on its id
4354 char hypGrpName[30];
4355 sprintf( hypGrpName, "Algorithm %d", id );
4356 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4357 aGroup->CreateOnDisk();
4358 // --> type name of algorithm
4359 aSize[0] = hypname.length() + 1;
4360 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4361 aDataset->CreateOnDisk();
4362 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4363 aDataset->CloseOnDisk();
4364 // --> server plugin library name of hypothesis
4365 aSize[0] = libname.length() + 1;
4366 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4367 aDataset->CreateOnDisk();
4368 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4369 aDataset->CloseOnDisk();
4370 // --> persistent data of algorithm
4371 aSize[0] = strlen( hypdata.in() ) + 1;
4372 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4373 aDataset->CreateOnDisk();
4374 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4375 aDataset->CloseOnDisk();
4376 // close algorithm HDF group
4377 aGroup->CloseOnDisk();
4382 // close algorithms root HDF group
4383 aTopGroup->CloseOnDisk();
4385 // --> mesh objects roots branches
4386 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4387 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4388 if ( !CORBA::is_nil( anObject ) ) {
4389 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4390 if ( !myMesh->_is_nil() ) {
4391 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4393 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4394 int id = myStudyContext->findId( string( objStr.in() ) );
4395 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4396 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4397 bool hasShape = myLocMesh.HasShapeToMesh();
4399 // for each mesh open the HDF group basing on its id
4400 char meshGrpName[ 30 ];
4401 sprintf( meshGrpName, "Mesh %d", id );
4402 aTopGroup = new HDFgroup( meshGrpName, aFile );
4403 aTopGroup->CreateOnDisk();
4405 // --> put dataset to hdf file which is a flag that mesh has data
4406 string strHasData = "0";
4407 // check if the mesh is not empty
4408 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4409 // write mesh data to med file
4410 myWriter.SetMesh( mySMESHDSMesh );
4411 myWriter.SetMeshId( id );
4414 aSize[ 0 ] = strHasData.length() + 1;
4415 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4416 aDataset->CreateOnDisk();
4417 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4418 aDataset->CloseOnDisk();
4421 // for each mesh open the HDF group basing on its auto color parameter
4422 char meshAutoColorName[ 30 ];
4423 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4425 anAutoColor[0] = myImpl->GetAutoColor();
4427 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4428 aDataset->CreateOnDisk();
4429 aDataset->WriteOnDisk( anAutoColor );
4430 aDataset->CloseOnDisk();
4432 // issue 0020693. Store _isModified flag
4433 int isModified = myLocMesh.GetIsModified();
4435 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4436 aDataset->CreateOnDisk();
4437 aDataset->WriteOnDisk( &isModified );
4438 aDataset->CloseOnDisk();
4440 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4441 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4443 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4444 aDataset->CreateOnDisk();
4445 aDataset->WriteOnDisk( &meshPersistentId );
4446 aDataset->CloseOnDisk();
4448 // Store SMESH_Mesh_i::_mainShapeTick
4449 int shapeTick = myImpl->MainShapeTick();
4451 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4452 aDataset->CreateOnDisk();
4453 aDataset->WriteOnDisk( &shapeTick );
4454 aDataset->CloseOnDisk();
4456 // write reference on a shape if exists
4457 SALOMEDS::SObject_wrap myRef;
4458 bool shapeRefFound = false;
4459 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4461 SALOMEDS::SObject_wrap myShape;
4462 bool ok = myRef->ReferencedObject( myShape.inout() );
4464 CORBA::Object_var shapeObj = myShape->GetObject();
4465 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4466 CORBA::String_var myRefOnObject = myShape->GetID();
4467 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4468 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4469 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4470 aDataset->CreateOnDisk();
4471 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4472 aDataset->CloseOnDisk();
4478 std::string info = myImpl->FileInfoToString();
4479 if ( !info.empty() )
4481 aSize[ 0 ] = info.size();
4482 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4483 aDataset->CreateOnDisk();
4484 aDataset->WriteOnDisk( (char*) info.data() );
4485 aDataset->CloseOnDisk();
4488 // write applied hypotheses if exist
4489 SALOMEDS::SObject_wrap myHypBranch;
4490 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4491 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4492 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4494 if ( found && (shapeRefFound || !hasShape) ) {
4495 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4496 aGroup->CreateOnDisk();
4498 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4500 for ( ; it->More(); it->Next() ) {
4501 SALOMEDS::SObject_wrap mySObject = it->Value();
4502 SALOMEDS::SObject_wrap myRefOnHyp;
4503 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4505 // san - it is impossible to recover applied hypotheses
4506 // using their entries within Load() method,
4507 // for there are no AttributeIORs in the study when Load() is working.
4508 // Hence, it is better to store persistent IDs of hypotheses as references to them
4510 //string myRefOnObject = myRefOnHyp->GetID();
4511 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4512 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4513 int id = myStudyContext->findId( string( objStr.in() ) );
4514 //if ( myRefOnObject.length() > 0 ) {
4515 //aSize[ 0 ] = myRefOnObject.length() + 1;
4516 char hypName[ 30 ], hypId[ 30 ];
4517 sprintf( hypName, "Hyp %d", ++hypNb );
4518 sprintf( hypId, "%d", id );
4519 aSize[ 0 ] = strlen( hypId ) + 1;
4520 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4521 aDataset->CreateOnDisk();
4522 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4523 aDataset->WriteOnDisk( hypId );
4524 aDataset->CloseOnDisk();
4528 aGroup->CloseOnDisk();
4531 // write applied algorithms if exist
4532 SALOMEDS::SObject_wrap myAlgoBranch;
4533 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4534 myAlgoBranch.inout() );
4535 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4536 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4538 if ( found && (shapeRefFound || !hasShape)) {
4539 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4540 aGroup->CreateOnDisk();
4542 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4544 for ( ; it->More(); it->Next() ) {
4545 SALOMEDS::SObject_wrap mySObject = it->Value();
4546 SALOMEDS::SObject_wrap myRefOnAlgo;
4547 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4549 // san - it is impossible to recover applied algorithms
4550 // using their entries within Load() method,
4551 // for there are no AttributeIORs in the study when Load() is working.
4552 // Hence, it is better to store persistent IDs of algorithms as references to them
4554 //string myRefOnObject = myRefOnAlgo->GetID();
4555 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4556 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4557 int id = myStudyContext->findId( string( objStr.in() ) );
4558 //if ( myRefOnObject.length() > 0 ) {
4559 //aSize[ 0 ] = myRefOnObject.length() + 1;
4560 char algoName[ 30 ], algoId[ 30 ];
4561 sprintf( algoName, "Algo %d", ++algoNb );
4562 sprintf( algoId, "%d", id );
4563 aSize[ 0 ] = strlen( algoId ) + 1;
4564 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4565 aDataset->CreateOnDisk();
4566 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4567 aDataset->WriteOnDisk( algoId );
4568 aDataset->CloseOnDisk();
4572 aGroup->CloseOnDisk();
4575 // --> submesh objects sub-branches
4577 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4578 SALOMEDS::SObject_wrap mySubmeshBranch;
4579 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4581 if ( found ) // check if there is shape reference in submeshes
4583 bool hasShapeRef = false;
4584 SALOMEDS::ChildIterator_wrap itSM =
4585 aStudy->NewChildIterator( mySubmeshBranch );
4586 for ( ; itSM->More(); itSM->Next() ) {
4587 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4588 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4589 mySubRef->ReferencedObject( myShape.inout() );
4590 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4593 { // remove one submesh
4594 if ( shapeRefFound )
4595 { // unassign hypothesis
4596 SMESH::SMESH_subMesh_var mySubMesh =
4597 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4598 if ( !mySubMesh->_is_nil() ) {
4599 int shapeID = mySubMesh->GetId();
4600 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4601 const list<const SMESHDS_Hypothesis*>& hypList =
4602 mySMESHDSMesh->GetHypothesis( S );
4603 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4604 while ( hyp != hypList.end() ) {
4605 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4606 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4610 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4612 } // loop on submeshes of a type
4613 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4614 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4617 } // end check if there is shape reference in submeshes
4619 char name_meshgroup[ 30 ];
4620 if ( i == GetSubMeshOnVertexTag() )
4621 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4622 else if ( i == GetSubMeshOnEdgeTag() )
4623 strcpy( name_meshgroup, "SubMeshes On Edge" );
4624 else if ( i == GetSubMeshOnWireTag() )
4625 strcpy( name_meshgroup, "SubMeshes On Wire" );
4626 else if ( i == GetSubMeshOnFaceTag() )
4627 strcpy( name_meshgroup, "SubMeshes On Face" );
4628 else if ( i == GetSubMeshOnShellTag() )
4629 strcpy( name_meshgroup, "SubMeshes On Shell" );
4630 else if ( i == GetSubMeshOnSolidTag() )
4631 strcpy( name_meshgroup, "SubMeshes On Solid" );
4632 else if ( i == GetSubMeshOnCompoundTag() )
4633 strcpy( name_meshgroup, "SubMeshes On Compound" );
4635 // for each type of submeshes create container HDF group
4636 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4637 aGroup->CreateOnDisk();
4639 // iterator for all submeshes of given type
4640 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4641 for ( ; itSM->More(); itSM->Next() ) {
4642 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4643 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4644 if ( !CORBA::is_nil( anSubObject ))
4646 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4647 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4648 int subid = myStudyContext->findId( string( objStr.in() ) );
4650 // for each mesh open the HDF group basing on its id
4651 char submeshGrpName[ 30 ];
4652 sprintf( submeshGrpName, "SubMesh %d", subid );
4653 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4654 aSubGroup->CreateOnDisk();
4656 // write reference on a shape, already checked if it exists
4657 SALOMEDS::SObject_wrap mySubRef, myShape;
4658 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4659 mySubRef->ReferencedObject( myShape.inout() );
4660 string myRefOnObject = myShape->GetID();
4661 if ( myRefOnObject.length() > 0 ) {
4662 aSize[ 0 ] = myRefOnObject.length() + 1;
4663 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4664 aDataset->CreateOnDisk();
4665 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4666 aDataset->CloseOnDisk();
4669 // write applied hypotheses if exist
4670 SALOMEDS::SObject_wrap mySubHypBranch;
4671 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4672 mySubHypBranch.inout() );
4674 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4675 aSubSubGroup->CreateOnDisk();
4677 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4679 for ( ; it->More(); it->Next() ) {
4680 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4681 SALOMEDS::SObject_wrap myRefOnHyp;
4682 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4684 //string myRefOnObject = myRefOnHyp->GetID();
4685 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4686 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4687 int id = myStudyContext->findId( string( objStr.in() ) );
4688 //if ( myRefOnObject.length() > 0 ) {
4689 //aSize[ 0 ] = myRefOnObject.length() + 1;
4690 char hypName[ 30 ], hypId[ 30 ];
4691 sprintf( hypName, "Hyp %d", ++hypNb );
4692 sprintf( hypId, "%d", id );
4693 aSize[ 0 ] = strlen( hypId ) + 1;
4694 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4695 aDataset->CreateOnDisk();
4696 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4697 aDataset->WriteOnDisk( hypId );
4698 aDataset->CloseOnDisk();
4702 aSubSubGroup->CloseOnDisk();
4705 // write applied algorithms if exist
4706 SALOMEDS::SObject_wrap mySubAlgoBranch;
4707 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4708 mySubAlgoBranch.inout() );
4710 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4711 aSubSubGroup->CreateOnDisk();
4713 SALOMEDS::ChildIterator_wrap it =
4714 aStudy->NewChildIterator( mySubAlgoBranch );
4716 for ( ; it->More(); it->Next() ) {
4717 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4718 SALOMEDS::SObject_wrap myRefOnAlgo;
4719 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4721 //string myRefOnObject = myRefOnAlgo->GetID();
4722 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4723 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4724 int id = myStudyContext->findId( string( objStr.in() ) );
4725 //if ( myRefOnObject.length() > 0 ) {
4726 //aSize[ 0 ] = myRefOnObject.length() + 1;
4727 char algoName[ 30 ], algoId[ 30 ];
4728 sprintf( algoName, "Algo %d", ++algoNb );
4729 sprintf( algoId, "%d", id );
4730 aSize[ 0 ] = strlen( algoId ) + 1;
4731 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4732 aDataset->CreateOnDisk();
4733 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4734 aDataset->WriteOnDisk( algoId );
4735 aDataset->CloseOnDisk();
4739 aSubSubGroup->CloseOnDisk();
4741 // close submesh HDF group
4742 aSubGroup->CloseOnDisk();
4745 // close container of submeshes by type HDF group
4746 aGroup->CloseOnDisk();
4750 // store submesh order if any
4751 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4752 const bool isNewOrederVersion = true; // old version saves ids, new one, entries
4753 if ( !theOrderIds.empty() && !isNewOrederVersion ) { // keep old version for reference
4754 char order_list[ 30 ];
4755 strcpy( order_list, "Mesh Order" );
4756 // count number of submesh ids
4758 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4759 for ( ; idIt != theOrderIds.end(); idIt++ )
4760 nbIDs += (*idIt).size();
4761 // number of values = number of IDs +
4762 // number of lists (for separators) - 1
4763 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4764 idIt = theOrderIds.begin();
4765 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4766 const TListOfInt& idList = *idIt;
4767 if (idIt != theOrderIds.begin()) // not first list
4768 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4769 // dump submesh ids from current list
4770 TListOfInt::const_iterator id_smId = idList.begin();
4771 for( ; id_smId != idList.end(); id_smId++ )
4772 smIDs[ i++ ] = *id_smId;
4775 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4777 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4778 aDataset->CreateOnDisk();
4779 aDataset->WriteOnDisk( smIDs );
4780 aDataset->CloseOnDisk();
4784 if ( !theOrderIds.empty() && isNewOrederVersion )
4786 // convert ids to entries
4787 std::list< std::list< std::string > > orderEntryLists;
4788 for ( const TListOfInt& idList : theOrderIds )
4790 orderEntryLists.emplace_back();
4791 std::list< std::string > & entryList = orderEntryLists.back();
4792 for ( const int& id : idList )
4794 const TopoDS_Shape& shape = mySMESHDSMesh->IndexToShape( id );
4795 GEOM::GEOM_Object_var go = ShapeToGeomObject( shape );
4796 SALOMEDS::SObject_var so = ObjectToSObject( go );
4797 if ( !so->_is_nil() )
4799 CORBA::String_var entry = so->GetID();
4800 entryList.emplace_back( entry.in() );
4804 // convert orderEntryLists to string
4805 std::ostringstream ostream;
4806 boost::archive::text_oarchive( ostream ) << orderEntryLists;
4807 std::string orderEntryString = ostream.str();
4810 aSize[ 0 ] = orderEntryString.size() + 1;
4811 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup, HDF_STRING, aSize, 1 );
4812 aDataset->CreateOnDisk();
4813 aDataset->WriteOnDisk((char*) orderEntryString.data() );
4814 aDataset->CloseOnDisk();
4817 // groups root sub-branch
4818 SALOMEDS::SObject_wrap myGroupsBranch;
4819 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4820 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4822 char name_group[ 30 ];
4823 if ( i == GetNodeGroupsTag() )
4824 strcpy( name_group, "Groups of Nodes" );
4825 else if ( i == GetEdgeGroupsTag() )
4826 strcpy( name_group, "Groups of Edges" );
4827 else if ( i == GetFaceGroupsTag() )
4828 strcpy( name_group, "Groups of Faces" );
4829 else if ( i == GetVolumeGroupsTag() )
4830 strcpy( name_group, "Groups of Volumes" );
4831 else if ( i == Get0DElementsGroupsTag() )
4832 strcpy( name_group, "Groups of 0D Elements" );
4833 else if ( i == GetBallElementsGroupsTag() )
4834 strcpy( name_group, "Groups of Balls" );
4836 aGroup = new HDFgroup( name_group, aTopGroup );
4837 aGroup->CreateOnDisk();
4839 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4840 for ( ; it->More(); it->Next() ) {
4841 SALOMEDS::SObject_wrap mySObject = it->Value();
4842 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4843 if ( !CORBA::is_nil( aSubObject ) ) {
4844 SMESH_GroupBase_i* myGroupImpl =
4845 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4848 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4852 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4853 int anId = myStudyContext->findId( string( objStr.in() ) );
4855 // For each group, create a dataset named "Group <group_persistent_id>"
4856 // and store the group's user name into it
4857 const char* grpName = aGrpBaseDS->GetStoreName();
4858 CORBA::String_var aUserName = myGroupImpl->GetName();
4859 aSize[ 0 ] = strlen( aUserName ) + 1;
4861 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4862 aDataset->CreateOnDisk();
4863 aDataset->WriteOnDisk( aUserName );
4864 aDataset->CloseOnDisk();
4867 // For each group, create a dataset named "Group <group_persistent_id> Color"
4868 // and store the group's color into it
4869 char grpColorName[ 30 ];
4870 sprintf( grpColorName, "ColorGroup %d", anId );
4871 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4873 anRGB[ 0 ] = aColor.R;
4874 anRGB[ 1 ] = aColor.G;
4875 anRGB[ 2 ] = aColor.B;
4877 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4878 aDataset->CreateOnDisk();
4879 aDataset->WriteOnDisk( anRGB );
4880 aDataset->CloseOnDisk();
4882 // Pass SMESHDS_Group to MED writer
4883 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4885 myWriter.AddGroup( aGrpDS );
4887 // write reference on a shape if exists
4888 SMESHDS_GroupOnGeom* aGeomGrp =
4889 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4891 SALOMEDS::SObject_wrap mySubRef, myShape;
4892 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4893 mySubRef->ReferencedObject( myShape.inout() ) &&
4894 !CORBA::is_nil( myShape->GetObject() ))
4896 CORBA::String_var myRefOnObject = myShape->GetID();
4897 if ( myRefOnObject.in()[0] ) {
4898 char aRefName[ 30 ];
4899 sprintf( aRefName, "Ref on shape %d", anId);
4900 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4901 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4902 aDataset->CreateOnDisk();
4903 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4904 aDataset->CloseOnDisk();
4907 else // shape ref is invalid:
4909 // save a group on geometry as ordinary group
4910 myWriter.AddGroup( aGeomGrp );
4913 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4914 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4916 std::string str = aFilterGrp_i->FilterToString();
4917 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4918 aSize[ 0 ] = str.length() + 1;
4919 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4920 aDataset->CreateOnDisk();
4921 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4922 aDataset->CloseOnDisk();
4926 aGroup->CloseOnDisk();
4930 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4932 // Flush current mesh information into MED file
4935 // save info on nb of elements
4936 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4938 // maybe a shape was deleted in the study
4939 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4940 TopoDS_Shape nullShape;
4941 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4944 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4949 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4950 aGroup->CreateOnDisk();
4952 // each element belongs to one or none submesh,
4953 // so for each node/element, we store a submesh ID
4955 // Store submesh IDs
4956 for ( int isNode = 0; isNode < 2; ++isNode )
4958 SMDS_ElemIteratorPtr eIt =
4959 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4960 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4963 std::vector<int> smIDs; smIDs.reserve( nbElems );
4964 while ( eIt->more() )
4965 if ( const SMDS_MeshElement* e = eIt->next())
4966 smIDs.push_back( e->getshapeId() );
4968 aSize[ 0 ] = nbElems;
4969 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4970 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4971 aDataset->CreateOnDisk();
4972 aDataset->WriteOnDisk( & smIDs[0] );
4973 aDataset->CloseOnDisk();
4976 aGroup->CloseOnDisk();
4978 // Store node positions on sub-shapes (SMDS_Position):
4979 // ----------------------------------------------------
4981 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4982 aGroup->CreateOnDisk();
4984 // in aGroup, create 5 datasets to contain:
4985 // "Nodes on Edges" - ID of node on edge
4986 // "Edge positions" - U parameter on node on edge
4987 // "Nodes on Faces" - ID of node on face
4988 // "Face U positions" - U parameter of node on face
4989 // "Face V positions" - V parameter of node on face
4991 // Find out nb of nodes on edges and faces
4992 // Collect corresponding sub-meshes
4993 int nbEdgeNodes = 0, nbFaceNodes = 0;
4994 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4995 // loop on SMESHDS_SubMesh'es
4996 while ( smIt->more() )
4998 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4999 if ( aSubMesh->IsComplexSubmesh() )
5000 continue; // submesh containing other submeshs
5001 int nbNodes = aSubMesh->NbNodes();
5002 if ( nbNodes == 0 ) continue;
5004 int aShapeID = aSubMesh->GetID();
5005 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5007 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5008 // write only SMDS_FacePosition and SMDS_EdgePosition
5009 switch ( aShapeType ) {
5011 nbFaceNodes += nbNodes;
5012 aFaceSM.push_back( aSubMesh );
5015 nbEdgeNodes += nbNodes;
5016 aEdgeSM.push_back( aSubMesh );
5022 // Treat positions on edges or faces
5023 for ( int onFace = 0; onFace < 2; onFace++ )
5025 // Create arrays to store in datasets
5026 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5027 if (!nbNodes) continue;
5028 int* aNodeIDs = new int [ nbNodes ];
5029 double* aUPos = new double [ nbNodes ];
5030 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5033 // loop on sub-meshes
5034 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5035 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5036 for ( ; itSM != pListSM->end(); itSM++ )
5038 SMESHDS_SubMesh* aSubMesh = (*itSM);
5040 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5041 // loop on nodes in aSubMesh
5042 while ( itNode->more() )
5045 const SMDS_MeshNode* node = itNode->next();
5046 aNodeIDs [ iNode ] = node->GetID();
5049 const SMDS_PositionPtr pos = node->GetPosition();
5050 if ( onFace ) { // on FACE
5051 SMDS_FacePositionPtr fPos = pos;
5053 aUPos[ iNode ] = fPos->GetUParameter();
5054 aVPos[ iNode ] = fPos->GetVParameter();
5061 SMDS_EdgePositionPtr ePos = pos;
5063 aUPos[ iNode ] = ePos->GetUParameter();
5069 } // loop on nodes in aSubMesh
5070 } // loop on sub-meshes
5075 aSize[ 0 ] = nbNodes;
5077 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5078 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5079 aDataset->CreateOnDisk();
5080 aDataset->WriteOnDisk( aNodeIDs );
5081 aDataset->CloseOnDisk();
5084 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5085 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5086 aDataset->CreateOnDisk();
5087 aDataset->WriteOnDisk( aUPos );
5088 aDataset->CloseOnDisk();
5091 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5092 aDataset->CreateOnDisk();
5093 aDataset->WriteOnDisk( aVPos );
5094 aDataset->CloseOnDisk();
5099 if ( aVPos ) delete [] aVPos;
5101 } // treat positions on edges or faces
5103 // close "Node Positions" group
5104 aGroup->CloseOnDisk();
5106 } // if ( there are submeshes in SMESHDS_Mesh )
5109 // close mesh HDF group
5110 aTopGroup->CloseOnDisk();
5118 aFile->CloseOnDisk();
5121 // Convert temporary files to stream
5122 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5124 // Remove temporary files and directory
5126 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5128 return aStreamFile._retn();
5131 //=============================================================================
5133 * SMESH_Gen_i::SaveASCII
5135 * Save SMESH module's data in ASCII format
5137 //=============================================================================
5139 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5141 bool isMultiFile ) {
5142 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5143 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5144 return aStreamFile._retn();
5146 //after usual saving needs to encipher binary to text string
5147 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5148 int size = aStreamFile.in().length();
5149 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5150 for ( int i = 0; i < size; i++ )
5151 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5153 buffer[size * 3] = '\0';
5155 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5157 return anAsciiStreamFile._retn();
5160 //=============================================================================
5164 * Load SMESH module's data
5166 //=============================================================================
5168 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5169 const SALOMEDS::TMPFile& theStream,
5173 UpdateStudy(); // load geom data
5174 Kernel_Utils::Localizer loc;
5176 SALOMEDS::Study_var aStudy = getStudyServant();
5178 // Get temporary files location
5179 TCollection_AsciiString tmpDir =
5180 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5182 // Convert the stream into sequence of files to process
5183 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5186 TCollection_AsciiString aStudyName( "" );
5187 if ( isMultiFile ) {
5188 CORBA::WString_var url = aStudy->URL();
5189 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5191 // Set names of temporary files
5192 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5193 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5197 HDFdataset* aDataset;
5198 HDFgroup* aTopGroup;
5200 HDFgroup* aSubGroup;
5201 HDFgroup* aSubSubGroup;
5204 // ---> open HDF file
5205 aFile = new HDFfile( (char*) filename.ToCString() );
5207 aFile->OpenOnDisk( HDF_RDONLY );
5209 catch ( HDFexception ) {
5210 INFOS( "Load(): " << filename << " not found!" );
5214 TPythonDump pd(this); // prevent dump during loading
5216 // For PAL13473 ("Repetitive mesh") implementation.
5217 // New dependencies between SMESH objects are established:
5218 // now hypotheses can refer to meshes, shapes and other hypotheses.
5219 // To keep data consistent, the following order of data restoration
5221 // 1. Create hypotheses
5222 // 2. Create all meshes
5223 // 3. Load hypotheses' data
5226 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5227 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5228 list< SMESH::Filter_var > filters;
5230 // get total number of top-level groups
5231 int aNbGroups = aFile->nInternalObjects();
5232 if ( aNbGroups > 0 ) {
5233 // --> in first turn we should read&create hypotheses
5234 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5235 // open hypotheses root HDF group
5236 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5237 aTopGroup->OpenOnDisk();
5239 // get number of hypotheses
5240 int aNbObjects = aTopGroup->nInternalObjects();
5241 for ( int j = 0; j < aNbObjects; j++ ) {
5242 // try to identify hypothesis
5243 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5244 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5246 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5247 // open hypothesis group
5248 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5249 aGroup->OpenOnDisk();
5251 // --> get hypothesis id
5252 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5257 // get number of datasets
5258 int aNbSubObjects = aGroup->nInternalObjects();
5259 for ( int k = 0; k < aNbSubObjects; k++ ) {
5261 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5262 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5263 // --> get hypothesis name
5264 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5265 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5266 aDataset->OpenOnDisk();
5267 size = aDataset->GetSize();
5268 char* hypname_str = new char[ size ];
5269 aDataset->ReadFromDisk( hypname_str );
5270 hypname = string( hypname_str );
5271 delete [] hypname_str;
5272 aDataset->CloseOnDisk();
5274 // --> get hypothesis plugin library name
5275 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5276 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5277 aDataset->OpenOnDisk();
5278 size = aDataset->GetSize();
5279 char* libname_str = new char[ size ];
5280 aDataset->ReadFromDisk( libname_str );
5281 if(MYDEBUG) SCRUTE( libname_str );
5282 libname = string( libname_str );
5283 delete [] libname_str;
5284 aDataset->CloseOnDisk();
5286 // --> get hypothesis data
5287 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5288 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5289 aDataset->OpenOnDisk();
5290 size = aDataset->GetSize();
5291 char* hypdata_str = new char[ size ];
5292 aDataset->ReadFromDisk( hypdata_str );
5293 hypdata = string( hypdata_str );
5294 delete [] hypdata_str;
5295 aDataset->CloseOnDisk();
5298 // close hypothesis HDF group
5299 aGroup->CloseOnDisk();
5301 // --> restore hypothesis from data
5302 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5303 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5304 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5305 SMESH::SMESH_Hypothesis_var myHyp;
5307 try { // protect persistence mechanism against exceptions
5308 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5311 INFOS( "Exception during hypothesis creation" );
5314 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5316 // myImpl->LoadFrom( hypdata.c_str() );
5317 hypDataList.push_back( make_pair( myImpl, hypdata ));
5318 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5319 int newId = myStudyContext->findId( iorString.in() );
5320 myStudyContext->mapOldToNew( id, newId );
5323 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5327 // close hypotheses root HDF group
5328 aTopGroup->CloseOnDisk();
5332 // --> then we should read&create algorithms
5333 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5334 // open algorithms root HDF group
5335 aTopGroup = new HDFgroup( "Algorithms", aFile );
5336 aTopGroup->OpenOnDisk();
5338 // get number of algorithms
5339 int aNbObjects = aTopGroup->nInternalObjects();
5340 for ( int j = 0; j < aNbObjects; j++ ) {
5341 // try to identify algorithm
5342 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5343 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5345 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5346 // open algorithm group
5347 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5348 aGroup->OpenOnDisk();
5350 // --> get algorithm id
5351 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5356 // get number of datasets
5357 int aNbSubObjects = aGroup->nInternalObjects();
5358 for ( int k = 0; k < aNbSubObjects; k++ ) {
5360 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5361 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5362 // --> get algorithm name
5363 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5364 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5365 aDataset->OpenOnDisk();
5366 size = aDataset->GetSize();
5367 char* hypname_str = new char[ size ];
5368 aDataset->ReadFromDisk( hypname_str );
5369 hypname = string( hypname_str );
5370 delete [] hypname_str;
5371 aDataset->CloseOnDisk();
5373 // --> get algorithm plugin library name
5374 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5375 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5376 aDataset->OpenOnDisk();
5377 size = aDataset->GetSize();
5378 char* libname_str = new char[ size ];
5379 aDataset->ReadFromDisk( libname_str );
5380 if(MYDEBUG) SCRUTE( libname_str );
5381 libname = string( libname_str );
5382 delete [] libname_str;
5383 aDataset->CloseOnDisk();
5385 // --> get algorithm data
5386 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5387 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5388 aDataset->OpenOnDisk();
5389 size = aDataset->GetSize();
5390 char* hypdata_str = new char[ size ];
5391 aDataset->ReadFromDisk( hypdata_str );
5392 if(MYDEBUG) SCRUTE( hypdata_str );
5393 hypdata = string( hypdata_str );
5394 delete [] hypdata_str;
5395 aDataset->CloseOnDisk();
5398 // close algorithm HDF group
5399 aGroup->CloseOnDisk();
5401 // --> restore algorithm from data
5402 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5403 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5404 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5405 SMESH::SMESH_Hypothesis_var myHyp;
5407 try { // protect persistence mechanism against exceptions
5408 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5410 catch( SALOME::SALOME_Exception& ex )
5412 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5415 INFOS( "Exception during hypothesis creation" );
5418 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5420 //myImpl->LoadFrom( hypdata.c_str() );
5421 hypDataList.push_back( make_pair( myImpl, hypdata ));
5422 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5423 int newId = myStudyContext->findId( iorString.in() );
5424 myStudyContext->mapOldToNew( id, newId );
5427 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5431 // close algorithms root HDF group
5432 aTopGroup->CloseOnDisk();
5436 // --> the rest groups should be meshes
5437 for ( int i = 0; i < aNbGroups; i++ ) {
5438 // identify next group
5439 char meshName[ HDF_NAME_MAX_LEN+1 ];
5440 aFile->InternalObjectIndentify( i, meshName );
5442 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5444 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5448 // open mesh HDF group
5449 aTopGroup = new HDFgroup( meshName, aFile );
5450 aTopGroup->OpenOnDisk();
5452 // get number of child HDF objects
5453 int aNbObjects = aTopGroup->nInternalObjects();
5454 if ( aNbObjects > 0 ) {
5456 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5457 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5458 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5459 if ( !myNewMeshImpl )
5461 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5463 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5464 int newId = myStudyContext->findId( iorString.in() );
5465 myStudyContext->mapOldToNew( id, newId );
5468 // try to read and set auto color flag
5469 char aMeshAutoColorName[ 30 ];
5470 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5471 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5473 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5474 aDataset->OpenOnDisk();
5475 size = aDataset->GetSize();
5476 int* anAutoColor = new int[ size ];
5477 aDataset->ReadFromDisk( anAutoColor );
5478 aDataset->CloseOnDisk();
5479 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5480 delete [] anAutoColor;
5483 // try to read and set reference to shape
5484 GEOM::GEOM_Object_var aShapeObject;
5485 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5486 // load mesh "Ref on shape" - it's an entry to SObject
5487 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5488 aDataset->OpenOnDisk();
5489 size = aDataset->GetSize();
5490 char* refFromFile = new char[ size ];
5491 aDataset->ReadFromDisk( refFromFile );
5492 aDataset->CloseOnDisk();
5493 if ( strlen( refFromFile ) > 0 ) {
5494 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5495 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5496 if ( !CORBA::is_nil( shapeObject ) ) {
5497 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5498 if ( !aShapeObject->_is_nil() )
5499 myNewMeshImpl->SetShape( aShapeObject );
5502 delete [] refFromFile;
5505 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5506 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5508 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5509 aDataset->OpenOnDisk();
5510 size = aDataset->GetSize();
5511 int* meshPersistentId = new int[ size ];
5512 aDataset->ReadFromDisk( meshPersistentId );
5513 aDataset->CloseOnDisk();
5514 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5515 delete [] meshPersistentId;
5518 // Restore SMESH_Mesh_i::_mainShapeTick
5519 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5521 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5522 aDataset->OpenOnDisk();
5523 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5524 aDataset->ReadFromDisk( shapeTick );
5525 aDataset->CloseOnDisk();
5528 // Restore file info
5529 if ( aTopGroup->ExistInternalObject( "file info" ))
5531 aDataset = new HDFdataset( "file info", aTopGroup );
5532 aDataset->OpenOnDisk();
5533 size = aDataset->GetSize();
5534 std::string info( size, ' ');
5535 aDataset->ReadFromDisk( (char*) info.data() );
5536 aDataset->CloseOnDisk();
5537 myNewMeshImpl->FileInfoFromString( info );
5543 // As all object that can be referred by hypothesis are created,
5544 // we can restore hypothesis data
5546 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5547 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5549 SMESH_Hypothesis_i* hyp = hyp_data->first;
5550 string & data = hyp_data->second;
5551 hyp->LoadFrom( data.c_str() );
5554 // Restore the rest mesh data
5556 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5557 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5559 aTopGroup = meshi_group->second;
5560 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5562 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5563 bool hasData = false;
5566 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5567 int newId = myStudyContext->findId( iorString.in() );
5568 int meshOldId = myStudyContext->getOldId( newId );
5570 // try to find mesh data dataset
5571 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5572 // load mesh "has data" flag
5573 aDataset = new HDFdataset( "Has data", aTopGroup );
5574 aDataset->OpenOnDisk();
5575 size = aDataset->GetSize();
5576 char* strHasData = new char[ size ];
5577 aDataset->ReadFromDisk( strHasData );
5578 aDataset->CloseOnDisk();
5579 if ( strcmp( strHasData, "1") == 0 ) {
5582 delete [] strHasData;
5585 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5586 // nodes and elements are not yet put into sub-meshes)
5587 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5588 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5589 aGroup->OpenOnDisk();
5590 // get number of applied algorithms
5591 int aNbSubObjects = aGroup->nInternalObjects();
5592 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5593 for ( int j = 0; j < aNbSubObjects; j++ ) {
5594 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5595 aGroup->InternalObjectIndentify( j, name_dataset );
5596 // check if it is an algorithm
5597 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5598 aDataset = new HDFdataset( name_dataset, aGroup );
5599 aDataset->OpenOnDisk();
5600 size = aDataset->GetSize();
5601 char* refFromFile = new char[ size ];
5602 aDataset->ReadFromDisk( refFromFile );
5603 aDataset->CloseOnDisk();
5604 // san - it is impossible to recover applied algorithms using their entries within Load() method
5605 int id = atoi( refFromFile );
5606 delete [] refFromFile;
5607 string anIOR = myStudyContext->getIORbyOldId( id );
5608 if ( !anIOR.empty() ) {
5609 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5610 if ( !CORBA::is_nil( hypObject ) ) {
5611 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5612 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5613 || !myNewMeshImpl->HasShapeToMesh()) )
5614 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5619 aGroup->CloseOnDisk();
5622 // try to get applied hypotheses
5623 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5624 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5625 aGroup->OpenOnDisk();
5626 // get number of applied hypotheses
5627 int aNbSubObjects = aGroup->nInternalObjects();
5628 for ( int j = 0; j < aNbSubObjects; j++ ) {
5629 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5630 aGroup->InternalObjectIndentify( j, name_dataset );
5631 // check if it is a hypothesis
5632 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5633 aDataset = new HDFdataset( name_dataset, aGroup );
5634 aDataset->OpenOnDisk();
5635 size = aDataset->GetSize();
5636 char* refFromFile = new char[ size ];
5637 aDataset->ReadFromDisk( refFromFile );
5638 aDataset->CloseOnDisk();
5639 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5640 int id = atoi( refFromFile );
5641 delete [] refFromFile;
5642 string anIOR = myStudyContext->getIORbyOldId( id );
5643 if ( !anIOR.empty() ) {
5644 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5645 if ( !CORBA::is_nil( hypObject ) ) {
5646 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5647 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5648 || !myNewMeshImpl->HasShapeToMesh()) )
5649 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5654 aGroup->CloseOnDisk();
5657 // --> try to find SUB-MESHES containers for each type of submesh
5658 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5659 const char* name_meshgroup = 0;
5660 if ( j == GetSubMeshOnVertexTag() )
5661 name_meshgroup = "SubMeshes On Vertex";
5662 else if ( j == GetSubMeshOnEdgeTag() )
5663 name_meshgroup = "SubMeshes On Edge";
5664 else if ( j == GetSubMeshOnWireTag() )
5665 name_meshgroup = "SubMeshes On Wire";
5666 else if ( j == GetSubMeshOnFaceTag() )
5667 name_meshgroup = "SubMeshes On Face";
5668 else if ( j == GetSubMeshOnShellTag() )
5669 name_meshgroup = "SubMeshes On Shell";
5670 else if ( j == GetSubMeshOnSolidTag() )
5671 name_meshgroup = "SubMeshes On Solid";
5672 else if ( j == GetSubMeshOnCompoundTag() )
5673 name_meshgroup = "SubMeshes On Compound";
5675 // try to get submeshes container HDF group
5676 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5677 // open submeshes containers HDF group
5678 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5679 aGroup->OpenOnDisk();
5681 // get number of submeshes
5682 int aNbSubMeshes = aGroup->nInternalObjects();
5683 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5685 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5686 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5687 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5688 // --> get submesh id
5689 int subid = atoi( name_submeshgroup + 7 );
5692 // open submesh HDF group
5693 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5694 aSubGroup->OpenOnDisk();
5696 // try to read and set reference to subshape
5697 GEOM::GEOM_Object_var aSubShapeObject;
5698 SMESH::SMESH_subMesh_var aSubMesh;
5700 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5701 // load submesh "Ref on shape" - it's an entry to SObject
5702 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5703 aDataset->OpenOnDisk();
5704 size = aDataset->GetSize();
5705 char* refFromFile = new char[ size ];
5706 aDataset->ReadFromDisk( refFromFile );
5707 aDataset->CloseOnDisk();
5708 if ( strlen( refFromFile ) > 0 ) {
5709 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5710 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5711 if ( !CORBA::is_nil( subShapeObject ) ) {
5712 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5713 if ( !aSubShapeObject->_is_nil() )
5714 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5715 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5716 if ( aSubMesh->_is_nil() )
5718 string iorSubString = GetORB()->object_to_string( aSubMesh );
5719 int newSubId = myStudyContext->findId( iorSubString );
5720 myStudyContext->mapOldToNew( subid, newSubId );
5723 delete [] refFromFile;
5726 if ( aSubMesh->_is_nil() )
5729 // try to get applied algorithms
5730 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5731 // open "applied algorithms" HDF group
5732 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5733 aSubSubGroup->OpenOnDisk();
5734 // get number of applied algorithms
5735 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5736 for ( int l = 0; l < aNbSubObjects; l++ ) {
5737 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5738 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5739 // check if it is an algorithm
5740 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5741 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5742 aDataset->OpenOnDisk();
5743 size = aDataset->GetSize();
5744 char* refFromFile = new char[ size ];
5745 aDataset->ReadFromDisk( refFromFile );
5746 aDataset->CloseOnDisk();
5748 int id = atoi( refFromFile );
5749 string anIOR = myStudyContext->getIORbyOldId( id );
5750 if ( !anIOR.empty() ) {
5751 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5752 if ( !CORBA::is_nil( hypObject ) ) {
5753 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5754 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5755 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5758 delete [] refFromFile;
5761 // close "applied algorithms" HDF group
5762 aSubSubGroup->CloseOnDisk();
5765 // try to get applied hypotheses
5766 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5767 // open "applied hypotheses" HDF group
5768 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5769 aSubSubGroup->OpenOnDisk();
5770 // get number of applied hypotheses
5771 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5772 for ( int l = 0; l < aNbSubObjects; l++ ) {
5773 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5774 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5775 // check if it is a hypothesis
5776 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5777 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5778 aDataset->OpenOnDisk();
5779 size = aDataset->GetSize();
5780 char* refFromFile = new char[ size ];
5781 aDataset->ReadFromDisk( refFromFile );
5782 aDataset->CloseOnDisk();
5784 int id = atoi( refFromFile );
5785 string anIOR = myStudyContext->getIORbyOldId( id );
5786 if ( !anIOR.empty() ) {
5787 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5788 if ( !CORBA::is_nil( hypObject ) ) {
5789 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5790 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5791 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5794 delete [] refFromFile;
5797 // close "APPLIED HYPOTHESES" hdf group
5798 aSubSubGroup->CloseOnDisk();
5801 // close SUB-MESH hdf group
5802 aSubGroup->CloseOnDisk();
5805 // close SUB-MESHES containers hdf group
5806 aGroup->CloseOnDisk();
5810 // try to get GROUPS
5811 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5812 char name_group[ 30 ];
5813 if ( ii == GetNodeGroupsTag() )
5814 strcpy( name_group, "Groups of Nodes" );
5815 else if ( ii == GetEdgeGroupsTag() )
5816 strcpy( name_group, "Groups of Edges" );
5817 else if ( ii == GetFaceGroupsTag() )
5818 strcpy( name_group, "Groups of Faces" );
5819 else if ( ii == GetVolumeGroupsTag() )
5820 strcpy( name_group, "Groups of Volumes" );
5821 else if ( ii == Get0DElementsGroupsTag() )
5822 strcpy( name_group, "Groups of 0D Elements" );
5823 else if ( ii == GetBallElementsGroupsTag() )
5824 strcpy( name_group, "Groups of Balls" );
5826 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5827 aGroup = new HDFgroup( name_group, aTopGroup );
5828 aGroup->OpenOnDisk();
5829 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5830 // within aGroup->ExistInternalObject( name )
5831 std::vector< std::string > subNames;
5832 TColStd_MapOfAsciiString mapOfNames;
5833 aGroup->GetAllObjects( subNames );
5834 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5835 mapOfNames.Add( subNames[ iN ].c_str() );
5837 for ( size_t j = 0; j < subNames.size(); j++ ) {
5838 const std::string& name_dataset = subNames[ j ];
5839 // check if it is a group
5840 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5843 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5846 int groupID = -1; // group local ID (also persistent)
5848 groupID = atoi( endptr + 1 );
5849 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5850 aDataset->OpenOnDisk();
5852 // Retrieve actual group name
5853 size = aDataset->GetSize();
5854 char* nameFromFile = new char[ size ];
5855 aDataset->ReadFromDisk( nameFromFile );
5856 aDataset->CloseOnDisk();
5858 // Try to find a shape reference
5859 TopoDS_Shape aShape;
5860 char aRefName[ 30 ];
5861 sprintf( aRefName, "Ref on shape %d", subid);
5862 if ( mapOfNames.Contains( aRefName ))
5864 // load mesh "Ref on shape" - it's an entry to SObject
5865 aDataset = new HDFdataset( aRefName, aGroup );
5866 aDataset->OpenOnDisk();
5867 size = aDataset->GetSize();
5868 char* refFromFile = new char[ size ];
5869 aDataset->ReadFromDisk( refFromFile );
5870 aDataset->CloseOnDisk();
5871 if ( strlen( refFromFile ) > 0 ) {
5872 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5873 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5874 if ( !CORBA::is_nil( shapeObject ) ) {
5875 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5876 if ( !aShapeObject->_is_nil() )
5877 aShape = GeomObjectToShape( aShapeObject );
5880 delete [] refFromFile;
5882 // Try to read a filter of SMESH_GroupOnFilter
5883 SMESH::Filter_var filter;
5884 SMESH_PredicatePtr predicate;
5885 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5886 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5888 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5889 aDataset->OpenOnDisk();
5890 size = aDataset->GetSize();
5891 char* persistStr = new char[ size ];
5892 aDataset->ReadFromDisk( persistStr );
5893 aDataset->CloseOnDisk();
5894 if ( strlen( persistStr ) > 0 ) {
5895 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5896 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5897 filters.push_back( filter );
5899 delete [] persistStr;
5902 // Create group servant
5903 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5904 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5905 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5906 delete [] nameFromFile;
5907 // Obtain a SMESHDS_Group object
5908 if ( aNewGroup->_is_nil() )
5911 string iorSubString = GetORB()->object_to_string( aNewGroup );
5912 int newSubId = myStudyContext->findId( iorSubString );
5913 myStudyContext->mapOldToNew( subid, newSubId );
5915 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5919 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5920 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5922 aFilterGroup->SetFilter( filter );
5923 filter->UnRegister();
5925 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5926 if ( !aGroupBaseDS )
5929 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5932 // Read color of the group
5933 char aGroupColorName[ 30 ];
5934 sprintf( aGroupColorName, "ColorGroup %d", subid);
5935 if ( mapOfNames.Contains( aGroupColorName ))
5937 aDataset = new HDFdataset( aGroupColorName, aGroup );
5938 aDataset->OpenOnDisk();
5939 size = aDataset->GetSize();
5940 double* anRGB = new double[ size ];
5941 aDataset->ReadFromDisk( anRGB );
5942 aDataset->CloseOnDisk();
5943 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5944 aGroupBaseDS->SetColor( aColor );
5949 aGroup->CloseOnDisk();
5953 // instead of reading mesh data, we read only brief information of all
5954 // objects: mesh, groups, sub-meshes (issue 0021208)
5957 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5958 meshfile.ToCString(), filename.ToCString(),
5962 // read Sub-Mesh ORDER if any
5963 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) { // old version keeps ids
5964 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5965 aDataset->OpenOnDisk();
5966 size = aDataset->GetSize();
5967 int* smIDs = new int[ size ];
5968 aDataset->ReadFromDisk( smIDs );
5969 aDataset->CloseOnDisk();
5970 TListOfListOfInt anOrderIds;
5971 anOrderIds.push_back( TListOfInt() );
5972 for ( int i = 0; i < size; i++ )
5973 if ( smIDs[ i ] < 0 ) // is separator
5974 anOrderIds.push_back( TListOfInt() );
5976 anOrderIds.back().push_back(smIDs[ i ]);
5978 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5981 if ( aTopGroup->ExistInternalObject( "MeshOrder_new" )) // new version keeps entries
5983 aDataset = new HDFdataset( "MeshOrder_new", aTopGroup );
5984 aDataset->OpenOnDisk();
5985 size = aDataset->GetSize();
5986 std::string dataString; dataString.resize( size );
5987 aDataset->ReadFromDisk((char*) dataString.data() );
5988 aDataset->CloseOnDisk();
5990 std::istringstream istream( dataString.data() );
5991 boost::archive::text_iarchive archive( istream );
5992 std::list< std::list< std::string > > orderEntryLists;
5994 archive >> orderEntryLists;
5998 TListOfListOfInt anOrderIds;
5999 for ( const std::list< std::string >& entryList : orderEntryLists )
6001 anOrderIds.emplace_back();
6002 for ( const std::string & entry : entryList )
6004 GEOM::GEOM_Object_var go = GetGeomObjectByEntry( entry );
6005 TopoDS_Shape shape = GeomObjectToShape( go );
6006 if ( SMESH_subMesh* sm = myNewMeshImpl->GetImpl().GetSubMesh( shape ))
6007 anOrderIds.back().emplace_back( sm->GetId() );
6010 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
6014 // update hyps needing full mesh data restored (issue 20918)
6015 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
6017 SMESH_Hypothesis_i* hyp = hyp_data->first;
6018 hyp->UpdateAsMeshesRestored();
6021 // notify algos on completed restoration to set sub-mesh event listeners
6022 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6024 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6025 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6027 TopoDS_Shape myLocShape;
6028 if(myLocMesh.HasShapeToMesh())
6029 myLocShape = myLocMesh.GetShapeToMesh();
6031 myLocShape = SMESH_Mesh::PseudoShape();
6033 myLocMesh.GetSubMesh(myLocShape)->
6034 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6037 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6038 list< SMESH::Filter_var >::iterator f = filters.begin();
6039 for ( ; f != filters.end(); ++f )
6040 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6041 fi->FindBaseObjects();
6046 aTopGroup->CloseOnDisk();
6049 aFile->CloseOnDisk();
6052 // Remove temporary files created from the stream
6055 SMESH_File meshFile( meshfile.ToCString() );
6056 if ( !meshFile ) // no meshfile exists
6058 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6062 Engines::Container_var container = GetContainerRef();
6063 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6065 container_i->registerTemporaryFile( filename.ToCString() );
6066 container_i->registerTemporaryFile( meshfile.ToCString() );
6067 container_i->registerTemporaryFile( tmpDir.ToCString() );
6072 // creation of tree nodes for all data objects in the study
6073 // to support tree representation customization and drag-n-drop:
6074 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6075 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6076 useCaseBuilder->SetRootCurrent();
6077 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6078 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6079 for (it->InitEx(true); it->More(); it->Next()) {
6080 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6087 //=============================================================================
6089 * SMESH_Gen_i::LoadASCII
6091 * Load SMESH module's data in ASCII format
6093 //=============================================================================
6095 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6096 const SALOMEDS::TMPFile& theStream,
6098 bool isMultiFile ) {
6099 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6100 return Load( theComponent, theStream, theURL, isMultiFile );
6102 //before call main ::Load method it's need for decipher text format to
6103 //binary ( "|xx" => x' )
6104 int size = theStream.length();
6105 if ( int((size / 3 )*3) != size ) //error size of buffer
6108 int real_size = int(size / 3);
6110 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6113 unsigned int c = -1;
6114 for ( int i = 0; i < real_size; i++ )
6116 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6117 sscanf( tmp, "%x", &c );
6118 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6121 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6123 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6126 //=============================================================================
6128 * SMESH_Gen_i::Close
6130 * Clears study-connected data when it is closed
6132 //=============================================================================
6134 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6136 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6138 // Clear study contexts data
6139 myStudyContext->Clear();
6141 // remove the tmp files meshes are loaded from
6142 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6144 // Clean trace of API methods calls
6150 //=============================================================================
6152 * SMESH_Gen_i::ComponentDataType
6154 * Get component data type
6156 //=============================================================================
6158 char* SMESH_Gen_i::ComponentDataType()
6160 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6161 return CORBA::string_dup( "SMESH" );
6165 //=============================================================================
6167 * SMESH_Gen_i::IORToLocalPersistentID
6169 * Transform data from transient form to persistent
6171 //=============================================================================
6173 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6174 const char* IORString,
6175 CORBA::Boolean /*isMultiFile*/,
6176 CORBA::Boolean /*isASCII*/ )
6178 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6180 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6181 int anId = myStudyContext->findId( IORString );
6183 if(MYDEBUG) MESSAGE( "VSR " << anId )
6185 sprintf( strId, "%d", anId );
6186 return CORBA::string_dup( strId );
6189 return CORBA::string_dup( "" );
6192 //=============================================================================
6194 * SMESH_Gen_i::LocalPersistentIDToIOR
6196 * Transform data from persistent form to transient
6198 //=============================================================================
6200 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6201 const char* aLocalPersistentID,
6202 CORBA::Boolean /*isMultiFile*/,
6203 CORBA::Boolean /*isASCII*/ )
6205 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6207 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6208 int anId = atoi( aLocalPersistentID );
6209 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6211 return CORBA::string_dup( "" );
6214 //=======================================================================
6215 //function : RegisterObject
6217 //=======================================================================
6219 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6221 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6222 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6223 return myStudyContext->addObject( string( iorString.in() ) );
6228 //================================================================================
6230 * \brief Return id of registered object
6231 * \param theObject - the Object
6232 * \retval int - Object id
6234 //================================================================================
6236 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6238 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6239 string iorString = GetORB()->object_to_string( theObject );
6240 return myStudyContext->findId( iorString );
6245 //=============================================================================
6247 * SMESH_Gen_i::SetName
6249 * Set a new object name
6251 //=============================================================================
6253 void SMESH_Gen_i::SetName(const char* theIOR,
6254 const char* theName)
6256 if ( theIOR && strcmp( theIOR, "" ) ) {
6257 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6258 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6259 if ( !aSO->_is_nil() ) {
6260 SetName( aSO, theName );
6265 // Version information
6266 char* SMESH_Gen_i::getVersion()
6268 #if SMESH_DEVELOPMENT
6269 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6271 return CORBA::string_dup(SMESH_VERSION_STR);
6275 //=================================================================================
6276 // function : Move()
6277 // purpose : Moves objects to the specified position.
6278 // Is used in the drag-n-drop functionality.
6279 //=================================================================================
6281 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6282 SALOMEDS::SObject_ptr where,
6285 if ( CORBA::is_nil( where ) ) return;
6287 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6288 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6289 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6290 std::string dataType = father->ComponentDataType();
6291 if ( dataType != "SMESH" ) return; // not a SMESH component
6293 SALOMEDS::SObject_var objAfter;
6294 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6295 // insert at given row -> find insertion position
6296 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6298 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6299 if ( i == row && useCaseIt->More() ) {
6300 objAfter = useCaseIt->Value();
6304 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6305 SALOMEDS::SObject_var sobj = what[i];
6306 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6307 // insert the object to the use case tree
6308 if ( !CORBA::is_nil( objAfter ) )
6309 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6311 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6314 //================================================================================
6316 * \brief Returns true if algorithm can be used to mesh a given geometry
6317 * \param [in] theAlgoType - the algorithm type
6318 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6319 * \param [in] theGeomObject - the geometry to mesh
6320 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6321 * else, returns \c True if at least one shape is meshable
6322 * \return CORBA::Boolean - can or can't
6324 //================================================================================
6326 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6327 const char* theLibName,
6328 GEOM::GEOM_Object_ptr theGeomObject,
6329 CORBA::Boolean toCheckAll)
6333 std::string aPlatformLibName;
6334 GenericHypothesisCreator_i* aCreator =
6335 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6338 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6339 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6340 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6347 SMESH_CATCH( SMESH::doNothing );
6350 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6355 //================================================================================
6357 * \brief Collect indices of elements, which are located inside the sphere
6359 //================================================================================
6361 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6362 SMESH::ElementType theElemType,
6368 SMESH::long_array_var aResult = new SMESH::long_array();
6369 if ( meshPart->_is_nil() )
6370 return aResult._retn();
6372 // 1. Create geometrical object
6373 gp_Pnt aP( theX, theY, theZ );
6374 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6376 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6378 if ( lst.size() > 0 ) {
6379 aResult->length( lst.size() );
6380 for ( size_t i = 0; i < lst.size(); i++ ) {
6381 aResult[i] = lst[i];
6384 return aResult._retn();
6387 //================================================================================
6389 * \brief Collect indices of elements, which are located inside the box
6391 //================================================================================
6393 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6394 SMESH::ElementType theElemType,
6395 CORBA::Double theX1,
6396 CORBA::Double theY1,
6397 CORBA::Double theZ1,
6398 CORBA::Double theX2,
6399 CORBA::Double theY2,
6400 CORBA::Double theZ2)
6402 SMESH::long_array_var aResult = new SMESH::long_array();
6403 if( meshPart->_is_nil() )
6404 return aResult._retn();
6406 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ),
6407 gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6409 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6411 if( lst.size() > 0 ) {
6412 aResult->length( lst.size() );
6413 for ( size_t i = 0; i < lst.size(); i++ ) {
6414 aResult[i] = lst[i];
6417 return aResult._retn();
6420 //================================================================================
6422 * \brief Collect indices of elements, which are located inside the cylinder
6424 //================================================================================
6426 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6427 SMESH::ElementType theElemType,
6431 CORBA::Double theDX,
6432 CORBA::Double theDY,
6433 CORBA::Double theDZ,
6435 CORBA::Double theR )
6437 SMESH::long_array_var aResult = new SMESH::long_array();
6438 if( meshPart->_is_nil() )
6439 return aResult._retn();
6441 gp_Pnt aP( theX, theY, theZ );
6442 gp_Vec aV( theDX, theDY, theDZ );
6443 gp_Ax2 anAxes (aP, aV);
6445 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6447 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6449 if( lst.size() > 0 ) {
6450 aResult->length( lst.size() );
6451 for ( size_t i = 0; i < lst.size(); i++ ) {
6452 aResult[i] = lst[i];
6455 return aResult._retn();
6458 //================================================================================
6460 * \brief Collect indices of elements, which are located inside the geom object
6462 //================================================================================
6464 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6465 SMESH::ElementType theElemType,
6466 GEOM::GEOM_Object_ptr theGeom,
6467 CORBA::Double theTolerance )
6469 SMESH::long_array_var aResult = new SMESH::long_array();
6470 if( meshPart->_is_nil() || theGeom->_is_nil() )
6471 return aResult._retn();
6473 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6475 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6477 if( lst.size() > 0 ) {
6478 aResult->length( lst.size() );
6479 for ( size_t i = 0; i < lst.size(); i++ ) {
6480 aResult[i] = lst[i];
6483 return aResult._retn();
6486 //================================================================================
6488 * \brief Collect indices of elements, which are located inside the TopoDS_Shape
6490 //================================================================================
6492 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6493 SMESH::ElementType theElemType,
6494 const TopoDS_Shape& theShape,
6495 double* theTolerance) {
6497 std::vector<long> res;
6498 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6500 if ( mesh->_is_nil() )
6503 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6507 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6512 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6513 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6514 anElementsOnShape->SetAllNodes( true );
6515 anElementsOnShape->SetMesh( meshDS );
6516 anElementsOnShape->SetShape( theShape, aType );
6519 anElementsOnShape->SetTolerance(*theTolerance);
6521 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6522 if ( !msource->_is_nil() ) { // Mesh case
6523 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6525 while ( elemIt->more() ) {
6526 const SMDS_MeshElement* anElem = elemIt->next();
6527 long anId = anElem->GetID();
6528 if ( anElementsOnShape->IsSatisfy( anId ) )
6529 res.push_back( anId );
6533 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6534 if ( !gsource->_is_nil() ) {
6535 if(theElemType == SMESH::NODE) {
6536 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6537 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6538 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6539 long anId = node->GetID();
6540 if ( anElementsOnShape->IsSatisfy( anId ) )
6541 res.push_back( anId );
6544 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6545 SMESH::long_array_var elems = gsource->GetListOfID();
6546 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6547 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6548 long anId = elem->GetID();
6549 if ( anElementsOnShape->IsSatisfy( anId ) )
6550 res.push_back( anId );
6555 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6556 if ( !smsource->_is_nil() ) {
6557 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6558 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6559 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6561 long anId = elem->GetID();
6562 if ( anElementsOnShape->IsSatisfy( anId ) )
6563 res.push_back( anId );