1 // Copyright (C) 2007-2019 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_SetIterator.hxx"
89 #include "SMDS_SpacePosition.hxx"
90 #include "SMDS_VertexPosition.hxx"
91 #include "SMESHDS_Document.hxx"
92 #include "SMESHDS_Group.hxx"
93 #include "SMESHDS_GroupOnGeom.hxx"
94 #include "SMESH_Algo_i.hxx"
95 #include "SMESH_File.hxx"
96 #include "SMESH_Group.hxx"
97 #include "SMESH_Group_i.hxx"
98 #include "SMESH_Hypothesis.hxx"
99 #include "SMESH_Hypothesis_i.hxx"
100 #include "SMESH_Mesh.hxx"
101 #include "SMESH_MeshEditor.hxx"
102 #include "SMESH_Mesh_i.hxx"
103 #include "SMESH_PreMeshInfo.hxx"
104 #include "SMESH_PythonDump.hxx"
105 #include "SMESH_ControlsDef.hxx"
107 // to pass CORBA exception through SMESH_TRY
108 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
109 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
111 #include CORBA_SERVER_HEADER(SMESH_Group)
112 #include CORBA_SERVER_HEADER(SMESH_Filter)
113 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
116 #include <GEOMImpl_Types.hxx>
117 #include <GEOM_Client.hxx>
119 #include <Basics_Utils.hxx>
120 #include <Basics_DirUtils.hxx>
122 #include <OpUtil.hxx>
123 #include <SALOMEDS_Tool.hxx>
124 #include <SALOME_Container_i.hxx>
125 #include <SALOME_LifeCycleCORBA.hxx>
126 #include <SALOME_NamingService.hxx>
127 #include <Utils_CorbaException.hxx>
128 #include <Utils_ExceptHandlers.hxx>
129 #include <Utils_SINGLETON.hxx>
130 #include <utilities.h>
132 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
133 #include CORBA_CLIENT_HEADER(SALOME_Session)
135 // helpers about SALOME::GenericObj
136 #include <SALOMEDS_wrap.hxx>
137 #include <SALOMEDS_Attributes_wrap.hxx>
138 #include <GEOM_wrap.hxx>
148 using SMESH::TPythonDump;
151 #define NUM_TMP_FILES 2
154 static int MYDEBUG = 0;
156 static int MYDEBUG = 0;
159 // Static variables definition
160 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
161 CORBA::ORB_var SMESH_Gen_i::myOrb;
162 PortableServer::POA_var SMESH_Gen_i::myPoa;
163 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
164 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
165 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
168 const int nbElemPerDiagonal = 10;
170 //=============================================================================
172 * GetServant [ static ]
174 * Get servant of the CORBA object
176 //=============================================================================
178 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
180 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
183 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
186 catch (PortableServer::POA::ObjectNotActive &ex)
188 INFOS("GetServant: ObjectNotActive");
191 catch (PortableServer::POA::WrongAdapter &ex)
193 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
196 catch (PortableServer::POA::WrongPolicy &ex)
198 INFOS("GetServant: WrongPolicy");
203 INFOS( "GetServant - Unknown exception was caught!!!" );
208 //=============================================================================
210 * SObjectToObject [ static ]
212 * Get CORBA object corresponding to the SALOMEDS::SObject
214 //=============================================================================
216 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
218 SALOMEDS::GenericAttribute_wrap anAttr;
219 CORBA::Object_var anObj;
220 if ( !theSObject->_is_nil() ) {
222 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
223 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
224 CORBA::String_var aValue = anIOR->Value();
225 if( strcmp( aValue, "" ) != 0 )
226 anObj = GetORB()->string_to_object( aValue );
230 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
236 //=============================================================================
240 * Get SALOME_NamingService object
242 //=============================================================================
244 SALOME_NamingService* SMESH_Gen_i::GetNS()
246 if ( myNS == NULL ) {
247 myNS = SINGLETON_<SALOME_NamingService>::Instance();
248 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
249 myNS->init_orb( GetORB() );
254 //=============================================================================
258 * Get SALOME_LifeCycleCORBA object
260 //=============================================================================
262 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
264 if ( myLCC == NULL ) {
265 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
270 //=============================================================================
272 * GetGeomEngine [ static ]
274 * Get GEOM::GEOM_Gen reference
276 //=============================================================================
278 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( bool isShaper )
280 Engines::EngineComponent_ptr temp =
281 GetLCC()->FindOrLoad_Component( isShaper ? "FactoryServer" : "FactoryServer",
282 isShaper ? "SHAPERSTUDY" : "GEOM" );
283 myGeomGen = GEOM::GEOM_Gen::_narrow( temp );
288 //=============================================================================
290 * GetGeomEngine [ static ]
292 * Get GEOM::GEOM_Gen reference
294 //=============================================================================
296 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
298 GEOM::GEOM_Gen_ptr gen;
299 if ( !CORBA::is_nil( go ))
304 //=============================================================================
306 * SMESH_Gen_i::SMESH_Gen_i
308 * Default constructor: not for use
310 //=============================================================================
312 SMESH_Gen_i::SMESH_Gen_i()
316 //=============================================================================
318 * SMESH_Gen_i::SMESH_Gen_i
320 * Standard constructor, used with Container
322 //=============================================================================
324 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
325 PortableServer::POA_ptr poa,
326 PortableServer::ObjectId* contId,
327 const char* instanceName,
328 const char* interfaceName )
329 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
332 myOrb = CORBA::ORB::_duplicate(orb);
333 myPoa = PortableServer::POA::_duplicate(poa);
336 _id = myPoa->activate_object( _thisObj );
338 myStudyContext = new StudyContext;
340 myIsEmbeddedMode = false;
341 myIsEnablePublish = true;
342 myShapeReader = NULL; // shape reader
344 myIsHistoricalPythonDump = true;
345 myToForgetMeshDataOnHypModif = false;
347 // set it in standalone mode only
348 //OSD::SetSignal( true );
350 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
351 // find out mode (embedded or standalone) here else
352 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
353 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
354 if ( SALOME_NamingService* ns = GetNS() )
356 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
357 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
358 if ( !session->_is_nil() )
360 CORBA::String_var str_host = session->getHostname();
361 CORBA::Long s_pid = session->getPID();
362 string my_host = Kernel_Utils::GetHostname();
364 long my_pid = (long)_getpid();
366 long my_pid = (long) getpid();
368 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
373 //=============================================================================
375 * SMESH_Gen_i::~SMESH_Gen_i
379 //=============================================================================
381 SMESH_Gen_i::~SMESH_Gen_i()
383 // delete hypothesis creators
384 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
385 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
387 // same creator can be mapped under different names
388 GenericHypothesisCreator_i* creator = (*itHyp).second;
392 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
393 if ( creator == (*itHyp2).second )
394 (*itHyp2).second = 0;
396 myHypCreatorMap.clear();
398 // Clear study contexts data
399 delete myStudyContext;
401 // delete shape reader
403 delete myShapeReader;
405 //=============================================================================
407 * SMESH_Gen_i::getHypothesisCreator
409 * Get hypothesis creator
411 //=============================================================================
412 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
413 const char* theLibName,
414 std::string& thePlatformLibName)
415 throw (SALOME::SALOME_Exception)
417 std::string aPlatformLibName;
418 /* It's Need to translate lib name for WIN32 or X platform */
419 if ( theLibName && theLibName[0] != '\0' )
421 int libNameLen = strlen(theLibName);
422 //check for old format "libXXXXXXX.so"
423 if (libNameLen > 7 &&
424 !strncmp( theLibName, "lib", 3 ) &&
425 !strcmp( theLibName+libNameLen-3, ".so" ))
429 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
430 #elif defined(__APPLE__)
431 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
433 aPlatformLibName = theLibName;
438 //try to use new format
440 aPlatformLibName = theLibName;
441 aPlatformLibName += ".dll";
442 #elif defined(__APPLE__)
443 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
445 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
449 thePlatformLibName = aPlatformLibName;
451 Unexpect aCatch(SALOME_SalomeException);
452 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
454 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
455 GenericHypothesisCreator_i* aCreator;
458 // check, if creator for this hypothesis type already exists
459 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
461 // load plugin library
462 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
465 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
467 const char* path = aPlatformLibName.c_str();
470 const char* path = aPlatformLibName.c_str();
472 LibHandle libHandle = LoadLib( path );
473 #if defined(WIN32) && defined(UNICODE)
478 // report any error, if occurred
480 const char* anError = dlerror();
481 throw(SALOME_Exception( anError ));
483 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
484 << aPlatformLibName));
488 // get method, returning hypothesis creator
489 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
490 GetHypothesisCreator procHandle =
491 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
494 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
495 << aPlatformLibName ));
496 UnLoadLib(libHandle);
499 // get hypothesis creator
500 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
501 aCreator = procHandle(theHypName);
504 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
505 << aPlatformLibName));
507 // map hypothesis creator to a hypothesis name
508 myHypCreatorMap[string(theHypName)] = aCreator;
513 return myHypCreatorMap[string(theHypName)];
516 catch (SALOME_Exception& S_ex)
518 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
523 //=============================================================================
525 * SMESH_Gen_i::createHypothesis
527 * Create hypothesis of given type
529 //=============================================================================
530 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
531 const char* theLibName)
533 SMESH_Hypothesis_i* myHypothesis_i = 0;
534 SMESH::SMESH_Hypothesis_var hypothesis_i;
535 std::string aPlatformLibName;
536 GenericHypothesisCreator_i* aCreator =
537 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
539 // create a new hypothesis object, store its ref. in studyContext
540 myHypothesis_i = aCreator->Create(myPoa, &myGen);
543 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
544 CORBA::String_var hypName = myHypothesis_i->GetName();
545 myHypCreatorMap[ hypName.in() ] = aCreator;
547 // activate the CORBA servant of hypothesis
548 hypothesis_i = myHypothesis_i->_this();
549 int nextId = RegisterObject( hypothesis_i );
550 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
551 else { nextId = 0; } // avoid "unused variable" warning in release mode
553 return hypothesis_i._retn();
556 //=============================================================================
558 * SMESH_Gen_i::createMesh
560 * Create empty mesh on shape
562 //=============================================================================
563 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
564 throw ( SALOME::SALOME_Exception )
566 Unexpect aCatch(SALOME_SalomeException);
567 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
569 // Get or create the GEOM_Client instance
571 // create a new mesh object servant, store it in a map in study context
572 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
573 // create a new mesh object
574 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
575 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
577 // activate the CORBA servant of Mesh
578 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
579 int nextId = RegisterObject( mesh );
580 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
581 else { nextId = 0; } // avoid "unused variable" warning in release mode
584 catch (SALOME_Exception& S_ex) {
585 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
587 return SMESH::SMESH_Mesh::_nil();
590 //=============================================================================
592 * SMESH_Gen_i::GetShapeReader
596 //=============================================================================
597 GEOM_Client* SMESH_Gen_i::GetShapeReader()
599 // create shape reader if necessary
600 if ( !myShapeReader )
601 myShapeReader = new GEOM_Client(GetContainerRef());
602 ASSERT( myShapeReader );
603 return myShapeReader;
606 //=============================================================================
608 * SMESH_Gen_i::SetGeomEngine
610 * Set GEOM::GEOM_Gen reference
612 //=============================================================================
613 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
614 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
616 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
617 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
618 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
622 //=============================================================================
624 * SMESH_Gen_i::SetEmbeddedMode
628 //=============================================================================
630 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
632 myIsEmbeddedMode = theMode;
634 if ( !myIsEmbeddedMode ) {
635 //PAL10867: disable signals catching with "noexcepthandler" option
636 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
637 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
642 char* envDisableFPE = getenv("DISABLE_FPE");
643 if (envDisableFPE && atoi(envDisableFPE))
648 OSD::SetSignal( raiseFPE );
650 // else OSD::SetSignal() is called in GUI
654 //=============================================================================
656 * SMESH_Gen_i::IsEmbeddedMode
660 //=============================================================================
662 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
664 return myIsEmbeddedMode;
667 //=============================================================================
669 * SMESH_Gen_i::SetEnablePublish
671 * Set enable publishing in the study
673 //=============================================================================
674 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
676 myIsEnablePublish = theIsEnablePublish;
679 //=============================================================================
681 * SMESH_Gen_i::IsEnablePublish
683 * Check enable publishing
685 //=============================================================================
687 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
689 return myIsEnablePublish;
692 //=============================================================================
694 * SMESH_Gen_i::UpdateStudy
696 * Update study (needed at switching GEOM->SMESH)
698 //=============================================================================
700 void SMESH_Gen_i::UpdateStudy()
702 if ( !myStudyContext )
703 myStudyContext = new StudyContext;
705 SALOMEDS::Study_var aStudy = getStudyServant();
706 if ( !CORBA::is_nil( aStudy ) )
708 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
710 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
711 if( !GEOM_var->_is_nil() )
712 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
714 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
715 if( !GEOM_var->_is_nil() )
716 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
718 // NPAL16168, issue 0020210
719 // Let meshes update their data depending on GEOM groups that could change
720 CORBA::String_var compDataType = ComponentDataType();
721 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
722 if ( !me->_is_nil() ) {
723 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
724 for ( ; anIter->More(); anIter->Next() ) {
725 SALOMEDS::SObject_wrap so = anIter->Value();
726 CORBA::Object_var ior = SObjectToObject( so );
727 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
728 mesh->CheckGeomModif();
734 //=================================================================================
735 // function : hasObjectInfo()
736 // purpose : shows if module provides information for its objects
737 //=================================================================================
739 bool SMESH_Gen_i::hasObjectInfo()
744 //=================================================================================
745 // function : getObjectInfo()
746 // purpose : returns an information for a given object by its entry
747 //=================================================================================
749 char* SMESH_Gen_i::getObjectInfo( const char* entry )
751 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
752 // for the rest, "module 'SMESH', ID=0:1:2:*"
756 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
757 CORBA::Object_var obj = SObjectToObject( so );
758 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
759 if ( !mesh->_is_nil() )
761 SALOMEDS::GenericAttribute_wrap attr;
762 if ( so->FindAttribute( attr.inout(), "AttributePixMap" ))
764 SALOMEDS::AttributePixMap_wrap pm = attr;
765 CORBA::String_var ico = pm->GetPixMap();
766 if ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 )
768 txt << "The geometry was changed and the mesh needs to be recomputed";
775 CORBA::String_var compType = ComponentDataType();
776 txt << "module '" << compType << "', ID=" << entry;
778 return CORBA::string_dup( txt );
781 //=============================================================================
783 * SMESH_Gen_i::GetStudyContext
787 //=============================================================================
788 StudyContext* SMESH_Gen_i::GetStudyContext()
790 return myStudyContext;
793 //=============================================================================
795 * SMESH_Gen_i::CreateHypothesis
797 * Create hypothesis/algorithm of given type and publish it in the study
799 //=============================================================================
801 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
802 const char* theLibName )
803 throw ( SALOME::SALOME_Exception )
805 Unexpect aCatch(SALOME_SalomeException);
806 // Create hypothesis/algorithm
807 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
809 // Publish hypothesis/algorithm in the study
810 if ( CanPublishInStudy( hyp ) ) {
811 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
812 if ( !aSO->_is_nil() ) {
813 // Update Python script
814 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
815 << theHypName << "', '" << theLibName << "')";
822 //================================================================================
824 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
825 * existing on the given geometry or to size of the geometry.
826 * \param theHypType - hypothesis type name
827 * \param theLibName - plugin library name
828 * \param theMesh - The mesh of interest
829 * \param theGeom - The shape to get parameter values from
830 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
831 * in a study and used to compute the mesh, or a temporary one created just to pass
834 //================================================================================
836 SMESH::SMESH_Hypothesis_ptr
837 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
838 const char* theLibName,
839 SMESH::SMESH_Mesh_ptr theMesh,
840 GEOM::GEOM_Object_ptr theGeom,
841 CORBA::Boolean byMesh)
842 throw ( SALOME::SALOME_Exception )
844 Unexpect aCatch(SALOME_SalomeException);
845 if ( byMesh && CORBA::is_nil( theMesh ) )
846 return SMESH::SMESH_Hypothesis::_nil();
847 if ( byMesh && CORBA::is_nil( theGeom ) )
848 return SMESH::SMESH_Hypothesis::_nil();
850 // -----------------------------------------------
851 // find hypothesis used to mesh theGeom
852 // -----------------------------------------------
854 // get mesh and shape
855 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
856 TopoDS_Shape shape = GeomObjectToShape( theGeom );
857 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
858 return SMESH::SMESH_Hypothesis::_nil();
859 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
861 // create a temporary hypothesis to know its dimension
862 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
863 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
865 return SMESH::SMESH_Hypothesis::_nil();
866 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
869 // look for a hypothesis of theHypType used to mesh the shape
870 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
873 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
874 int nbLocalHyps = aHypList->length();
875 for ( int i = 0; i < nbLocalHyps; i++ ) {
876 CORBA::String_var hypName = aHypList[i]->GetName();
877 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
878 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
880 // check super shapes
881 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
882 while ( nbLocalHyps == 0 && itShape.More() ) {
883 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
884 if ( ! CORBA::is_nil( geomObj )) {
885 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
886 nbLocalHyps = aHypList->length();
887 for ( int i = 0; i < nbLocalHyps; i++ )
888 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
889 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
895 // let the temporary hypothesis find out somehow parameter values by mesh
896 if ( hyp->SetParametersByMesh( mesh, shape ))
897 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
902 diagonal = mesh->GetShapeDiagonalSize();
904 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
905 ::SMESH_Hypothesis::TDefaults dflts;
906 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
907 dflts._nbSegments = myGen.GetDefaultNbSegments();
908 dflts._shape = &shape;
909 // let the temporary hypothesis initialize it's values
910 if ( hyp->SetParametersByDefaults( dflts, mesh ))
911 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
914 return SMESH::SMESH_Hypothesis::_nil();
917 //=============================================================================
919 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
920 * \param [in] theHyp - the hypothesis of interest
921 * \param [out] theMesh - the sole mesh using \a theHyp
922 * \param [out] theShape - the sole geometry \a theHyp is assigned to
923 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
925 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
926 * considered as SAME sub-mesh => result is \c true.
927 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
928 * a shape to which an hyp being edited is assigned.
930 //=============================================================================
932 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
933 SMESH::SMESH_Mesh_out theMesh,
934 GEOM::GEOM_Object_out theShape)
936 if ( CORBA::is_nil( theHyp ))
939 // get Mesh component SO
940 CORBA::String_var compDataType = ComponentDataType();
941 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
942 if ( CORBA::is_nil( comp ))
945 // look for child SO of meshes
946 SMESH::SMESH_Mesh_var foundMesh;
947 TopoDS_Shape foundShape;
949 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
950 for ( ; meshIter->More() && isSole; meshIter->Next() )
952 SALOMEDS::SObject_wrap curSO = meshIter->Value();
953 CORBA::Object_var obj = SObjectToObject( curSO );
954 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
958 // look for a sole shape where theHyp is assigned
959 bool isHypFound = false;
960 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
961 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
962 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
964 const THypList& hyps = s2hypsIt.Value();
965 THypList::const_iterator h = hyps.begin();
966 for ( ; h != hyps.end(); ++h )
967 if ( (*h)->GetID() == theHyp->GetId() )
969 if ( h != hyps.end()) // theHyp found
972 if ( ! foundShape.IsNull() &&
973 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
975 foundShape.Nullify();
979 foundShape = s2hypsIt.Key();
981 } // loop on assigned hyps
983 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
985 if ( !foundMesh->_is_nil() ) // not a sole mesh
987 if ( !foundMesh->HasShapeToMesh() ||
988 !mesh_i ->HasShapeToMesh() )
990 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
994 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
995 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
996 isSole = s1->IsSame( s2 );
999 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1005 ! foundMesh->_is_nil() &&
1006 ! foundShape.IsNull() )
1008 theMesh = foundMesh._retn();
1009 theShape = ShapeToGeomObject( foundShape );
1010 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1015 //=============================================================================
1017 * Sets number of segments per diagonal of boundary box of geometry by which
1018 * default segment length of appropriate 1D hypotheses is defined
1020 //=============================================================================
1022 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1023 throw ( SALOME::SALOME_Exception )
1025 if ( theNbSegments > 0 )
1026 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1028 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1030 //=============================================================================
1032 * \brief Sets default number of segments per edge
1034 //=============================================================================
1035 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1036 throw ( SALOME::SALOME_Exception )
1038 if ( theNbSegments > 0 )
1039 myGen.SetDefaultNbSegments( int(theNbSegments) );
1041 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1044 //=============================================================================
1048 //=============================================================================
1050 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1052 if ( name && value && strlen( value ) > 0 )
1055 if ( strcmp(name, "historical_python_dump") == 0 )
1057 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1058 msgToGUI = "preferences/SMESH/historical_python_dump/";
1059 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1061 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1063 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1064 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1065 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1067 else if ( strcmp(name, "default_grp_color") == 0 )
1071 // color must be presented as a string of following form:
1072 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1073 str = str.substr(1);
1074 for ( size_t i = 0; i < str.length()/2; i++ )
1075 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1076 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1078 else if ( value ) { // rgb color ("255,170,0", for example)
1079 string tempValue( value );
1080 char* colorValue = strtok( &tempValue[0], "," );
1081 while ( colorValue != NULL ) {
1082 int c_value = atoi( colorValue );
1083 if ( c_value >= 0 && c_value <= 255 )
1084 color.push_back( c_value );
1085 colorValue = strtok( NULL, "," );
1088 if ( color.size() == 3 ) { // color must have three valid component
1089 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1090 myDefaultGroupColor = value;
1091 msgToGUI = "preferences/SMESH/default_grp_color/";
1096 // update preferences in case if SetOption() is invoked from python console
1097 if ( !msgToGUI.empty() )
1099 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1100 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1101 if ( !CORBA::is_nil( session ) )
1102 session->emitMessageOneWay(msgToGUI.c_str());
1107 //=============================================================================
1109 Return an option value
1111 //=============================================================================
1113 char* SMESH_Gen_i::GetOption(const char* name)
1117 if ( strcmp(name, "historical_python_dump") == 0 )
1119 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1121 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1123 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1125 if ( strcmp(name, "default_grp_color") == 0 )
1127 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1130 return CORBA::string_dup( "" );
1133 //=============================================================================
1135 * SMESH_Gen_i::CreateMesh
1137 * Create empty mesh on a shape and publish it in the study
1139 //=============================================================================
1141 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1142 throw ( SALOME::SALOME_Exception )
1144 Unexpect aCatch(SALOME_SalomeException);
1145 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1147 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1149 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1150 ASSERT( meshServant );
1151 meshServant->SetShape( theShapeObject );
1153 // publish mesh in the study
1154 if ( CanPublishInStudy( mesh ) ) {
1155 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1156 aStudyBuilder->NewCommand(); // There is a transaction
1157 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1158 aStudyBuilder->CommitCommand();
1159 if ( !aSO->_is_nil() ) {
1160 // Update Python script
1161 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1165 return mesh._retn();
1168 //=============================================================================
1170 * SMESH_Gen_i::CreateEmptyMesh
1174 //=============================================================================
1176 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1177 throw ( SALOME::SALOME_Exception )
1179 Unexpect aCatch(SALOME_SalomeException);
1180 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1182 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1184 // publish mesh in the study
1185 if ( CanPublishInStudy( mesh ) ) {
1186 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1187 aStudyBuilder->NewCommand(); // There is a transaction
1188 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1189 aStudyBuilder->CommitCommand();
1190 if ( !aSO->_is_nil() ) {
1191 // Update Python script
1192 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1196 return mesh._retn();
1201 //================================================================================
1203 * \brief Throws an exception in case if the file can't be read
1205 //================================================================================
1207 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1209 SMESH_File f ( theFileName );
1212 if ( !f.error().empty() )
1213 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1215 THROW_SALOME_CORBA_EXCEPTION
1216 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1217 SALOME::BAD_PARAM );
1222 //=============================================================================
1224 * SMESH_Gen_i::CreateMeshFromUNV
1226 * Create mesh and import data from UNV file
1228 //=============================================================================
1230 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1231 throw ( SALOME::SALOME_Exception )
1233 Unexpect aCatch(SALOME_SalomeException);
1235 checkFileReadable( theFileName );
1237 SMESH::SMESH_Mesh_var aMesh = createMesh();
1239 // publish mesh in the study
1240 if ( CanPublishInStudy( aMesh ) ) {
1241 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1242 aStudyBuilder->NewCommand(); // There is a transaction
1243 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1244 aStudyBuilder->CommitCommand();
1245 if ( !aSO->_is_nil() ) {
1246 // Update Python script
1247 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1251 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1253 aServant->ImportUNVFile( theFileName );
1255 // Dump creation of groups
1256 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1258 aServant->GetImpl().GetMeshDS()->Modified();
1259 return aMesh._retn();
1262 //=============================================================================
1264 * SMESH_Gen_i::CreateMeshFromMED
1266 * Create mesh and import data from MED file
1268 //=============================================================================
1270 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1271 SMESH::DriverMED_ReadStatus& theStatus,
1272 const char* theCommandNameForPython,
1273 const char* theFileNameForPython)
1276 char bname[ _MAX_FNAME ];
1277 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1278 string aFileName = bname;
1280 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1282 // Retrieve mesh names from the file
1283 DriverMED_R_SMESHDS_Mesh myReader;
1284 myReader.SetFile( theFileName );
1285 myReader.SetMeshId( -1 );
1286 Driver_Mesh::Status aStatus;
1287 list<string> aNames = myReader.GetMeshNames(aStatus);
1288 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1289 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1291 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1294 TPythonDump aPythonDump;
1295 aPythonDump << "([";
1297 if (theStatus == SMESH::DRS_OK) {
1298 SALOMEDS::StudyBuilder_var aStudyBuilder;
1299 aStudyBuilder = getStudyServant()->NewBuilder();
1300 aStudyBuilder->NewCommand(); // There is a transaction
1302 aResult->length( aNames.size() );
1305 // Iterate through all meshes and create mesh objects
1306 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1309 if (i > 0) aPythonDump << ", ";
1312 SMESH::SMESH_Mesh_var mesh = createMesh();
1314 // publish mesh in the study
1315 SALOMEDS::SObject_wrap aSO;
1316 if ( CanPublishInStudy( mesh ) )
1317 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1318 // - as names of meshes are stored in MED file, we use them for data publishing
1319 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1320 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1323 if ( !aSO->_is_nil() ) {
1326 aPythonDump << "mesh_" << i;
1329 // Read mesh data (groups are published automatically by ImportMEDFile())
1330 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1331 ASSERT( meshServant );
1332 SMESH::DriverMED_ReadStatus status1 =
1333 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1334 if (status1 > theStatus)
1335 theStatus = status1;
1337 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1338 meshServant->GetImpl().GetMeshDS()->Modified();
1340 if ( !aStudyBuilder->_is_nil() )
1341 aStudyBuilder->CommitCommand();
1344 // Update Python script
1345 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1347 // Dump creation of groups
1348 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1349 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1351 return aResult._retn();
1354 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1355 SMESH::DriverMED_ReadStatus& theStatus)
1356 throw ( SALOME::SALOME_Exception )
1358 Unexpect aCatch(SALOME_SalomeException);
1359 checkFileReadable( theFileName );
1361 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1365 //=============================================================================
1367 * SMESH_Gen_i::CreateMeshFromSAUV
1369 * Create mesh and import data from SAUV file
1371 //=============================================================================
1373 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1374 SMESH::DriverMED_ReadStatus& theStatus)
1375 throw ( SALOME::SALOME_Exception )
1377 Unexpect aCatch(SALOME_SalomeException);
1378 checkFileReadable( theFileName );
1380 std::string sauvfilename(theFileName);
1381 std::string medfilename(theFileName);
1382 medfilename += ".med";
1385 cmd = "%PYTHONBIN% ";
1390 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1392 system(cmd.c_str());
1393 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1395 cmd = "%PYTHONBIN% ";
1400 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1402 system(cmd.c_str());
1406 //=============================================================================
1408 * SMESH_Gen_i::CreateMeshFromSTL
1410 * Create mesh and import data from STL file
1412 //=============================================================================
1414 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1415 throw ( SALOME::SALOME_Exception )
1417 Unexpect aCatch(SALOME_SalomeException);
1418 checkFileReadable( theFileName );
1420 SMESH::SMESH_Mesh_var aMesh = createMesh();
1423 char bname[ _MAX_FNAME ];
1424 _splitpath( theFileName, NULL, NULL, bname, NULL );
1425 string aFileName = bname;
1427 string aFileName = basename( const_cast<char *>(theFileName) );
1429 // publish mesh in the study
1430 if ( CanPublishInStudy( aMesh ) ) {
1431 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1432 aStudyBuilder->NewCommand(); // There is a transaction
1433 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1434 aStudyBuilder->CommitCommand();
1435 if ( !aSO->_is_nil() ) {
1436 // Update Python script
1437 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1441 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1443 aServant->ImportSTLFile( theFileName );
1444 aServant->GetImpl().GetMeshDS()->Modified();
1445 return aMesh._retn();
1448 //================================================================================
1450 * \brief Create meshes and import data from the CGSN file
1452 //================================================================================
1454 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1455 SMESH::DriverMED_ReadStatus& theStatus)
1456 throw ( SALOME::SALOME_Exception )
1458 Unexpect aCatch(SALOME_SalomeException);
1459 checkFileReadable( theFileName );
1461 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1464 // Retrieve nb meshes from the file
1465 DriverCGNS_Read myReader;
1466 myReader.SetFile( theFileName );
1467 Driver_Mesh::Status aStatus;
1468 int nbMeshes = myReader.GetNbMeshes(aStatus);
1469 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1471 aResult->length( nbMeshes );
1473 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1476 TPythonDump aPythonDump;
1477 aPythonDump << "([";
1479 if (theStatus == SMESH::DRS_OK)
1481 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1482 aStudyBuilder->NewCommand(); // There is a transaction
1486 // Iterate through all meshes and create mesh objects
1487 for ( ; i < nbMeshes; ++i )
1490 if (i > 0) aPythonDump << ", ";
1493 SMESH::SMESH_Mesh_var mesh = createMesh();
1494 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1496 // Read mesh data (groups are published automatically by ImportMEDFile())
1497 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1498 ASSERT( meshServant );
1500 SMESH::DriverMED_ReadStatus status1 =
1501 meshServant->ImportCGNSFile( theFileName, i, meshName );
1502 if (status1 > theStatus)
1503 theStatus = status1;
1505 meshServant->GetImpl().GetMeshDS()->Modified();
1506 // publish mesh in the study
1507 SALOMEDS::SObject_wrap aSO;
1508 if ( CanPublishInStudy( mesh ) )
1509 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1512 if ( !aSO->_is_nil() ) {
1516 aPythonDump << "mesh_" << i;
1519 aStudyBuilder->CommitCommand();
1522 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1524 // Dump creation of groups
1525 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1526 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1528 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1531 return aResult._retn();
1534 //================================================================================
1536 * \brief Create a mesh and import data from a GMF file
1538 //================================================================================
1540 SMESH::SMESH_Mesh_ptr
1541 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1542 CORBA::Boolean theMakeRequiredGroups,
1543 SMESH::ComputeError_out theError)
1544 throw ( SALOME::SALOME_Exception )
1546 Unexpect aCatch(SALOME_SalomeException);
1547 checkFileReadable( theFileName );
1549 SMESH::SMESH_Mesh_var aMesh = createMesh();
1551 char bname[ _MAX_FNAME ];
1552 _splitpath( theFileName, NULL, NULL, bname, NULL );
1553 string aFileName = bname;
1555 string aFileName = basename( const_cast<char *>(theFileName) );
1557 // publish mesh in the study
1558 if ( CanPublishInStudy( aMesh ) ) {
1559 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1560 aStudyBuilder->NewCommand(); // There is a transaction
1561 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1562 aStudyBuilder->CommitCommand();
1563 if ( !aSO->_is_nil() ) {
1564 // Update Python script
1565 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1566 << theFileName << "', "
1567 << theMakeRequiredGroups << " )";
1570 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1572 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1573 aServant->GetImpl().GetMeshDS()->Modified();
1574 return aMesh._retn();
1578 //=============================================================================
1580 * SMESH_Gen_i::IsReadyToCompute
1582 * Returns true if mesh contains enough data to be computed
1584 //=============================================================================
1586 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1587 GEOM::GEOM_Object_ptr theShapeObject )
1588 throw ( SALOME::SALOME_Exception )
1590 Unexpect aCatch(SALOME_SalomeException);
1591 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1593 if ( CORBA::is_nil( theShapeObject ) )
1594 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1595 SALOME::BAD_PARAM );
1597 if ( CORBA::is_nil( theMesh ) )
1598 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1599 SALOME::BAD_PARAM );
1603 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1604 ASSERT( meshServant );
1605 if ( meshServant ) {
1606 // get local TopoDS_Shape
1607 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1608 // call implementation
1609 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1610 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1613 catch ( SALOME_Exception& S_ex ) {
1614 INFOS( "catch exception "<< S_ex.what() );
1619 //================================================================================
1621 * \brief Find SObject for an algo
1623 //================================================================================
1625 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1628 SALOMEDS::Study_var aStudy = getStudyServant();
1629 if ( !aStudy->_is_nil() ) {
1630 // find algo in the study
1631 CORBA::String_var compDataType = ComponentDataType();
1632 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1633 if ( !father->_is_nil() ) {
1634 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1635 for ( ; itBig->More(); itBig->Next() ) {
1636 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1637 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1638 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1639 for ( ; algoIt->More(); algoIt->Next() ) {
1640 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1641 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1642 if ( !CORBA::is_nil( algoIOR )) {
1643 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1644 if ( impl && impl->GetImpl() == algo )
1645 return algoSO._retn();
1647 } // loop on algo SO's
1650 } // SMESH component iterator
1654 return SALOMEDS::SObject::_nil();
1657 //================================================================================
1659 * \brief Return errors of mesh computation
1661 //================================================================================
1663 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1664 GEOM::GEOM_Object_ptr theSubObject )
1665 throw ( SALOME::SALOME_Exception )
1667 Unexpect aCatch(SALOME_SalomeException);
1668 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1670 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1671 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1673 if ( CORBA::is_nil( theMesh ) )
1674 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1676 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1678 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1681 if(theMesh->HasShapeToMesh())
1682 shape = GeomObjectToShape( theSubObject );
1684 shape = SMESH_Mesh::PseudoShape();
1686 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1688 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1691 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1692 const bool includeSelf = true, complexShapeFirst = true;
1693 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1695 while ( smIt->more() )
1698 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1700 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1701 if ( error && !error->IsOK() )
1703 if ( !( error->myAlgo ) &&
1704 !( error->myAlgo = sm->GetAlgo() ))
1706 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1707 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1708 errStruct.comment = error->myComment.c_str();
1709 errStruct.subShapeID = sm->GetId();
1710 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1711 if ( !algoSO->_is_nil() ) {
1712 CORBA::String_var algoName = algoSO->GetName();
1713 errStruct.algoName = algoName;
1716 errStruct.algoName = error->myAlgo->GetName();
1718 errStruct.hasBadMesh = error->HasBadElems();
1721 error_array->length( nbErr );
1724 catch ( SALOME_Exception& S_ex ) {
1725 INFOS( "catch exception "<< S_ex.what() );
1728 return error_array._retn();
1731 //================================================================================
1733 * \brief Return mesh elements preventing computation of a subshape
1735 //================================================================================
1737 SMESH::MeshPreviewStruct*
1738 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1739 CORBA::Short theSubShapeID )
1740 throw ( SALOME::SALOME_Exception )
1742 Unexpect aCatch(SALOME_SalomeException);
1743 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1745 if ( CORBA::is_nil( theMesh ) )
1746 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1748 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1751 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1753 // mesh implementation
1754 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1755 // submesh by subshape id
1756 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1759 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1760 if ( error && error->HasBadElems() )
1762 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1763 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1765 // get nodes of elements and count elements
1766 TNode2LocalIDMap mapNode2LocalID;
1767 list< TNodeLocalID > connectivity;
1768 int i, nbElements = 0, nbConnNodes = 0;
1770 const list<const SMDS_MeshElement*>& badElems =
1771 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1772 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1773 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1774 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1776 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1777 while ( nIt->more() )
1778 connectivity.push_back
1779 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1781 // fill node coords and assign local ids to the nodes
1782 int nbNodes = mapNode2LocalID.size();
1783 result->nodesXYZ.length( nbNodes );
1784 TNodeLocalID node2ID = mapNode2LocalID.begin();
1785 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1786 node2ID->second = i;
1787 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1788 result->nodesXYZ[i].x = node->X();
1789 result->nodesXYZ[i].y = node->Y();
1790 result->nodesXYZ[i].z = node->Z();
1792 // fill connectivity
1793 result->elementConnectivities.length( nbConnNodes );
1794 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1795 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1796 result->elementConnectivities[i] = (*connIt)->second;
1798 // fill element types
1799 result->elementTypes.length( nbElements );
1800 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1802 const SMDS_MeshElement* elem = *elemIt;
1803 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1804 result->elementTypes[i].isPoly = elem->IsPoly();
1805 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1811 catch ( SALOME_Exception& S_ex ) {
1812 INFOS( "catch exception "<< S_ex.what() );
1815 return result._retn();
1818 //================================================================================
1820 * \brief Create a group of elements preventing computation of a sub-shape
1822 //================================================================================
1824 SMESH::ListOfGroups*
1825 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1826 CORBA::Short theSubShapeID,
1827 const char* theGroupName )
1828 throw ( SALOME::SALOME_Exception )
1830 Unexpect aCatch(SALOME_SalomeException);
1832 SMESH::ListOfGroups_var groups;
1834 if ( CORBA::is_nil( theMesh ) )
1835 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1838 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1840 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1841 TPythonDump() << groups << " = " << this
1842 << ".MakeGroupsOfBadInputElements( "
1843 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1846 catch ( SALOME_Exception& S_ex ) {
1847 INFOS( "catch exception "<< S_ex.what() );
1849 return groups._retn();
1852 //================================================================================
1854 * \brief Returns errors of hypotheses definition
1855 * \param theMesh - the mesh
1856 * \param theSubObject - the main or sub- shape
1857 * \retval SMESH::algo_error_array* - sequence of errors
1859 //================================================================================
1861 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1862 GEOM::GEOM_Object_ptr theSubObject )
1863 throw ( SALOME::SALOME_Exception )
1865 Unexpect aCatch(SALOME_SalomeException);
1866 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1868 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1869 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1871 if ( CORBA::is_nil( theMesh ) )
1872 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1874 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1876 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1877 ASSERT( meshServant );
1878 if ( meshServant ) {
1879 TopoDS_Shape myLocShape;
1880 if(theMesh->HasShapeToMesh())
1881 myLocShape = GeomObjectToShape( theSubObject );
1883 myLocShape = SMESH_Mesh::PseudoShape();
1885 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1886 list< ::SMESH_Gen::TAlgoStateError > error_list;
1887 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1888 // call ::SMESH_Gen::GetAlgoState()
1889 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1890 error_array->length( error_list.size() );
1892 for ( error = error_list.begin(); error != error_list.end(); ++error )
1894 // fill AlgoStateError structure
1895 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1896 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1897 errStruct.algoDim = error->_algoDim;
1898 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1899 errStruct.algoName = "";
1900 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1901 if ( !algoSO->_is_nil() ) {
1902 CORBA::String_var algoName = algoSO->GetName();
1903 errStruct.algoName = algoName.in();
1908 catch ( SALOME_Exception& S_ex ) {
1909 INFOS( "catch exception "<< S_ex.what() );
1911 return error_array._retn();
1914 //=============================================================================
1916 * SMESH_Gen_i::GetSubShapesId
1918 * Get sub-shapes unique ID's list
1920 //=============================================================================
1923 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1924 const SMESH::object_array& theListOfSubShapeObject )
1925 throw ( SALOME::SALOME_Exception )
1927 Unexpect aCatch(SALOME_SalomeException);
1928 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1930 SMESH::long_array_var shapesId = new SMESH::long_array;
1933 if ( CORBA::is_nil( theMainShapeObject ) )
1934 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1938 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1939 TopTools_IndexedMapOfShape myIndexToShape;
1940 TopExp::MapShapes(myMainShape,myIndexToShape);
1942 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1944 GEOM::GEOM_Object_var aShapeObject
1945 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1946 if ( CORBA::is_nil( aShapeObject ) )
1947 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1948 SALOME::BAD_PARAM );
1950 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1951 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1953 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1954 setId.insert(myIndexToShape.FindIndex(F));
1955 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1957 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1959 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1960 setId.insert(myIndexToShape.FindIndex(E));
1961 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1963 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1965 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1966 setId.insert(myIndexToShape.FindIndex(V));
1967 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1970 shapesId->length(setId.size());
1971 set<int>::iterator iind;
1973 for (iind = setId.begin(); iind != setId.end(); iind++)
1975 if(MYDEBUG) SCRUTE((*iind));
1976 shapesId[i] = (*iind);
1977 if(MYDEBUG) SCRUTE(shapesId[i]);
1981 catch (SALOME_Exception& S_ex)
1983 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1986 return shapesId._retn();
1989 //=============================================================================
1991 * SMESH_Gen_i::Compute
1993 * Compute mesh on a shape
1995 //=============================================================================
1997 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1998 GEOM::GEOM_Object_ptr theShapeObject )
1999 throw ( SALOME::SALOME_Exception )
2002 Unexpect aCatch(SALOME_SalomeException);
2003 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2005 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2006 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2007 SALOME::BAD_PARAM );
2009 if ( CORBA::is_nil( theMesh ) )
2010 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2011 SALOME::BAD_PARAM );
2013 // Update Python script
2014 TPythonDump() << "isDone = " << this << ".Compute( "
2015 << theMesh << ", " << theShapeObject << ")";
2019 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2020 ASSERT( meshServant );
2021 if ( meshServant ) {
2022 meshServant->Load();
2023 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2024 meshServant->CheckGeomModif();
2025 // get local TopoDS_Shape
2026 TopoDS_Shape myLocShape;
2027 if(theMesh->HasShapeToMesh())
2028 myLocShape = GeomObjectToShape( theShapeObject );
2030 myLocShape = SMESH_Mesh::PseudoShape();
2031 // call implementation compute
2032 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2033 myGen.PrepareCompute( myLocMesh, myLocShape );
2034 int how = ::SMESH_Gen::COMPACT_MESH;
2035 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2036 how |= ::SMESH_Gen::SHAPE_ONLY;
2037 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2038 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2039 myLocMesh.GetMeshDS()->Modified();
2040 UpdateIcons( theMesh );
2042 HighLightInvalid( theMesh, /*isInvalid=*/false );
2046 catch ( std::bad_alloc ) {
2047 INFOS( "Compute(): lack of memory" );
2049 catch ( SALOME_Exception& S_ex ) {
2050 INFOS( "Compute(): catch exception "<< S_ex.what() );
2053 INFOS( "Compute(): unknown exception " );
2058 //=============================================================================
2060 * SMESH_Gen_i::CancelCompute
2062 * Cancel Compute mesh on a shape
2064 //=============================================================================
2066 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2067 GEOM::GEOM_Object_ptr theShapeObject )
2069 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2071 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2072 TopoDS_Shape myLocShape;
2073 if(theMesh->HasShapeToMesh())
2074 myLocShape = GeomObjectToShape( theShapeObject );
2076 myLocShape = SMESH_Mesh::PseudoShape();
2077 myGen.CancelCompute( myLocMesh, myLocShape);
2081 //=============================================================================
2083 * SMESH_Gen_i::Precompute
2085 * Compute mesh as preview till indicated dimension on shape
2087 //=============================================================================
2089 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2090 GEOM::GEOM_Object_ptr theShapeObject,
2091 SMESH::Dimension theDimension,
2092 SMESH::long_array& theShapesId)
2093 throw ( SALOME::SALOME_Exception )
2095 Unexpect aCatch(SALOME_SalomeException);
2096 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2098 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2099 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2100 SALOME::BAD_PARAM );
2102 if ( CORBA::is_nil( theMesh ) )
2103 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2104 SALOME::BAD_PARAM );
2106 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2109 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2110 meshServant->Load();
2111 ASSERT( meshServant );
2112 if ( meshServant ) {
2113 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2114 meshServant->CheckGeomModif();
2115 // get local TopoDS_Shape
2116 TopoDS_Shape myLocShape;
2117 if(theMesh->HasShapeToMesh())
2118 myLocShape = GeomObjectToShape( theShapeObject );
2120 return result._retn();;
2122 // call implementation compute
2123 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2125 ::MeshDimension aDim = (MeshDimension)theDimension;
2126 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2128 int nbShapeId = shapeIds.size();
2129 theShapesId.length( nbShapeId );
2130 // iterates on shapes and collect mesh entities into mesh preview
2131 TSetOfInt::const_iterator idIt = shapeIds.begin();
2132 TSetOfInt::const_iterator idEnd = shapeIds.end();
2133 std::map< int, int > mapOfShIdNb;
2134 std::set< SMESH_TLink > setOfEdge;
2135 std::list< SMDSAbs_ElementType > listOfElemType;
2136 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2137 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2138 TNode2LocalIDMap mapNode2LocalID;
2139 list< TNodeLocalID > connectivity;
2140 int i, nbConnNodes = 0;
2141 std::set< const SMESH_subMesh* > setOfVSubMesh;
2142 // iterates on shapes
2143 for ( ; idIt != idEnd; idIt++ )
2145 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2147 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2148 if ( !sm || !sm->IsMeshComputed() )
2151 const TopoDS_Shape& aSh = sm->GetSubShape();
2152 const int shDim = myGen.GetShapeDim( aSh );
2153 if ( shDim < 1 || shDim > theDimension )
2156 mapOfShIdNb[ *idIt ] = 0;
2157 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2159 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2160 if ( !smDS ) continue;
2162 if ( theDimension == SMESH::DIM_2D )
2164 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2165 while ( faceIt->more() )
2167 const SMDS_MeshElement* face = faceIt->next();
2168 int aNbNode = face->NbNodes();
2170 aNbNode /= 2; // do not take into account additional middle nodes
2172 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2173 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2175 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2176 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2178 listOfElemType.push_back( SMDSAbs_Edge );
2179 connectivity.push_back
2180 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2181 connectivity.push_back
2182 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2188 else if ( theDimension == SMESH::DIM_1D )
2190 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2191 while ( nodeIt->more() )
2193 listOfElemType.push_back( SMDSAbs_Node );
2194 connectivity.push_back
2195 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2197 // add corner nodes by first vertex from edge
2198 SMESH_subMeshIteratorPtr edgeSmIt =
2199 sm->getDependsOnIterator(/*includeSelf*/false,
2200 /*complexShapeFirst*/false);
2201 while ( edgeSmIt->more() )
2203 SMESH_subMesh* vertexSM = edgeSmIt->next();
2204 // check that vertex is not already treated
2205 if ( !setOfVSubMesh.insert( vertexSM ).second )
2207 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2210 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2211 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2212 while ( nodeIt->more() )
2214 listOfElemType.push_back( SMDSAbs_Node );
2215 connectivity.push_back
2216 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2222 // fill node coords and assign local ids to the nodes
2223 int nbNodes = mapNode2LocalID.size();
2224 result->nodesXYZ.length( nbNodes );
2225 TNodeLocalID node2ID = mapNode2LocalID.begin();
2226 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2227 node2ID->second = i;
2228 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2229 result->nodesXYZ[i].x = node->X();
2230 result->nodesXYZ[i].y = node->Y();
2231 result->nodesXYZ[i].z = node->Z();
2233 // fill connectivity
2234 result->elementConnectivities.length( nbConnNodes );
2235 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2236 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2237 result->elementConnectivities[i] = (*connIt)->second;
2240 // fill element types
2241 result->elementTypes.length( listOfElemType.size() );
2242 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2243 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2244 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2246 SMDSAbs_ElementType elemType = *typeIt;
2247 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2248 result->elementTypes[i].isPoly = false;
2249 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2252 // correct number of shapes
2253 theShapesId.length( mapOfShIdNb.size() );
2257 catch ( std::bad_alloc ) {
2258 INFOS( "Precompute(): lack of memory" );
2260 catch ( SALOME_Exception& S_ex ) {
2261 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2264 INFOS( "Precompute(): unknown exception " );
2266 return result._retn();
2270 //=============================================================================
2272 * SMESH_Gen_i::Evaluate
2274 * Evaluate mesh on a shape
2276 //=============================================================================
2278 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2279 GEOM::GEOM_Object_ptr theShapeObject)
2280 // SMESH::long_array& theNbElems)
2281 throw ( SALOME::SALOME_Exception )
2283 Unexpect aCatch(SALOME_SalomeException);
2284 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2286 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2287 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2288 SALOME::BAD_PARAM );
2290 if ( CORBA::is_nil( theMesh ) )
2291 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2292 SALOME::BAD_PARAM );
2294 SMESH::long_array_var nbels = new SMESH::long_array;
2295 nbels->length(SMESH::Entity_Last);
2296 int i = SMESH::Entity_Node;
2297 for (; i < SMESH::Entity_Last; i++)
2300 // Update Python script
2301 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2302 << theMesh << ", " << theShapeObject << ")";
2306 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2307 ASSERT( meshServant );
2308 if ( meshServant ) {
2309 meshServant->Load();
2310 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2311 meshServant->CheckGeomModif();
2312 // get local TopoDS_Shape
2313 TopoDS_Shape myLocShape;
2314 if(theMesh->HasShapeToMesh())
2315 myLocShape = GeomObjectToShape( theShapeObject );
2317 myLocShape = SMESH_Mesh::PseudoShape();
2318 // call implementation compute
2319 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2320 MapShapeNbElems aResMap;
2321 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2322 MapShapeNbElemsItr anIt = aResMap.begin();
2323 for(; anIt!=aResMap.end(); anIt++) {
2324 const vector<int>& aVec = (*anIt).second;
2325 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2326 int nbElem = aVec[i];
2327 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2329 SMESH_subMesh* sm = anIt->first;
2330 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2331 const SMESH_Algo* algo = sm->GetAlgo();
2332 if ( (algo && !error.get()) || error->IsOK() )
2333 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2337 nbels[i] += aVec[i];
2341 return nbels._retn();
2344 catch ( std::bad_alloc ) {
2345 INFOS( "Evaluate(): lack of memory" );
2347 catch ( SALOME_Exception& S_ex ) {
2348 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2351 INFOS( "Evaluate(): unknown exception " );
2354 return nbels._retn();
2357 //================================================================================
2359 * \brief Return geometrical object the given element is built on
2360 * \param theMesh - the mesh the element is in
2361 * \param theElementID - the element ID
2362 * \param theGeomName - the name of the result geom object if it is not yet published
2363 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2365 //================================================================================
2367 GEOM::GEOM_Object_ptr
2368 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2369 CORBA::Long theElementID,
2370 const char* theGeomName)
2371 throw ( SALOME::SALOME_Exception )
2373 Unexpect aCatch(SALOME_SalomeException);
2375 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2376 if ( !geom->_is_nil() ) {
2377 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2378 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2380 // try to find the corresponding SObject
2381 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2382 if ( SObj->_is_nil() ) // submesh can be not found even if published
2384 // try to find published submesh
2385 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2386 if ( !geom->IsMainShape() && list->length() == 1 ) {
2387 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2388 SALOMEDS::ChildIterator_wrap it;
2389 if ( !mainSO->_is_nil() ) {
2390 it = getStudyServant()->NewChildIterator( mainSO );
2392 if ( !it->_is_nil() ) {
2393 for ( it->InitEx(true); it->More(); it->Next() ) {
2394 SALOMEDS::SObject_wrap so = it->Value();
2395 CORBA::Object_var obj = SObjectToObject( so );
2396 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2397 if ( !subGeom->_is_nil() ) {
2398 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2399 if ( subList->length() == 1 && list[0] == subList[0] ) {
2409 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2410 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2412 // return only published geometry
2413 if ( !SObj->_is_nil() ) {
2414 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2415 CORBA::Object_var obj = SObjectToObject( SObj );
2416 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2420 return GEOM::GEOM_Object::_nil();
2423 //================================================================================
2425 * \brief Return geometrical object the given element is built on.
2426 * \param theMesh - the mesh the element is in
2427 * \param theElementID - the element ID
2428 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2430 //================================================================================
2432 GEOM::GEOM_Object_ptr
2433 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2434 CORBA::Long theElementID)
2435 throw ( SALOME::SALOME_Exception )
2437 Unexpect aCatch(SALOME_SalomeException);
2438 if ( CORBA::is_nil( theMesh ) )
2439 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2441 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2442 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2444 // get a core mesh DS
2445 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2446 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2448 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2449 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2450 // find the element in mesh
2451 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2452 // find a shape id by the element
2453 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2454 // get a geom object by the shape id
2455 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2456 if ( geom->_is_nil() ) {
2457 // try to find a published sub-shape
2458 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2459 SALOMEDS::ChildIterator_wrap it;
2460 if ( !mainSO->_is_nil() ) {
2461 it = getStudyServant()->NewChildIterator( mainSO );
2463 if ( !it->_is_nil() ) {
2464 for ( it->InitEx(true); it->More(); it->Next() ) {
2465 SALOMEDS::SObject_wrap so = it->Value();
2466 CORBA::Object_var obj = SObjectToObject( so );
2467 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2468 if ( !subGeom->_is_nil() ) {
2469 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2470 if ( subList->length() == 1 && shapeID == subList[0] ) {
2478 if ( geom->_is_nil() ) {
2480 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2481 if ( !op->_is_nil() )
2482 geom = op->GetSubShape( mainShape, shapeID );
2487 if ( !geom->_is_nil() ) {
2488 GeomObjectToShape( geom ); // let geom client remember the found shape
2489 return geom._retn();
2494 return GEOM::GEOM_Object::_nil();
2497 //================================================================================
2499 * SMESH_Gen_i::Concatenate
2501 * Concatenate the given meshes into one mesh
2503 //================================================================================
2505 SMESH::SMESH_Mesh_ptr
2506 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2507 CORBA::Boolean theUniteIdenticalGroups,
2508 CORBA::Boolean theMergeNodesAndElements,
2509 CORBA::Double theMergeTolerance,
2510 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2511 throw ( SALOME::SALOME_Exception )
2513 return ConcatenateCommon(theMeshesArray,
2514 theUniteIdenticalGroups,
2515 theMergeNodesAndElements,
2521 //================================================================================
2523 * SMESH_Gen_i::ConcatenateWithGroups
2525 * Concatenate the given meshes into one mesh
2526 * Create the groups of all elements from initial meshes
2528 //================================================================================
2530 SMESH::SMESH_Mesh_ptr
2531 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2532 CORBA::Boolean theUniteIdenticalGroups,
2533 CORBA::Boolean theMergeNodesAndElements,
2534 CORBA::Double theMergeTolerance,
2535 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2536 throw ( SALOME::SALOME_Exception )
2538 return ConcatenateCommon(theMeshesArray,
2539 theUniteIdenticalGroups,
2540 theMergeNodesAndElements,
2546 //================================================================================
2548 * SMESH_Gen_i::ConcatenateCommon
2550 * Concatenate the given meshes into one mesh
2552 //================================================================================
2554 SMESH::SMESH_Mesh_ptr
2555 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2556 CORBA::Boolean theUniteIdenticalGroups,
2557 CORBA::Boolean theMergeNodesAndElements,
2558 CORBA::Double theMergeTolerance,
2559 CORBA::Boolean theCommonGroups,
2560 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2561 throw ( SALOME::SALOME_Exception )
2563 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2564 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2566 // create mesh if theMeshToAppendTo not provided
2567 SMESH::SMESH_Mesh_var newMesh;
2568 if ( CORBA::is_nil( theMeshToAppendTo ))
2569 newMesh = CreateEmptyMesh();
2571 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2572 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2573 if ( !newImpl ) return newMesh._retn();
2576 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2577 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2579 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2580 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2581 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2582 TGroupsMap groupsMap;
2583 TListOfNewGroups listOfNewGroups;
2585 if ( !CORBA::is_nil( theMeshToAppendTo ))
2587 // fill groupsMap with existing groups
2588 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2589 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2591 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2592 if ( !group->_is_nil() )
2594 CORBA::String_var name = group->GetName();
2595 SMESH::ElementType type = group->GetType();
2596 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2601 ::SMESH_MeshEditor newEditor( &locMesh );
2602 ::SMESH_MeshEditor::ElemFeatures elemType;
2604 // loop on sub-meshes
2605 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2607 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2608 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2609 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2610 if ( !initImpl ) continue;
2611 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2615 // assure that IDs increment by one during iteration
2616 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2617 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2618 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2619 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2621 initMeshDS->Modified();
2622 initMeshDS->CompactMesh();
2625 // remember nb of elements before filling in
2626 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2630 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2631 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2632 while ( elemIt->more() )
2634 SMESH_NodeXYZ node = elemIt->next();
2635 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2640 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2641 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2643 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2644 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2645 while ( elemIt->more() )
2647 const SMDS_MeshElement* elem = elemIt->next();
2648 elemType.myNodes.resize( elem->NbNodes() );
2650 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2651 for ( int k = 0; itNodes->more(); k++)
2653 const SMDS_MeshNode* node = itNodes->next();
2654 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2657 // creates a corresponding element on existent nodes in new mesh
2658 newElems[ elem->GetID() ] =
2659 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2661 newEditor.ClearLastCreated(); // forget the history
2664 // create groups of just added elements
2665 SMESH::SMESH_Group_var newGroup;
2666 SMESH::ElementType groupType;
2667 if ( theCommonGroups )
2670 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2671 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2672 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2673 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2676 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2678 for( groupType = SMESH::NODE;
2679 groupType < SMESH::NB_ELEMENT_TYPES;
2680 groupType = (SMESH::ElementType)( groupType + 1 ))
2682 if ( curState[ groupType ] <= prevState[ groupType ])
2683 continue; // no elements of groupType added from the i-th mesh
2685 // make a group name
2686 std::string groupName = "Gr";
2687 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2689 CORBA::String_var name = meshSO->GetName();
2693 groupName += typeNames[ groupType ];
2695 // make and fill a group
2696 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2697 std::vector< const SMDS_MeshElement* > & elemVec =
2698 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2699 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2701 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2703 for ( size_t j = 0; j < elemVec.size(); ++j )
2705 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2706 grpDS->Add( elemVec[j] );
2710 listOfNewGroups.clear();
2711 listOfNewGroups.push_back( newGroup );
2712 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2717 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2721 SMESH::SMESH_GroupBase_ptr group;
2722 CORBA::String_var groupName;
2723 SMESH::long_array_var newIDs = new SMESH::long_array();
2725 // loop on groups of a source mesh
2726 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2727 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2729 group = listOfGroups[iG];
2730 groupType = group->GetType();
2731 groupName = group->GetName();
2732 std::string name = groupName.in();
2734 // convert a list of IDs
2735 newIDs->length( group->Size() );
2736 std::vector< const SMDS_MeshElement* > & elemVec =
2737 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2738 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2740 while ( itGrElems->more() )
2742 const SMDS_MeshElement* elem = itGrElems->next();
2743 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2745 newIDs[ nbElems++ ] = newElem->GetID();
2747 newIDs->length( nbElems );
2749 // check that a current group name and type don't have identical ones in final mesh
2750 listOfNewGroups.clear();
2751 TNameAndType nameAndType( name, groupType );
2752 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2753 if ( anIter == groupsMap.end() )
2755 // add a new group in the mesh
2756 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2757 newGroup->Add( newIDs );
2759 listOfNewGroups.push_back( newGroup );
2760 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2762 else if ( theUniteIdenticalGroups )
2764 // unite identical groups
2765 TListOfNewGroups& aNewGroups = anIter->second;
2766 aNewGroups.front()->Add( newIDs );
2770 // rename identical groups
2771 newGroup = newImpl->CreateGroup( groupType, groupName );
2772 newGroup->Add( newIDs );
2774 TListOfNewGroups& newGroups = anIter->second;
2775 std::string newGroupName;
2776 if ( newGroups.size() == 1 )
2778 newGroupName = name + "_1";
2779 newGroups.front()->SetName( newGroupName.c_str() );
2781 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2782 newGroup->SetName( newGroupName.c_str() );
2783 newGroups.push_back( newGroup );
2786 } // if an IDSource is a mesh
2789 if ( theMergeNodesAndElements ) // merge nodes
2791 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2792 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2793 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2794 /*SeparateCornersAndMedium=*/ false );
2795 newEditor.MergeNodes( groupsOfNodes );
2797 newEditor.MergeEqualElements();
2800 // Update Python script
2801 pythonDump << newMesh << " = " << this
2802 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2803 << theMeshesArray << ", "
2804 << theUniteIdenticalGroups << ", "
2805 << theMergeNodesAndElements << ", "
2806 << TVar( theMergeTolerance ) << ", "
2807 << theMeshToAppendTo << " )";
2809 pPythonDump.reset(); // enable python dump from GetGroups()
2811 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2812 if ( !newMesh->_is_nil() )
2814 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2817 // IPAL21468 Change icon of compound because it need not be computed.
2818 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2819 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2821 newMeshDS->Modified();
2823 return newMesh._retn();
2826 //================================================================================
2828 * \brief Create a mesh by copying a part of another mesh
2829 * \param meshPart - a part of mesh to copy
2830 * \param toCopyGroups - to create in the new mesh groups
2831 * the copied elements belongs to
2832 * \param toKeepIDs - to preserve IDs of the copied elements or not
2833 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2835 //================================================================================
2837 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2838 const char* meshName,
2839 CORBA::Boolean toCopyGroups,
2840 CORBA::Boolean toKeepIDs)
2841 throw ( SALOME::SALOME_Exception )
2843 Unexpect aCatch(SALOME_SalomeException);
2845 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2846 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2848 // 1. Get source mesh
2850 if ( CORBA::is_nil( meshPart ))
2851 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2853 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2854 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2856 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2858 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2860 // 2. Make a new mesh
2862 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2863 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2865 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2866 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2867 if ( !meshSO->_is_nil() )
2869 SetName( meshSO, meshName, "Mesh" );
2870 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2872 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2873 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2874 ::SMESH_MeshEditor::ElemFeatures elemType;
2876 // 3. Get elements to copy
2878 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2879 TIDSortedElemSet srcElems;
2880 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2881 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2884 srcElemIt = srcMeshDS->elementsIterator();
2885 srcNodeIt = srcMeshDS->nodesIterator();
2889 SMESH::long_array_var ids = meshPart->GetIDs();
2890 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2892 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2893 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2894 srcElems.insert( elem );
2898 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2899 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2900 srcElems.insert( elem );
2902 if ( srcElems.empty() )
2903 return newMesh._retn();
2905 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2906 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2911 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2912 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2913 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2915 const SMDS_MeshNode *nSrc, *nTgt;
2916 vector< const SMDS_MeshNode* > nodes;
2917 while ( srcElemIt->more() )
2919 const SMDS_MeshElement * elem = srcElemIt->next();
2921 nodes.resize( elem->NbNodes());
2922 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2924 for ( iN = 0; nIt->more(); ++iN )
2926 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2927 nTgt = newMeshDS->FindNode( nSrc->GetID());
2929 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2934 for ( iN = 0; nIt->more(); ++iN )
2936 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2937 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2939 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2940 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2944 if ( elem->GetType() != SMDSAbs_Node )
2946 elemType.Init( elem, /*basicOnly=*/false );
2947 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2949 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2950 if ( toCopyGroups && !toKeepIDs )
2951 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2953 } // while ( srcElemIt->more() )
2955 // 4(b). Copy free nodes
2957 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2959 while ( srcNodeIt->more() )
2961 nSrc = srcNodeIt->next();
2962 if ( nSrc->NbInverseElements() == 0 )
2965 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2967 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2974 int nbNewGroups = 0;
2977 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2978 while ( gIt->more() )
2980 SMESH_Group* group = gIt->next();
2981 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2983 // Check group type. We copy nodal groups containing nodes of copied element
2984 SMDSAbs_ElementType groupType = groupDS->GetType();
2985 if ( groupType != SMDSAbs_Node &&
2986 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2987 continue; // group type differs from types of meshPart
2989 // Find copied elements in the group
2990 vector< const SMDS_MeshElement* > groupElems;
2991 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2994 const SMDS_MeshElement* foundElem;
2995 if ( groupType == SMDSAbs_Node )
2997 while ( eIt->more() )
2998 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
2999 groupElems.push_back( foundElem );
3003 while ( eIt->more() )
3004 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3005 groupElems.push_back( foundElem );
3010 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3011 if ( e2eMap.empty() ) continue;
3012 int minID = e2eMap.begin()->first->GetID();
3013 int maxID = e2eMap.rbegin()->first->GetID();
3014 TE2EMap::iterator e2e;
3015 while ( eIt->more() && groupElems.size() < e2eMap.size())
3017 const SMDS_MeshElement* e = eIt->next();
3018 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3019 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3020 groupElems.push_back( e2e->second );
3024 if ( !groupElems.empty() )
3026 SMESH::SMESH_Group_var newGroupObj =
3027 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3028 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3030 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3031 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3032 for ( unsigned i = 0; i < groupElems.size(); ++i )
3033 smdsGroup.Add( groupElems[i] );
3041 newMeshDS->Modified();
3043 *pyDump << newMesh << " = " << this
3044 << ".CopyMesh( " << meshPart << ", "
3045 << "'" << meshName << "', "
3046 << toCopyGroups << ", "
3047 << toKeepIDs << ")";
3049 pyDumpDeleter.reset(); // allow dump in GetGroups()
3051 if ( nbNewGroups > 0 ) // dump created groups
3052 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3054 return newMesh._retn();
3058 namespace // utils for CopyMeshWithGeom()
3060 typedef std::map< std::string, std::string > TStr2StrMap;
3061 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3062 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3063 typedef std::map< std::string, int > TName2IndexMap;
3065 //================================================================================
3067 * \brief Return a new sub-shape corresponding to an old one
3069 //================================================================================
3073 SMESH_Mesh_i* mySrcMesh_i;
3074 SMESH_Mesh_i* myNewMesh_i;
3075 SMESH_Gen_i* myGen_i;
3079 TStr2StrMap myOld2NewEntryMap; // map of study entries
3081 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3082 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3083 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3086 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3088 // not directly relating to shape search
3089 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3091 //================================================================================
3093 * \brief Constructor
3095 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3096 SMESH_Mesh_i* newMesh_i,
3097 SMESH_Gen_i* smeshGen_i )
3098 : mySrcMesh_i( srcMesh_i ),
3099 myNewMesh_i( newMesh_i ),
3100 myGen_i ( smeshGen_i ),
3101 myToPublish( smeshGen_i->IsEnablePublish() ),
3102 myGIPMapDone( false )
3104 // retrieve from the study shape mapping made thanks to
3105 // "Set presentation parameters and sub-shapes from arguments" option
3107 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3108 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3109 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3110 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3111 if ( newSO->_is_nil() )
3113 myToPublish = false;
3116 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3118 CORBA::String_var oldEntry = oldSO->GetID();
3119 CORBA::String_var newEntry = newSO->GetID();
3120 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3121 std::string( newEntry.in() )));
3122 std::string newMainEntry = newEntry.in();
3124 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3125 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3126 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3127 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3128 /*groupsOnly=*/false );
3129 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3131 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3132 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3133 bool refFound = false;
3134 for ( ; anIter->More(); anIter->Next() )
3136 SALOMEDS::SObject_wrap so = anIter->Value();
3137 if ( so->ReferencedObject( oldSO.inout() ))
3139 oldEntry = oldSO->GetID();
3140 newEntry = newSO->GetID();
3141 if (( refFound = ( newMainEntry != oldEntry.in() )))
3142 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3143 std::string( newEntry.in() )));
3148 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3149 if ( father->_is_equivalent( mainShapeNew ))
3151 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3152 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3153 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3154 CORBA::String_var name = newSO->GetName();
3156 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3162 //================================================================================
3164 * \brief Find a new sub-shape corresponding to an old one
3166 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3169 return GEOM::GEOM_Object::_duplicate( oldShape );
3171 GEOM::GEOM_Object_var newShape;
3173 if ( CORBA::is_nil( oldShape ))
3174 return newShape._retn();
3176 if ( !isChildOfOld( oldShape ))
3177 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3179 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3180 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3182 // try to find by entry or name
3185 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3186 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3187 if ( o2nID != myOld2NewEntryMap.end() )
3189 newShape = getShapeByEntry( o2nID->second );
3191 if ( newShape->_is_nil() )
3193 CORBA::String_var name = oldShape->GetName();
3194 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3195 if ( n2ind != myName2SubshapeIndex.end() )
3197 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3198 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3199 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3200 if ( oldIndices->length() == 0 ||
3201 newIndices->length() == 0 ||
3202 getShapeType( myNewMesh_i, newIndices[0] ) !=
3203 getShapeType( mySrcMesh_i, oldIndices[0] ))
3204 newShape = GEOM::GEOM_Object::_nil();
3209 if ( newShape->_is_nil() )
3211 // try to construct a new sub-shape using myGIPMap
3213 std::vector< int > newIndices;
3214 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3215 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3217 findNewIDs( oldIndices[i], newIndices );
3219 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3222 newShape = getInPlace( oldShape );
3224 if ( !newIndices.empty() && newShape->_is_nil() )
3226 // search for a sub-shape with same ids
3227 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3228 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3229 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3230 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3232 if ( newShape->_is_nil() )
3235 // create a new shape
3236 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3238 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3240 GEOM::GEOM_IGroupOperations_ptr grOp = geomGen->GetIGroupOperations();
3241 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3243 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3244 newIndicesList->length( newIndices.size() );
3245 for ( size_t i = 0; i < newIndices.size(); ++i )
3246 newIndicesList[ i ] = newIndices[ i ];
3247 grOp->UnionIDs( newShape, newIndicesList );
3251 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3252 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3261 if ( !newShape->_is_nil() && myToPublish )
3263 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3264 if ( !newEntry.in() || !newEntry.in()[0] )
3266 CORBA::String_var name = oldShape->GetName();
3267 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3268 newEntry = newShape->GetStudyEntry();
3269 oldEntry = oldShape->GetStudyEntry();
3270 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3271 std::string( newEntry.in() )));
3275 return newShape._retn();
3278 //================================================================================
3280 * \brief Return a study entry of a new shape by study entry of the old one
3282 std::string FindNew( const std::string & oldEntry )
3287 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3288 if ( o2nID != myOld2NewEntryMap.end() )
3289 return o2nID->second;
3291 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3292 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3295 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3296 if ( newShape->_is_nil() )
3297 return std::string();
3299 CORBA::String_var newEntry = newShape->GetStudyEntry();
3300 return newEntry.in();
3303 //================================================================================
3305 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3306 * Return zero if not found or there are more than one new ID
3308 int FindNew( int oldID )
3317 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3319 if ( myGIPMap[ oldID ].length() == 1 )
3321 newID = myGIPMap[ oldID ][ 0 ];
3323 else if ( myGIPMap[ oldID ].length() > 1 &&
3324 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3326 // select a meshed VERTEX
3327 SMESH_subMesh* newSM;
3328 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3329 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3330 ( !newSM->IsEmpty() ))
3331 newID = myGIPMap[ oldID ][ i ];
3337 //================================================================================
3339 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3340 * Return zero if the old shape is not kept as is in the new shape.
3342 int FindNewNotChanged( SMESH_subMesh* oldSM )
3345 return oldSM->GetId();
3347 int newID = FindNew( oldSM->GetId() );
3351 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3355 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3356 // one new sub-shape of the same type.
3358 if ( oldSM->DependsOn().size() !=
3359 newSM->DependsOn().size() )
3362 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3363 while ( srcSMIt->more() )
3365 oldSM = srcSMIt->next();
3366 int newSubID = FindNew( oldSM->GetId() );
3367 if ( getShapeType( myNewMesh_i, newSubID ) !=
3368 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3374 //================================================================================
3376 * \brief Return shape by study entry
3378 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3380 GEOM::GEOM_Object_var shape;
3381 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3382 if ( !so->_is_nil() )
3384 CORBA::Object_var obj = so->GetObject();
3385 shape = GEOM::GEOM_Object::_narrow( obj );
3387 return shape._retn();
3390 //================================================================================
3392 * \brief Fill myGIPMap by calling GetInPlaceMap()
3396 if ( !myGIPMapDone )
3398 myGIPMapDone = true;
3400 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3401 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3402 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3403 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3406 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3410 myGIPMap = new GEOM::ListOfListOfLong();
3415 //================================================================================
3417 * \brief Get new sub-shape by calling GetInPlace()
3419 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3421 GEOM::GEOM_Object_var newShape;
3423 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3424 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3425 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3428 newShape = op->GetInPlace( mainShapeNew, oldShape );
3433 return newShape._retn();
3436 //================================================================================
3438 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3439 * number of found IDs
3441 int findNewIDs( int oldID, std::vector< int >& newIDs )
3443 size_t prevNbIDs = newIDs.size();
3445 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3447 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3448 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3450 return newIDs.size() - prevNbIDs;
3453 //================================================================================
3455 * \brief Check if an object relates to the old shape
3457 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3459 if ( CORBA::is_nil( oldShape ))
3461 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3462 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3463 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3464 mainShapeOld1->_is_equivalent( oldShape ));
3467 //================================================================================
3469 * \brief Return shape type by shape ID
3471 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3473 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3474 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3475 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3478 //================================================================================
3480 * \brief Store a source sub-shape for which a counterpart not found and
3481 * a smesh object invalid due to that
3483 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3484 SALOMEDS::SObject_wrap smeshSO )
3486 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3487 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3489 CORBA::String_var smeshEntry = smeshSO->GetID();
3490 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3494 //================================================================================
3496 * \brief Store a source sub-shape for which a counterpart not found and
3497 * a smesh object invalid due to that
3499 void AddInvalid( std::string geomEntry,
3500 SALOMEDS::SObject_wrap smeshSO )
3502 if ( !geomEntry.empty() )
3504 CORBA::String_var smeshEntry = smeshSO->GetID();
3505 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
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( int oldGeomID,
3515 SALOMEDS::SObject_wrap smeshSO )
3517 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3518 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3521 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3522 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3524 SMESH_Comment geomName( typeName[ shapeType ]);
3525 geomName << " #" << oldGeomID;
3527 CORBA::String_var smeshEntry = smeshSO->GetID();
3528 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3531 //================================================================================
3533 * \brief Return entries of a source sub-shape for which a counterpart not found and
3534 * of smesh objects invalid due to that
3536 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3537 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3540 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3541 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3543 nbSO += 1 + entry2entrySet->second.size();
3545 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3546 theInvalidEntries->length ( nbSO );
3547 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3549 entry2entrySet = myInvalidMap.begin();
3550 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3552 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3554 std::set< std::string > & entrySet = entry2entrySet->second;
3555 std::set< std::string >::iterator entry = entrySet.begin();
3556 for ( ; entry != entrySet.end(); ++entry )
3558 theInvalidEntries[ iEntry++ ] = entry->c_str();
3560 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3561 if ( !so->_is_nil() )
3562 theInvalidMeshSObjects[ iSO++ ] = so;
3567 }; // struct ShapeMapper
3569 //================================================================================
3571 * \brief Append an item to a CORBA sequence
3573 template < class CORBA_seq, class ITEM >
3574 void append( CORBA_seq& seq, ITEM item )
3576 if ( !CORBA::is_nil( item ))
3578 seq->length( 1 + seq->length() );
3579 seq[ seq->length() - 1 ] = item;
3582 } // namespace // utils for CopyMeshWithGeom()
3584 //================================================================================
3586 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3587 * \param [in] sourceMesh - a mesh to copy
3588 * \param [in] newGeometry - a new geometry
3589 * \param [in] toCopyGroups - to create groups in the new mesh
3590 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3591 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3592 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3593 * \param [out] newMesh - return a new mesh
3594 * \param [out] newGroups - return new groups
3595 * \param [out] newSubmeshes - return new sub-meshes
3596 * \param [out] newHypotheses - return new algorithms and hypotheses
3597 * \param [out] invalidEntries - return study entries of objects whose
3598 * counterparts are not found in the newGeometry, followed by entries
3599 * of mesh sub-objects that are invalid because they depend on a not found
3600 * preceding sub-shape
3601 * \return CORBA::Boolean - is a success
3603 //================================================================================
3605 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3606 GEOM::GEOM_Object_ptr theNewGeometry,
3607 const char* theMeshName,
3608 CORBA::Boolean theToCopyGroups,
3609 CORBA::Boolean theToReuseHypotheses,
3610 CORBA::Boolean theToCopyElements,
3611 SMESH::SMESH_Mesh_out theNewMesh,
3612 SMESH::ListOfGroups_out theNewGroups,
3613 SMESH::submesh_array_out theNewSubmeshes,
3614 SMESH::ListOfHypothesis_out theNewHypotheses,
3615 SMESH::string_array_out theInvalidEntries)
3616 throw ( SALOME::SALOME_Exception )
3618 if ( CORBA::is_nil( theSourceMesh ) ||
3619 CORBA::is_nil( theNewGeometry ))
3620 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3622 if ( !theSourceMesh->HasShapeToMesh() )
3623 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3628 TPythonDump pyDump; // prevent dump from CreateMesh()
3630 theNewMesh = CreateMesh( theNewGeometry );
3631 theNewGroups = new SMESH::ListOfGroups();
3632 theNewSubmeshes = new SMESH::submesh_array();
3633 theNewHypotheses = new SMESH::ListOfHypothesis();
3634 theInvalidEntries = new SMESH::string_array();
3636 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3638 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3639 GEOM::GEOM_Object_var geom, newGeom;
3640 SALOMEDS::SObject_wrap so;
3642 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3643 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3646 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3648 // treat hypotheses of mesh and sub-meshes
3649 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3650 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3652 bool isSubMesh = ( iSM < smList->length() );
3655 // create a new sub-mesh
3656 SMESH::SMESH_subMesh_var newSM;
3657 geom = smList[iSM]->GetSubShape();
3658 so = ObjectToSObject( smList[iSM] );
3659 CORBA::String_var name;
3660 if ( !so->_is_nil() )
3661 name = so->GetName();
3662 newGeom = shapeMapper.FindNew( geom );
3663 if ( newGeom->_is_nil() )
3665 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3666 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3671 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3673 append( theNewSubmeshes, newSM );
3675 if ( newGeom->_is_nil() )
3676 continue; // don't assign hypotheses
3680 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3682 so = ObjectToSObject( theNewMesh );
3683 SetName( so, theMeshName, "Mesh" );
3686 // assign hypotheses
3687 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3688 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3690 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3691 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3693 // get geometry hyp depends on
3694 std::vector< std::string > entryArray;
3695 std::vector< int > subIDArray;
3696 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3698 if ( !theToReuseHypotheses || dependsOnGeom )
3700 // create a new hypothesis
3701 CORBA::String_var type = hyp->GetName();
3702 CORBA::String_var lib = hyp->GetLibName();
3703 CORBA::String_var data = hyp_i->SaveTo();
3706 hyp = CreateHypothesis( type, lib );
3707 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3708 hyp_i->LoadFrom( data.in() );
3709 append( theNewHypotheses, hyp );
3713 // update geometry hyp depends on
3714 if ( dependsOnGeom )
3716 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3718 if ( !entryArray[ iGeo ].empty() )
3720 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3721 if ( newEntry.empty() )
3724 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3725 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3727 entryArray[ iGeo ] = newEntry;
3730 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3732 if ( subIDArray[ iGeo ] > 0 )
3734 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3738 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3739 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3741 subIDArray[ iGeo ] = newID;
3744 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3748 CORBA::String_var errorText;
3749 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3750 if ( errorText.in()[0] )
3753 } // loop on hypotheses
3754 } // loop on sub-meshes and mesh
3757 // copy mesh elements, keeping IDs
3758 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3759 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3761 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3762 ::SMESH_MeshEditor::ElemFeatures elemData;
3764 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3765 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3766 /*vertexLast=*/false);
3767 while ( srcSMIt->more() )
3769 SMESH_subMesh* srcSM = srcSMIt->next();
3770 if ( srcSM->IsEmpty() )
3771 continue; // not yet computed
3772 int newID = shapeMapper.FindNewNotChanged( srcSM );
3776 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3777 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3778 while ( nIt->more() )
3780 SMESH_NodeXYZ node( nIt->next() );
3781 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3783 const SMDS_PositionPtr pos = node->GetPosition();
3784 const double* uv = pos->GetParameters();
3785 switch ( pos->GetTypeOfPosition() )
3787 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3788 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3789 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3790 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3794 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3795 while( eIt->more() )
3797 const SMDS_MeshElement* e = eIt->next();
3798 elemData.Init( e, /*basicOnly=*/false );
3799 elemData.SetID( e->GetID() );
3800 elemData.myNodes.resize( e->NbNodes() );
3801 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3803 for ( iN = 0; nnIt->more(); ++iN )
3805 const SMDS_MeshNode* srcNode = nnIt->next();
3806 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3807 if ( !elemData.myNodes[ iN ])
3810 if ( iN == elemData.myNodes.size() )
3811 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3812 newMeshDS->SetMeshElementOnShape( newElem, newID );
3814 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3815 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3818 newMeshDS->Modified();
3824 TStr2StrMap old2newGroupMap;
3826 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3828 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3829 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3830 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3832 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3833 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3834 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3836 CORBA::String_var name = groups[ i ]->GetName();
3837 SMESH::ElementType elemType = groups[ i ]->GetType();
3839 SMESH::SMESH_GroupBase_var newGroup;
3841 if ( !stdlGroup->_is_nil() )
3843 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3845 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3846 const bool isElem = ( elemType != SMESH::NODE );
3847 CORBA::ULong iE = 0;
3848 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3849 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3851 if ( iE < elemIDs->length() )
3853 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3854 stdlGroup->Add( elemIDs );
3855 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3859 else if ( !geomGroup->_is_nil() )
3861 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3862 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3863 if ( newGeom->_is_nil() )
3865 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3866 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3871 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3874 else if ( !fltrGroup->_is_nil() )
3876 // replace geometry in a filter
3877 SMESH::Filter_var filter = fltrGroup->GetFilter();
3878 SMESH::Filter::Criteria_var criteria;
3879 filter->GetCriteria( criteria.out() );
3881 bool isMissingGroup = false;
3882 std::vector< std::string > badEntries;
3884 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3886 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3887 switch ( criteria[ iCr ].Type )
3889 case SMESH::FT_BelongToMeshGroup:
3891 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3892 btgg->SetGroupID( thresholdID );
3893 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3894 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3895 if ( refGroupSO->_is_nil() )
3897 CORBA::String_var refID = refGroupSO->GetID();
3898 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3899 if ( o2nID == old2newGroupMap.end() )
3901 isMissingGroup = true; // corresponding new group not yet created
3904 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3906 if ( o2nID->second.empty() ) // new referred group is invalid
3907 badEntries.push_back( refID.in() );
3910 case SMESH::FT_BelongToGeom:
3911 case SMESH::FT_BelongToPlane:
3912 case SMESH::FT_BelongToCylinder:
3913 case SMESH::FT_BelongToGenSurface:
3914 case SMESH::FT_LyingOnGeom:
3916 std::string newID = shapeMapper.FindNew( thresholdID );
3917 criteria[ iCr ].ThresholdID = newID.c_str();
3918 if ( newID.empty() )
3919 badEntries.push_back( thresholdID );
3922 case SMESH::FT_ConnectedElements:
3924 if ( thresholdID && thresholdID[0] )
3926 std::string newID = shapeMapper.FindNew( thresholdID );
3927 criteria[ iCr ].ThresholdID = newID.c_str();
3928 if ( newID.empty() )
3929 badEntries.push_back( thresholdID );
3935 } // loop on criteria
3937 if ( isMissingGroup && i < nbGroups )
3939 // to treat the group again
3940 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3944 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3945 newFilter->SetCriteria( criteria );
3947 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3948 newFilter->UnRegister();
3950 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3951 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3952 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3954 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3956 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3959 if ( !badEntries.empty() )
3962 } // treat a group on filter
3964 append( theNewGroups, newGroup );
3966 // fill old2newGroupMap
3967 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3968 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3969 if ( !srcSO->_is_nil() )
3971 CORBA::String_var srcID, newID("");
3972 srcID = srcSO->GetID();
3973 if ( !newSO->_is_nil() )
3974 newID = newSO->GetID();
3975 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3976 std::string( newID.in() )));
3979 if ( newGroup->_is_nil() )
3984 newMeshDS->CompactMesh();
3987 if ( !theMeshName || !theMeshName[0] )
3989 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
3990 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
3991 CORBA::String_var oldName = soOld->GetName();
3992 SetName( soNew, oldName.in(), "Mesh" );
3994 // mark invalid objects
3995 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3997 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
3998 highLightInvalid( invalidSObjects[i].in(), true );
4001 << theNewMesh << ", "
4002 << theNewGroups << ", "
4003 << *theNewSubmeshes.ptr() << ", "
4004 << *theNewHypotheses.ptr() << ", "
4005 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4006 << theSourceMesh << ", "
4007 << theNewGeometry << ", "
4008 << "'" << theMeshName << "', "
4009 << theToCopyGroups << ", "
4010 << theToReuseHypotheses << ", "
4011 << theToCopyElements << " )";
4013 SMESH_CATCH( SMESH::throwCorbaException );
4018 //================================================================================
4020 * \brief Get version of MED format being used.
4022 //================================================================================
4024 char* SMESH_Gen_i::GetMEDFileVersion()
4026 MED::TInt majeur, mineur, release;
4027 majeur = mineur = release = 0;
4028 MED::GetVersionRelease(majeur, mineur, release);
4029 std::ostringstream version;
4030 version << majeur << "." << mineur << "." << release;
4031 return CORBA::string_dup( version.str().c_str() );
4034 //================================================================================
4036 * SMESH_Gen_i::GetMEDVersion
4038 * Get MED version of the file by its name
4040 //================================================================================
4041 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4043 std::string version = MED::GetMEDVersion( theFileName );
4044 return CORBA::string_dup( version.c_str() );
4047 //================================================================================
4049 * SMESH_Gen_i::CheckCompatibility
4051 * Check compatibility of file with MED format being used, read only.
4053 //================================================================================
4054 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4056 return MED::CheckCompatibility( theFileName );
4059 //================================================================================
4061 * SMESH_Gen_i::CheckWriteCompatibility
4063 * Check compatibility of file with MED format being used, for append on write.
4065 //================================================================================
4066 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4068 return MED::CheckCompatibility( theFileName, true );
4071 //================================================================================
4073 * SMESH_Gen_i::GetMeshNames
4075 * Get names of meshes defined in file with the specified name
4077 //================================================================================
4078 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4080 //MESSAGE("GetMeshNames " << theFileName);
4081 SMESH::string_array_var aResult = new SMESH::string_array();
4082 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4084 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4085 //MESSAGE("---" << aNbMeshes);
4087 aResult->length( aNbMeshes );
4088 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4089 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4090 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4093 return aResult._retn();
4096 //=============================================================================
4100 * Save SMESH module's data
4102 //=============================================================================
4103 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4108 Kernel_Utils::Localizer loc;
4110 if (!myStudyContext)
4113 // Store study contents as a set of python commands
4116 SALOMEDS::Study_var aStudy = getStudyServant();
4118 // Declare a byte stream
4119 SALOMEDS::TMPFile_var aStreamFile;
4121 // Obtain a temporary dir
4122 TCollection_AsciiString tmpDir =
4123 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4125 // Create a sequence of files processed
4126 SALOMEDS_Tool::ListOfFiles aFileSeq;
4127 aFileSeq.reserve( NUM_TMP_FILES );
4129 TCollection_AsciiString aStudyName( "" );
4131 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4133 // Set names of temporary files
4134 TCollection_AsciiString filename =
4135 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4136 TCollection_AsciiString meshfile =
4137 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4138 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4139 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4140 filename = tmpDir + filename;
4141 meshfile = tmpDir + meshfile;
4144 HDFdataset* aDataset;
4145 HDFgroup* aTopGroup;
4147 HDFgroup* aSubGroup;
4148 HDFgroup* aSubSubGroup;
4149 hdf_size aSize[ 1 ];
4152 //Remove the files if they exist: BugID: 11225
4153 #ifndef WIN32 /* unix functionality */
4154 TCollection_AsciiString cmd("rm -f \"");
4156 TCollection_AsciiString cmd("del /F \"");
4166 system(cmd.ToCString());
4168 // MED writer to be used by storage process
4169 DriverMED_W_SMESHDS_Mesh myWriter;
4170 myWriter.SetFile( meshfile.ToCString() );
4173 // SetStoreName() to groups before storing hypotheses to let them refer to
4174 // groups using "store name", which is "Group <group_persistent_id>"
4176 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4177 for ( ; itBig->More(); itBig->Next() ) {
4178 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4179 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4180 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4181 if ( !CORBA::is_nil( anObject ) ) {
4182 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4183 if ( !myMesh->_is_nil() ) {
4184 myMesh->Load(); // load from study file if not yet done
4185 TPythonDump pd; // not to dump GetGroups()
4186 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4187 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4189 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4192 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4193 int anId = myStudyContext->findId( string( objStr.in() ) );
4195 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4196 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4197 aGrpBaseDS->SetStoreName( grpName );
4207 // ---> create HDF file
4208 aFile = new HDFfile( (char*) filename.ToCString() );
4209 aFile->CreateOnDisk();
4211 // --> iterator for top-level objects
4212 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4213 for ( ; itBig->More(); itBig->Next() ) {
4214 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4216 // --> hypotheses root branch (only one for the study)
4217 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4218 // create hypotheses root HDF group
4219 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4220 aTopGroup->CreateOnDisk();
4222 // iterator for all hypotheses
4223 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4224 for ( ; it->More(); it->Next() ) {
4225 SALOMEDS::SObject_wrap mySObject = it->Value();
4226 CORBA::Object_var anObject = SObjectToObject( mySObject );
4227 if ( !CORBA::is_nil( anObject ) ) {
4228 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4229 if ( !myHyp->_is_nil() ) {
4230 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4232 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4233 std::string hypname = hn.in();
4234 std::string libname = ln.in();
4236 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4237 // WIN32 and ".so" for X-system) must be deleted
4238 int libname_len = libname.length();
4240 if( libname_len > 4 )
4241 libname.resize( libname_len - 4 );
4243 // PAL17753 (Regression: missing hypothesis in restored study)
4244 // "lib" also should be removed from the beginning
4245 //if( libname_len > 3 )
4246 //libname.resize( libname_len - 3 );
4247 if( libname_len > 6 )
4248 libname = libname.substr( 3, libname_len - 3 - 3 );
4250 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4251 CORBA::String_var hypdata = myImpl->SaveTo();
4252 int id = myStudyContext->findId( string( objStr.in() ));
4254 // for each hypothesis create HDF group basing on its id
4255 char hypGrpName[30];
4256 sprintf( hypGrpName, "Hypothesis %d", id );
4257 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4258 aGroup->CreateOnDisk();
4259 // --> type name of hypothesis
4260 aSize[ 0 ] = hypname.length() + 1;
4261 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4262 aDataset->CreateOnDisk();
4263 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4264 aDataset->CloseOnDisk();
4265 // --> server plugin library name of hypothesis
4266 aSize[ 0 ] = libname.length() + 1;
4267 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4268 aDataset->CreateOnDisk();
4269 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4270 aDataset->CloseOnDisk();
4271 // --> persistent data of hypothesis
4272 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4273 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4274 aDataset->CreateOnDisk();
4275 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4276 aDataset->CloseOnDisk();
4277 // close hypothesis HDF group
4278 aGroup->CloseOnDisk();
4283 // close hypotheses root HDF group
4284 aTopGroup->CloseOnDisk();
4286 // --> algorithms root branch (only one for the study)
4287 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4288 // create algorithms root HDF group
4289 aTopGroup = new HDFgroup( "Algorithms", aFile );
4290 aTopGroup->CreateOnDisk();
4292 // iterator for all algorithms
4293 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4294 for ( ; it->More(); it->Next() ) {
4295 SALOMEDS::SObject_wrap mySObject = it->Value();
4296 CORBA::Object_var anObject = SObjectToObject( mySObject );
4297 if ( !CORBA::is_nil( anObject ) ) {
4298 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4299 if ( !myHyp->_is_nil() ) {
4300 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4302 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4303 std::string hypname = hn.in();
4304 std::string libname = ln.in();
4306 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4307 // WIN32 and ".so" for X-system) must be deleted
4308 int libname_len = libname.length();
4310 if( libname_len > 4 )
4311 libname.resize( libname_len - 4 );
4313 // PAL17753 (Regression: missing hypothesis in restored study)
4314 // "lib" also should be removed from the beginning
4315 //if( libname_len > 3 )
4316 //libname.resize( libname_len - 3 );
4317 if( libname_len > 6 )
4318 libname = libname.substr( 3, libname_len - 3 - 3 );
4320 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4321 CORBA::String_var hypdata = myImpl->SaveTo();
4322 int id = myStudyContext->findId( string( objStr.in() ) );
4324 // for each algorithm create HDF group basing on its id
4325 char hypGrpName[30];
4326 sprintf( hypGrpName, "Algorithm %d", id );
4327 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4328 aGroup->CreateOnDisk();
4329 // --> type name of algorithm
4330 aSize[0] = hypname.length() + 1;
4331 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4332 aDataset->CreateOnDisk();
4333 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4334 aDataset->CloseOnDisk();
4335 // --> server plugin library name of hypothesis
4336 aSize[0] = libname.length() + 1;
4337 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4338 aDataset->CreateOnDisk();
4339 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4340 aDataset->CloseOnDisk();
4341 // --> persistent data of algorithm
4342 aSize[0] = strlen( hypdata.in() ) + 1;
4343 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4344 aDataset->CreateOnDisk();
4345 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4346 aDataset->CloseOnDisk();
4347 // close algorithm HDF group
4348 aGroup->CloseOnDisk();
4353 // close algorithms root HDF group
4354 aTopGroup->CloseOnDisk();
4356 // --> mesh objects roots branches
4357 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4358 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4359 if ( !CORBA::is_nil( anObject ) ) {
4360 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4361 if ( !myMesh->_is_nil() ) {
4362 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4364 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4365 int id = myStudyContext->findId( string( objStr.in() ) );
4366 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4367 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4368 bool hasShape = myLocMesh.HasShapeToMesh();
4370 // for each mesh open the HDF group basing on its id
4371 char meshGrpName[ 30 ];
4372 sprintf( meshGrpName, "Mesh %d", id );
4373 aTopGroup = new HDFgroup( meshGrpName, aFile );
4374 aTopGroup->CreateOnDisk();
4376 // --> put dataset to hdf file which is a flag that mesh has data
4377 string strHasData = "0";
4378 // check if the mesh is not empty
4379 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4380 // write mesh data to med file
4381 myWriter.SetMesh( mySMESHDSMesh );
4382 myWriter.SetMeshId( id );
4385 aSize[ 0 ] = strHasData.length() + 1;
4386 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4387 aDataset->CreateOnDisk();
4388 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4389 aDataset->CloseOnDisk();
4392 // for each mesh open the HDF group basing on its auto color parameter
4393 char meshAutoColorName[ 30 ];
4394 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4396 anAutoColor[0] = myImpl->GetAutoColor();
4398 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4399 aDataset->CreateOnDisk();
4400 aDataset->WriteOnDisk( anAutoColor );
4401 aDataset->CloseOnDisk();
4403 // issue 0020693. Store _isModified flag
4404 int isModified = myLocMesh.GetIsModified();
4406 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4407 aDataset->CreateOnDisk();
4408 aDataset->WriteOnDisk( &isModified );
4409 aDataset->CloseOnDisk();
4411 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4412 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4414 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4415 aDataset->CreateOnDisk();
4416 aDataset->WriteOnDisk( &meshPersistentId );
4417 aDataset->CloseOnDisk();
4419 // Store SMESH_Mesh_i::_mainShapeTick
4420 int shapeTick = myImpl->MainShapeTick();
4422 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4423 aDataset->CreateOnDisk();
4424 aDataset->WriteOnDisk( &shapeTick );
4425 aDataset->CloseOnDisk();
4427 // write reference on a shape if exists
4428 SALOMEDS::SObject_wrap myRef;
4429 bool shapeRefFound = false;
4430 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4432 SALOMEDS::SObject_wrap myShape;
4433 bool ok = myRef->ReferencedObject( myShape.inout() );
4435 CORBA::Object_var shapeObj = myShape->GetObject();
4436 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4437 CORBA::String_var myRefOnObject = myShape->GetID();
4438 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4439 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4440 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4441 aDataset->CreateOnDisk();
4442 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4443 aDataset->CloseOnDisk();
4449 std::string info = myImpl->FileInfoToString();
4450 if ( !info.empty() )
4452 aSize[ 0 ] = info.size();
4453 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4454 aDataset->CreateOnDisk();
4455 aDataset->WriteOnDisk( (char*) info.data() );
4456 aDataset->CloseOnDisk();
4459 // write applied hypotheses if exist
4460 SALOMEDS::SObject_wrap myHypBranch;
4461 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4462 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4463 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4465 if ( found && (shapeRefFound || !hasShape) ) {
4466 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4467 aGroup->CreateOnDisk();
4469 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4471 for ( ; it->More(); it->Next() ) {
4472 SALOMEDS::SObject_wrap mySObject = it->Value();
4473 SALOMEDS::SObject_wrap myRefOnHyp;
4474 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4476 // san - it is impossible to recover applied hypotheses
4477 // using their entries within Load() method,
4478 // for there are no AttributeIORs in the study when Load() is working.
4479 // Hence, it is better to store persistent IDs of hypotheses as references to them
4481 //string myRefOnObject = myRefOnHyp->GetID();
4482 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4483 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4484 int id = myStudyContext->findId( string( objStr.in() ) );
4485 //if ( myRefOnObject.length() > 0 ) {
4486 //aSize[ 0 ] = myRefOnObject.length() + 1;
4487 char hypName[ 30 ], hypId[ 30 ];
4488 sprintf( hypName, "Hyp %d", ++hypNb );
4489 sprintf( hypId, "%d", id );
4490 aSize[ 0 ] = strlen( hypId ) + 1;
4491 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4492 aDataset->CreateOnDisk();
4493 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4494 aDataset->WriteOnDisk( hypId );
4495 aDataset->CloseOnDisk();
4499 aGroup->CloseOnDisk();
4502 // write applied algorithms if exist
4503 SALOMEDS::SObject_wrap myAlgoBranch;
4504 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4505 myAlgoBranch.inout() );
4506 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4507 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4509 if ( found && (shapeRefFound || !hasShape)) {
4510 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4511 aGroup->CreateOnDisk();
4513 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4515 for ( ; it->More(); it->Next() ) {
4516 SALOMEDS::SObject_wrap mySObject = it->Value();
4517 SALOMEDS::SObject_wrap myRefOnAlgo;
4518 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4520 // san - it is impossible to recover applied algorithms
4521 // using their entries within Load() method,
4522 // for there are no AttributeIORs in the study when Load() is working.
4523 // Hence, it is better to store persistent IDs of algorithms as references to them
4525 //string myRefOnObject = myRefOnAlgo->GetID();
4526 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4527 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4528 int id = myStudyContext->findId( string( objStr.in() ) );
4529 //if ( myRefOnObject.length() > 0 ) {
4530 //aSize[ 0 ] = myRefOnObject.length() + 1;
4531 char algoName[ 30 ], algoId[ 30 ];
4532 sprintf( algoName, "Algo %d", ++algoNb );
4533 sprintf( algoId, "%d", id );
4534 aSize[ 0 ] = strlen( algoId ) + 1;
4535 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4536 aDataset->CreateOnDisk();
4537 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4538 aDataset->WriteOnDisk( algoId );
4539 aDataset->CloseOnDisk();
4543 aGroup->CloseOnDisk();
4546 // --> submesh objects sub-branches
4548 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4549 SALOMEDS::SObject_wrap mySubmeshBranch;
4550 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4552 if ( found ) // check if there is shape reference in submeshes
4554 bool hasShapeRef = false;
4555 SALOMEDS::ChildIterator_wrap itSM =
4556 aStudy->NewChildIterator( mySubmeshBranch );
4557 for ( ; itSM->More(); itSM->Next() ) {
4558 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4559 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4560 mySubRef->ReferencedObject( myShape.inout() );
4561 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4564 { // remove one submesh
4565 if ( shapeRefFound )
4566 { // unassign hypothesis
4567 SMESH::SMESH_subMesh_var mySubMesh =
4568 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4569 if ( !mySubMesh->_is_nil() ) {
4570 int shapeID = mySubMesh->GetId();
4571 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4572 const list<const SMESHDS_Hypothesis*>& hypList =
4573 mySMESHDSMesh->GetHypothesis( S );
4574 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4575 while ( hyp != hypList.end() ) {
4576 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4577 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4581 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4583 } // loop on submeshes of a type
4584 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4585 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4588 } // end check if there is shape reference in submeshes
4590 char name_meshgroup[ 30 ];
4591 if ( i == GetSubMeshOnVertexTag() )
4592 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4593 else if ( i == GetSubMeshOnEdgeTag() )
4594 strcpy( name_meshgroup, "SubMeshes On Edge" );
4595 else if ( i == GetSubMeshOnWireTag() )
4596 strcpy( name_meshgroup, "SubMeshes On Wire" );
4597 else if ( i == GetSubMeshOnFaceTag() )
4598 strcpy( name_meshgroup, "SubMeshes On Face" );
4599 else if ( i == GetSubMeshOnShellTag() )
4600 strcpy( name_meshgroup, "SubMeshes On Shell" );
4601 else if ( i == GetSubMeshOnSolidTag() )
4602 strcpy( name_meshgroup, "SubMeshes On Solid" );
4603 else if ( i == GetSubMeshOnCompoundTag() )
4604 strcpy( name_meshgroup, "SubMeshes On Compound" );
4606 // for each type of submeshes create container HDF group
4607 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4608 aGroup->CreateOnDisk();
4610 // iterator for all submeshes of given type
4611 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4612 for ( ; itSM->More(); itSM->Next() ) {
4613 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4614 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4615 if ( !CORBA::is_nil( anSubObject ))
4617 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4618 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4619 int subid = myStudyContext->findId( string( objStr.in() ) );
4621 // for each mesh open the HDF group basing on its id
4622 char submeshGrpName[ 30 ];
4623 sprintf( submeshGrpName, "SubMesh %d", subid );
4624 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4625 aSubGroup->CreateOnDisk();
4627 // write reference on a shape, already checked if it exists
4628 SALOMEDS::SObject_wrap mySubRef, myShape;
4629 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4630 mySubRef->ReferencedObject( myShape.inout() );
4631 string myRefOnObject = myShape->GetID();
4632 if ( myRefOnObject.length() > 0 ) {
4633 aSize[ 0 ] = myRefOnObject.length() + 1;
4634 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4635 aDataset->CreateOnDisk();
4636 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4637 aDataset->CloseOnDisk();
4640 // write applied hypotheses if exist
4641 SALOMEDS::SObject_wrap mySubHypBranch;
4642 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4643 mySubHypBranch.inout() );
4645 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4646 aSubSubGroup->CreateOnDisk();
4648 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4650 for ( ; it->More(); it->Next() ) {
4651 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4652 SALOMEDS::SObject_wrap myRefOnHyp;
4653 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4655 //string myRefOnObject = myRefOnHyp->GetID();
4656 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4657 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4658 int id = myStudyContext->findId( string( objStr.in() ) );
4659 //if ( myRefOnObject.length() > 0 ) {
4660 //aSize[ 0 ] = myRefOnObject.length() + 1;
4661 char hypName[ 30 ], hypId[ 30 ];
4662 sprintf( hypName, "Hyp %d", ++hypNb );
4663 sprintf( hypId, "%d", id );
4664 aSize[ 0 ] = strlen( hypId ) + 1;
4665 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4666 aDataset->CreateOnDisk();
4667 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4668 aDataset->WriteOnDisk( hypId );
4669 aDataset->CloseOnDisk();
4673 aSubSubGroup->CloseOnDisk();
4676 // write applied algorithms if exist
4677 SALOMEDS::SObject_wrap mySubAlgoBranch;
4678 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4679 mySubAlgoBranch.inout() );
4681 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4682 aSubSubGroup->CreateOnDisk();
4684 SALOMEDS::ChildIterator_wrap it =
4685 aStudy->NewChildIterator( mySubAlgoBranch );
4687 for ( ; it->More(); it->Next() ) {
4688 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4689 SALOMEDS::SObject_wrap myRefOnAlgo;
4690 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4692 //string myRefOnObject = myRefOnAlgo->GetID();
4693 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4694 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4695 int id = myStudyContext->findId( string( objStr.in() ) );
4696 //if ( myRefOnObject.length() > 0 ) {
4697 //aSize[ 0 ] = myRefOnObject.length() + 1;
4698 char algoName[ 30 ], algoId[ 30 ];
4699 sprintf( algoName, "Algo %d", ++algoNb );
4700 sprintf( algoId, "%d", id );
4701 aSize[ 0 ] = strlen( algoId ) + 1;
4702 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4703 aDataset->CreateOnDisk();
4704 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4705 aDataset->WriteOnDisk( algoId );
4706 aDataset->CloseOnDisk();
4710 aSubSubGroup->CloseOnDisk();
4712 // close submesh HDF group
4713 aSubGroup->CloseOnDisk();
4716 // close container of submeshes by type HDF group
4717 aGroup->CloseOnDisk();
4720 // All sub-meshes will be stored in MED file
4721 // .. will NOT (PAL 12992)
4722 //if ( shapeRefFound )
4723 //myWriter.AddAllSubMeshes();
4725 // store submesh order if any
4726 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4727 if ( theOrderIds.size() ) {
4728 char order_list[ 30 ];
4729 strcpy( order_list, "Mesh Order" );
4730 // count number of submesh ids
4732 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4733 for ( ; idIt != theOrderIds.end(); idIt++ )
4734 nbIDs += (*idIt).size();
4735 // number of values = number of IDs +
4736 // number of lists (for separators) - 1
4737 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4738 idIt = theOrderIds.begin();
4739 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4740 const TListOfInt& idList = *idIt;
4741 if (idIt != theOrderIds.begin()) // not first list
4742 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4743 // dump submesh ids from current list
4744 TListOfInt::const_iterator id_smId = idList.begin();
4745 for( ; id_smId != idList.end(); id_smId++ )
4746 smIDs[ i++ ] = *id_smId;
4749 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4751 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4752 aDataset->CreateOnDisk();
4753 aDataset->WriteOnDisk( smIDs );
4754 aDataset->CloseOnDisk();
4759 // groups root sub-branch
4760 SALOMEDS::SObject_wrap myGroupsBranch;
4761 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4762 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4764 char name_group[ 30 ];
4765 if ( i == GetNodeGroupsTag() )
4766 strcpy( name_group, "Groups of Nodes" );
4767 else if ( i == GetEdgeGroupsTag() )
4768 strcpy( name_group, "Groups of Edges" );
4769 else if ( i == GetFaceGroupsTag() )
4770 strcpy( name_group, "Groups of Faces" );
4771 else if ( i == GetVolumeGroupsTag() )
4772 strcpy( name_group, "Groups of Volumes" );
4773 else if ( i == Get0DElementsGroupsTag() )
4774 strcpy( name_group, "Groups of 0D Elements" );
4775 else if ( i == GetBallElementsGroupsTag() )
4776 strcpy( name_group, "Groups of Balls" );
4778 aGroup = new HDFgroup( name_group, aTopGroup );
4779 aGroup->CreateOnDisk();
4781 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4782 for ( ; it->More(); it->Next() ) {
4783 SALOMEDS::SObject_wrap mySObject = it->Value();
4784 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4785 if ( !CORBA::is_nil( aSubObject ) ) {
4786 SMESH_GroupBase_i* myGroupImpl =
4787 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4790 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4794 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4795 int anId = myStudyContext->findId( string( objStr.in() ) );
4797 // For each group, create a dataset named "Group <group_persistent_id>"
4798 // and store the group's user name into it
4799 const char* grpName = aGrpBaseDS->GetStoreName();
4800 CORBA::String_var aUserName = myGroupImpl->GetName();
4801 aSize[ 0 ] = strlen( aUserName ) + 1;
4803 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4804 aDataset->CreateOnDisk();
4805 aDataset->WriteOnDisk( aUserName );
4806 aDataset->CloseOnDisk();
4809 // For each group, create a dataset named "Group <group_persistent_id> Color"
4810 // and store the group's color into it
4811 char grpColorName[ 30 ];
4812 sprintf( grpColorName, "ColorGroup %d", anId );
4813 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4815 anRGB[ 0 ] = aColor.R;
4816 anRGB[ 1 ] = aColor.G;
4817 anRGB[ 2 ] = aColor.B;
4819 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4820 aDataset->CreateOnDisk();
4821 aDataset->WriteOnDisk( anRGB );
4822 aDataset->CloseOnDisk();
4824 // Pass SMESHDS_Group to MED writer
4825 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4827 myWriter.AddGroup( aGrpDS );
4829 // write reference on a shape if exists
4830 SMESHDS_GroupOnGeom* aGeomGrp =
4831 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4833 SALOMEDS::SObject_wrap mySubRef, myShape;
4834 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4835 mySubRef->ReferencedObject( myShape.inout() ) &&
4836 !CORBA::is_nil( myShape->GetObject() ))
4838 CORBA::String_var myRefOnObject = myShape->GetID();
4839 if ( myRefOnObject.in()[0] ) {
4840 char aRefName[ 30 ];
4841 sprintf( aRefName, "Ref on shape %d", anId);
4842 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4843 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4844 aDataset->CreateOnDisk();
4845 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4846 aDataset->CloseOnDisk();
4849 else // shape ref is invalid:
4851 // save a group on geometry as ordinary group
4852 myWriter.AddGroup( aGeomGrp );
4855 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4856 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4858 std::string str = aFilterGrp_i->FilterToString();
4859 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4860 aSize[ 0 ] = str.length() + 1;
4861 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4862 aDataset->CreateOnDisk();
4863 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4864 aDataset->CloseOnDisk();
4868 aGroup->CloseOnDisk();
4872 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4874 // Flush current mesh information into MED file
4877 // save info on nb of elements
4878 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4880 // maybe a shape was deleted in the study
4881 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4882 TopoDS_Shape nullShape;
4883 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4886 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4891 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4892 aGroup->CreateOnDisk();
4894 // each element belongs to one or none submesh,
4895 // so for each node/element, we store a submesh ID
4897 // Store submesh IDs
4898 for ( int isNode = 0; isNode < 2; ++isNode )
4900 SMDS_ElemIteratorPtr eIt =
4901 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4902 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4905 std::vector<int> smIDs; smIDs.reserve( nbElems );
4906 while ( eIt->more() )
4907 if ( const SMDS_MeshElement* e = eIt->next())
4908 smIDs.push_back( e->getshapeId() );
4910 aSize[ 0 ] = nbElems;
4911 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4912 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4913 aDataset->CreateOnDisk();
4914 aDataset->WriteOnDisk( & smIDs[0] );
4915 aDataset->CloseOnDisk();
4918 aGroup->CloseOnDisk();
4920 // Store node positions on sub-shapes (SMDS_Position):
4921 // ----------------------------------------------------
4923 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4924 aGroup->CreateOnDisk();
4926 // in aGroup, create 5 datasets to contain:
4927 // "Nodes on Edges" - ID of node on edge
4928 // "Edge positions" - U parameter on node on edge
4929 // "Nodes on Faces" - ID of node on face
4930 // "Face U positions" - U parameter of node on face
4931 // "Face V positions" - V parameter of node on face
4933 // Find out nb of nodes on edges and faces
4934 // Collect corresponding sub-meshes
4935 int nbEdgeNodes = 0, nbFaceNodes = 0;
4936 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4937 // loop on SMESHDS_SubMesh'es
4938 while ( smIt->more() )
4940 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4941 if ( aSubMesh->IsComplexSubmesh() )
4942 continue; // submesh containing other submeshs
4943 int nbNodes = aSubMesh->NbNodes();
4944 if ( nbNodes == 0 ) continue;
4946 int aShapeID = aSubMesh->GetID();
4947 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4949 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4950 // write only SMDS_FacePosition and SMDS_EdgePosition
4951 switch ( aShapeType ) {
4953 nbFaceNodes += nbNodes;
4954 aFaceSM.push_back( aSubMesh );
4957 nbEdgeNodes += nbNodes;
4958 aEdgeSM.push_back( aSubMesh );
4964 // Treat positions on edges or faces
4965 for ( int onFace = 0; onFace < 2; onFace++ )
4967 // Create arrays to store in datasets
4968 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4969 if (!nbNodes) continue;
4970 int* aNodeIDs = new int [ nbNodes ];
4971 double* aUPos = new double [ nbNodes ];
4972 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4975 // loop on sub-meshes
4976 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4977 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4978 for ( ; itSM != pListSM->end(); itSM++ )
4980 SMESHDS_SubMesh* aSubMesh = (*itSM);
4982 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4983 // loop on nodes in aSubMesh
4984 while ( itNode->more() )
4987 const SMDS_MeshNode* node = itNode->next();
4988 aNodeIDs [ iNode ] = node->GetID();
4991 const SMDS_PositionPtr pos = node->GetPosition();
4992 if ( onFace ) { // on FACE
4993 SMDS_FacePositionPtr fPos = pos;
4995 aUPos[ iNode ] = fPos->GetUParameter();
4996 aVPos[ iNode ] = fPos->GetVParameter();
5003 SMDS_EdgePositionPtr ePos = pos;
5005 aUPos[ iNode ] = ePos->GetUParameter();
5011 } // loop on nodes in aSubMesh
5012 } // loop on sub-meshes
5017 aSize[ 0 ] = nbNodes;
5019 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5020 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5021 aDataset->CreateOnDisk();
5022 aDataset->WriteOnDisk( aNodeIDs );
5023 aDataset->CloseOnDisk();
5026 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5027 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5028 aDataset->CreateOnDisk();
5029 aDataset->WriteOnDisk( aUPos );
5030 aDataset->CloseOnDisk();
5033 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5034 aDataset->CreateOnDisk();
5035 aDataset->WriteOnDisk( aVPos );
5036 aDataset->CloseOnDisk();
5041 if ( aVPos ) delete [] aVPos;
5043 } // treat positions on edges or faces
5045 // close "Node Positions" group
5046 aGroup->CloseOnDisk();
5048 } // if ( there are submeshes in SMESHDS_Mesh )
5051 // close mesh HDF group
5052 aTopGroup->CloseOnDisk();
5060 aFile->CloseOnDisk();
5063 // Convert temporary files to stream
5064 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5066 // Remove temporary files and directory
5068 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5070 return aStreamFile._retn();
5073 //=============================================================================
5075 * SMESH_Gen_i::SaveASCII
5077 * Save SMESH module's data in ASCII format
5079 //=============================================================================
5081 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5083 bool isMultiFile ) {
5084 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5085 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5086 return aStreamFile._retn();
5088 //after usual saving needs to encipher binary to text string
5089 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5090 int size = aStreamFile.in().length();
5091 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5092 for ( int i = 0; i < size; i++ )
5093 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5095 buffer[size * 3] = '\0';
5097 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5099 return anAsciiStreamFile._retn();
5102 //=============================================================================
5106 * Load SMESH module's data
5108 //=============================================================================
5110 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5111 const SALOMEDS::TMPFile& theStream,
5115 UpdateStudy(); // load geom data
5116 Kernel_Utils::Localizer loc;
5118 SALOMEDS::Study_var aStudy = getStudyServant();
5120 // Get temporary files location
5121 TCollection_AsciiString tmpDir =
5122 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5124 // Convert the stream into sequence of files to process
5125 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5128 TCollection_AsciiString aStudyName( "" );
5129 if ( isMultiFile ) {
5130 CORBA::WString_var url = aStudy->URL();
5131 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5133 // Set names of temporary files
5134 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5135 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5139 HDFdataset* aDataset;
5140 HDFgroup* aTopGroup;
5142 HDFgroup* aSubGroup;
5143 HDFgroup* aSubSubGroup;
5146 // ---> open HDF file
5147 aFile = new HDFfile( (char*) filename.ToCString() );
5149 aFile->OpenOnDisk( HDF_RDONLY );
5151 catch ( HDFexception ) {
5152 INFOS( "Load(): " << filename << " not found!" );
5156 TPythonDump pd; // prevent dump during loading
5158 // DriverMED_R_SMESHDS_Mesh myReader;
5159 // myReader.SetFile( meshfile.ToCString() );
5161 // For PAL13473 ("Repetitive mesh") implementation.
5162 // New dependencies between SMESH objects are established:
5163 // now hypotheses can refer to meshes, shapes and other hypotheses.
5164 // To keep data consistent, the following order of data restoration
5166 // 1. Create hypotheses
5167 // 2. Create all meshes
5168 // 3. Load hypotheses' data
5171 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5172 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5173 list< SMESH::Filter_var > filters;
5175 // get total number of top-level groups
5176 int aNbGroups = aFile->nInternalObjects();
5177 if ( aNbGroups > 0 ) {
5178 // --> in first turn we should read&create hypotheses
5179 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5180 // open hypotheses root HDF group
5181 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5182 aTopGroup->OpenOnDisk();
5184 // get number of hypotheses
5185 int aNbObjects = aTopGroup->nInternalObjects();
5186 for ( int j = 0; j < aNbObjects; j++ ) {
5187 // try to identify hypothesis
5188 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5189 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5191 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5192 // open hypothesis group
5193 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5194 aGroup->OpenOnDisk();
5196 // --> get hypothesis id
5197 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5202 // get number of datasets
5203 int aNbSubObjects = aGroup->nInternalObjects();
5204 for ( int k = 0; k < aNbSubObjects; k++ ) {
5206 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5207 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5208 // --> get hypothesis name
5209 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5210 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5211 aDataset->OpenOnDisk();
5212 size = aDataset->GetSize();
5213 char* hypname_str = new char[ size ];
5214 aDataset->ReadFromDisk( hypname_str );
5215 hypname = string( hypname_str );
5216 delete [] hypname_str;
5217 aDataset->CloseOnDisk();
5219 // --> get hypothesis plugin library name
5220 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5221 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5222 aDataset->OpenOnDisk();
5223 size = aDataset->GetSize();
5224 char* libname_str = new char[ size ];
5225 aDataset->ReadFromDisk( libname_str );
5226 if(MYDEBUG) SCRUTE( libname_str );
5227 libname = string( libname_str );
5228 delete [] libname_str;
5229 aDataset->CloseOnDisk();
5231 // --> get hypothesis data
5232 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5233 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5234 aDataset->OpenOnDisk();
5235 size = aDataset->GetSize();
5236 char* hypdata_str = new char[ size ];
5237 aDataset->ReadFromDisk( hypdata_str );
5238 hypdata = string( hypdata_str );
5239 delete [] hypdata_str;
5240 aDataset->CloseOnDisk();
5243 // close hypothesis HDF group
5244 aGroup->CloseOnDisk();
5246 // --> restore hypothesis from data
5247 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5248 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5249 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5250 SMESH::SMESH_Hypothesis_var myHyp;
5252 try { // protect persistence mechanism against exceptions
5253 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5256 INFOS( "Exception during hypothesis creation" );
5259 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5261 // myImpl->LoadFrom( hypdata.c_str() );
5262 hypDataList.push_back( make_pair( myImpl, hypdata ));
5263 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5264 int newId = myStudyContext->findId( iorString.in() );
5265 myStudyContext->mapOldToNew( id, newId );
5268 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5272 // close hypotheses root HDF group
5273 aTopGroup->CloseOnDisk();
5277 // --> then we should read&create algorithms
5278 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5279 // open algorithms root HDF group
5280 aTopGroup = new HDFgroup( "Algorithms", aFile );
5281 aTopGroup->OpenOnDisk();
5283 // get number of algorithms
5284 int aNbObjects = aTopGroup->nInternalObjects();
5285 for ( int j = 0; j < aNbObjects; j++ ) {
5286 // try to identify algorithm
5287 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5288 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5290 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5291 // open algorithm group
5292 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5293 aGroup->OpenOnDisk();
5295 // --> get algorithm id
5296 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5301 // get number of datasets
5302 int aNbSubObjects = aGroup->nInternalObjects();
5303 for ( int k = 0; k < aNbSubObjects; k++ ) {
5305 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5306 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5307 // --> get algorithm name
5308 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5309 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5310 aDataset->OpenOnDisk();
5311 size = aDataset->GetSize();
5312 char* hypname_str = new char[ size ];
5313 aDataset->ReadFromDisk( hypname_str );
5314 hypname = string( hypname_str );
5315 delete [] hypname_str;
5316 aDataset->CloseOnDisk();
5318 // --> get algorithm plugin library name
5319 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5320 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5321 aDataset->OpenOnDisk();
5322 size = aDataset->GetSize();
5323 char* libname_str = new char[ size ];
5324 aDataset->ReadFromDisk( libname_str );
5325 if(MYDEBUG) SCRUTE( libname_str );
5326 libname = string( libname_str );
5327 delete [] libname_str;
5328 aDataset->CloseOnDisk();
5330 // --> get algorithm data
5331 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5332 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5333 aDataset->OpenOnDisk();
5334 size = aDataset->GetSize();
5335 char* hypdata_str = new char[ size ];
5336 aDataset->ReadFromDisk( hypdata_str );
5337 if(MYDEBUG) SCRUTE( hypdata_str );
5338 hypdata = string( hypdata_str );
5339 delete [] hypdata_str;
5340 aDataset->CloseOnDisk();
5343 // close algorithm HDF group
5344 aGroup->CloseOnDisk();
5346 // --> restore algorithm from data
5347 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5348 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5349 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5350 SMESH::SMESH_Hypothesis_var myHyp;
5352 try { // protect persistence mechanism against exceptions
5353 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5355 catch( SALOME::SALOME_Exception& ex )
5357 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5360 INFOS( "Exception during hypothesis creation" );
5363 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5365 //myImpl->LoadFrom( hypdata.c_str() );
5366 hypDataList.push_back( make_pair( myImpl, hypdata ));
5367 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5368 int newId = myStudyContext->findId( iorString.in() );
5369 myStudyContext->mapOldToNew( id, newId );
5372 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5376 // close algorithms root HDF group
5377 aTopGroup->CloseOnDisk();
5381 // --> the rest groups should be meshes
5382 for ( int i = 0; i < aNbGroups; i++ ) {
5383 // identify next group
5384 char meshName[ HDF_NAME_MAX_LEN+1 ];
5385 aFile->InternalObjectIndentify( i, meshName );
5387 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5389 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5393 // open mesh HDF group
5394 aTopGroup = new HDFgroup( meshName, aFile );
5395 aTopGroup->OpenOnDisk();
5397 // get number of child HDF objects
5398 int aNbObjects = aTopGroup->nInternalObjects();
5399 if ( aNbObjects > 0 ) {
5401 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5402 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5403 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5404 if ( !myNewMeshImpl )
5406 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5408 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5409 int newId = myStudyContext->findId( iorString.in() );
5410 myStudyContext->mapOldToNew( id, newId );
5413 // try to read and set auto color flag
5414 char aMeshAutoColorName[ 30 ];
5415 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5416 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5418 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5419 aDataset->OpenOnDisk();
5420 size = aDataset->GetSize();
5421 int* anAutoColor = new int[ size ];
5422 aDataset->ReadFromDisk( anAutoColor );
5423 aDataset->CloseOnDisk();
5424 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5425 delete [] anAutoColor;
5428 // try to read and set reference to shape
5429 GEOM::GEOM_Object_var aShapeObject;
5430 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5431 // load mesh "Ref on shape" - it's an entry to SObject
5432 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5433 aDataset->OpenOnDisk();
5434 size = aDataset->GetSize();
5435 char* refFromFile = new char[ size ];
5436 aDataset->ReadFromDisk( refFromFile );
5437 aDataset->CloseOnDisk();
5438 if ( strlen( refFromFile ) > 0 ) {
5439 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5440 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5441 if ( !CORBA::is_nil( shapeObject ) ) {
5442 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5443 if ( !aShapeObject->_is_nil() )
5444 myNewMeshImpl->SetShape( aShapeObject );
5447 delete [] refFromFile;
5450 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5451 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5453 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5454 aDataset->OpenOnDisk();
5455 size = aDataset->GetSize();
5456 int* meshPersistentId = new int[ size ];
5457 aDataset->ReadFromDisk( meshPersistentId );
5458 aDataset->CloseOnDisk();
5459 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5460 delete [] meshPersistentId;
5463 // Restore SMESH_Mesh_i::_mainShapeTick
5464 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5466 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5467 aDataset->OpenOnDisk();
5468 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5469 aDataset->ReadFromDisk( shapeTick );
5470 aDataset->CloseOnDisk();
5473 // Restore file info
5474 if ( aTopGroup->ExistInternalObject( "file info" ))
5476 aDataset = new HDFdataset( "file info", aTopGroup );
5477 aDataset->OpenOnDisk();
5478 size = aDataset->GetSize();
5479 std::string info( size, ' ');
5480 aDataset->ReadFromDisk( (char*) info.data() );
5481 aDataset->CloseOnDisk();
5482 myNewMeshImpl->FileInfoFromString( info );
5488 // As all object that can be referred by hypothesis are created,
5489 // we can restore hypothesis data
5491 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5492 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5494 SMESH_Hypothesis_i* hyp = hyp_data->first;
5495 string & data = hyp_data->second;
5496 hyp->LoadFrom( data.c_str() );
5499 // Restore the rest mesh data
5501 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5502 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5504 aTopGroup = meshi_group->second;
5505 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5506 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5507 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5509 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5510 bool hasData = false;
5513 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5514 int newId = myStudyContext->findId( iorString.in() );
5515 int meshOldId = myStudyContext->getOldId( newId );
5517 // try to find mesh data dataset
5518 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5519 // load mesh "has data" flag
5520 aDataset = new HDFdataset( "Has data", aTopGroup );
5521 aDataset->OpenOnDisk();
5522 size = aDataset->GetSize();
5523 char* strHasData = new char[ size ];
5524 aDataset->ReadFromDisk( strHasData );
5525 aDataset->CloseOnDisk();
5526 if ( strcmp( strHasData, "1") == 0 ) {
5529 delete [] strHasData;
5532 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5533 // nodes and elements are not yet put into sub-meshes)
5534 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5535 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5536 aGroup->OpenOnDisk();
5537 // get number of applied algorithms
5538 int aNbSubObjects = aGroup->nInternalObjects();
5539 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5540 for ( int j = 0; j < aNbSubObjects; j++ ) {
5541 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5542 aGroup->InternalObjectIndentify( j, name_dataset );
5543 // check if it is an algorithm
5544 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5545 aDataset = new HDFdataset( name_dataset, aGroup );
5546 aDataset->OpenOnDisk();
5547 size = aDataset->GetSize();
5548 char* refFromFile = new char[ size ];
5549 aDataset->ReadFromDisk( refFromFile );
5550 aDataset->CloseOnDisk();
5551 // san - it is impossible to recover applied algorithms using their entries within Load() method
5552 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5553 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5554 int id = atoi( refFromFile );
5555 delete [] refFromFile;
5556 string anIOR = myStudyContext->getIORbyOldId( id );
5557 if ( !anIOR.empty() ) {
5558 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5559 if ( !CORBA::is_nil( hypObject ) ) {
5560 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5561 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5562 || !myNewMeshImpl->HasShapeToMesh()) )
5563 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5568 aGroup->CloseOnDisk();
5571 // try to get applied hypotheses
5572 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5573 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5574 aGroup->OpenOnDisk();
5575 // get number of applied hypotheses
5576 int aNbSubObjects = aGroup->nInternalObjects();
5577 for ( int j = 0; j < aNbSubObjects; j++ ) {
5578 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5579 aGroup->InternalObjectIndentify( j, name_dataset );
5580 // check if it is a hypothesis
5581 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5582 aDataset = new HDFdataset( name_dataset, aGroup );
5583 aDataset->OpenOnDisk();
5584 size = aDataset->GetSize();
5585 char* refFromFile = new char[ size ];
5586 aDataset->ReadFromDisk( refFromFile );
5587 aDataset->CloseOnDisk();
5588 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5589 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5590 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5591 int id = atoi( refFromFile );
5592 delete [] refFromFile;
5593 string anIOR = myStudyContext->getIORbyOldId( id );
5594 if ( !anIOR.empty() ) {
5595 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5596 if ( !CORBA::is_nil( hypObject ) ) {
5597 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5598 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5599 || !myNewMeshImpl->HasShapeToMesh()) )
5600 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5605 aGroup->CloseOnDisk();
5608 // --> try to find SUB-MESHES containers for each type of submesh
5609 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5610 const char* name_meshgroup = 0;
5611 if ( j == GetSubMeshOnVertexTag() )
5612 name_meshgroup = "SubMeshes On Vertex";
5613 else if ( j == GetSubMeshOnEdgeTag() )
5614 name_meshgroup = "SubMeshes On Edge";
5615 else if ( j == GetSubMeshOnWireTag() )
5616 name_meshgroup = "SubMeshes On Wire";
5617 else if ( j == GetSubMeshOnFaceTag() )
5618 name_meshgroup = "SubMeshes On Face";
5619 else if ( j == GetSubMeshOnShellTag() )
5620 name_meshgroup = "SubMeshes On Shell";
5621 else if ( j == GetSubMeshOnSolidTag() )
5622 name_meshgroup = "SubMeshes On Solid";
5623 else if ( j == GetSubMeshOnCompoundTag() )
5624 name_meshgroup = "SubMeshes On Compound";
5626 // try to get submeshes container HDF group
5627 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5628 // open submeshes containers HDF group
5629 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5630 aGroup->OpenOnDisk();
5632 // get number of submeshes
5633 int aNbSubMeshes = aGroup->nInternalObjects();
5634 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5636 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5637 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5638 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5639 // --> get submesh id
5640 int subid = atoi( name_submeshgroup + 7 );
5643 // open submesh HDF group
5644 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5645 aSubGroup->OpenOnDisk();
5647 // try to read and set reference to subshape
5648 GEOM::GEOM_Object_var aSubShapeObject;
5649 SMESH::SMESH_subMesh_var aSubMesh;
5651 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5652 // load submesh "Ref on shape" - it's an entry to SObject
5653 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5654 aDataset->OpenOnDisk();
5655 size = aDataset->GetSize();
5656 char* refFromFile = new char[ size ];
5657 aDataset->ReadFromDisk( refFromFile );
5658 aDataset->CloseOnDisk();
5659 if ( strlen( refFromFile ) > 0 ) {
5660 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5661 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5662 if ( !CORBA::is_nil( subShapeObject ) ) {
5663 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5664 if ( !aSubShapeObject->_is_nil() )
5665 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5666 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5667 if ( aSubMesh->_is_nil() )
5669 string iorSubString = GetORB()->object_to_string( aSubMesh );
5670 int newSubId = myStudyContext->findId( iorSubString );
5671 myStudyContext->mapOldToNew( subid, newSubId );
5674 delete [] refFromFile;
5677 if ( aSubMesh->_is_nil() )
5680 // try to get applied algorithms
5681 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5682 // open "applied algorithms" HDF group
5683 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5684 aSubSubGroup->OpenOnDisk();
5685 // get number of applied algorithms
5686 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5687 for ( int l = 0; l < aNbSubObjects; l++ ) {
5688 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5689 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5690 // check if it is an algorithm
5691 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5692 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5693 aDataset->OpenOnDisk();
5694 size = aDataset->GetSize();
5695 char* refFromFile = new char[ size ];
5696 aDataset->ReadFromDisk( refFromFile );
5697 aDataset->CloseOnDisk();
5699 int id = atoi( refFromFile );
5700 string anIOR = myStudyContext->getIORbyOldId( id );
5701 if ( !anIOR.empty() ) {
5702 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5703 if ( !CORBA::is_nil( hypObject ) ) {
5704 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5705 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5706 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5709 delete [] refFromFile;
5712 // close "applied algorithms" HDF group
5713 aSubSubGroup->CloseOnDisk();
5716 // try to get applied hypotheses
5717 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5718 // open "applied hypotheses" HDF group
5719 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5720 aSubSubGroup->OpenOnDisk();
5721 // get number of applied hypotheses
5722 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5723 for ( int l = 0; l < aNbSubObjects; l++ ) {
5724 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5725 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5726 // check if it is a hypothesis
5727 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5728 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5729 aDataset->OpenOnDisk();
5730 size = aDataset->GetSize();
5731 char* refFromFile = new char[ size ];
5732 aDataset->ReadFromDisk( refFromFile );
5733 aDataset->CloseOnDisk();
5735 int id = atoi( refFromFile );
5736 string anIOR = myStudyContext->getIORbyOldId( id );
5737 if ( !anIOR.empty() ) {
5738 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5739 if ( !CORBA::is_nil( hypObject ) ) {
5740 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5741 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5742 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5745 delete [] refFromFile;
5748 // close "APPLIED HYPOTHESES" hdf group
5749 aSubSubGroup->CloseOnDisk();
5752 // close SUB-MESH hdf group
5753 aSubGroup->CloseOnDisk();
5756 // close SUB-MESHES containers hdf group
5757 aGroup->CloseOnDisk();
5761 // try to get GROUPS
5762 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5763 char name_group[ 30 ];
5764 if ( ii == GetNodeGroupsTag() )
5765 strcpy( name_group, "Groups of Nodes" );
5766 else if ( ii == GetEdgeGroupsTag() )
5767 strcpy( name_group, "Groups of Edges" );
5768 else if ( ii == GetFaceGroupsTag() )
5769 strcpy( name_group, "Groups of Faces" );
5770 else if ( ii == GetVolumeGroupsTag() )
5771 strcpy( name_group, "Groups of Volumes" );
5772 else if ( ii == Get0DElementsGroupsTag() )
5773 strcpy( name_group, "Groups of 0D Elements" );
5774 else if ( ii == GetBallElementsGroupsTag() )
5775 strcpy( name_group, "Groups of Balls" );
5777 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5778 aGroup = new HDFgroup( name_group, aTopGroup );
5779 aGroup->OpenOnDisk();
5780 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5781 // within aGroup->ExistInternalObject( name )
5782 std::vector< std::string > subNames;
5783 TColStd_MapOfAsciiString mapOfNames;
5784 aGroup->GetAllObjects( subNames );
5785 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5786 mapOfNames.Add( subNames[ iN ].c_str() );
5788 for ( size_t j = 0; j < subNames.size(); j++ ) {
5789 const std::string& name_dataset = subNames[ j ];
5790 // check if it is a group
5791 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5794 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5797 int groupID = -1; // group local ID (also persistent)
5799 groupID = atoi( endptr + 1 );
5800 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5801 aDataset->OpenOnDisk();
5803 // Retrieve actual group name
5804 size = aDataset->GetSize();
5805 char* nameFromFile = new char[ size ];
5806 aDataset->ReadFromDisk( nameFromFile );
5807 aDataset->CloseOnDisk();
5809 // Try to find a shape reference
5810 TopoDS_Shape aShape;
5811 char aRefName[ 30 ];
5812 sprintf( aRefName, "Ref on shape %d", subid);
5813 if ( mapOfNames.Contains( aRefName ))
5815 // load mesh "Ref on shape" - it's an entry to SObject
5816 aDataset = new HDFdataset( aRefName, aGroup );
5817 aDataset->OpenOnDisk();
5818 size = aDataset->GetSize();
5819 char* refFromFile = new char[ size ];
5820 aDataset->ReadFromDisk( refFromFile );
5821 aDataset->CloseOnDisk();
5822 if ( strlen( refFromFile ) > 0 ) {
5823 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5824 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5825 if ( !CORBA::is_nil( shapeObject ) ) {
5826 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5827 if ( !aShapeObject->_is_nil() )
5828 aShape = GeomObjectToShape( aShapeObject );
5831 delete [] refFromFile;
5833 // Try to read a filter of SMESH_GroupOnFilter
5834 SMESH::Filter_var filter;
5835 SMESH_PredicatePtr predicate;
5836 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5837 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5839 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5840 aDataset->OpenOnDisk();
5841 size = aDataset->GetSize();
5842 char* persistStr = new char[ size ];
5843 aDataset->ReadFromDisk( persistStr );
5844 aDataset->CloseOnDisk();
5845 if ( strlen( persistStr ) > 0 ) {
5846 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5847 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5848 filters.push_back( filter );
5850 delete [] persistStr;
5853 // Create group servant
5854 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5855 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5856 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5857 delete [] nameFromFile;
5858 // Obtain a SMESHDS_Group object
5859 if ( aNewGroup->_is_nil() )
5862 string iorSubString = GetORB()->object_to_string( aNewGroup );
5863 int newSubId = myStudyContext->findId( iorSubString );
5864 myStudyContext->mapOldToNew( subid, newSubId );
5866 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5870 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5871 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5873 aFilterGroup->SetFilter( filter );
5874 filter->UnRegister();
5876 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5877 if ( !aGroupBaseDS )
5880 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5883 // Read color of the group
5884 char aGroupColorName[ 30 ];
5885 sprintf( aGroupColorName, "ColorGroup %d", subid);
5886 if ( mapOfNames.Contains( aGroupColorName ))
5888 aDataset = new HDFdataset( aGroupColorName, aGroup );
5889 aDataset->OpenOnDisk();
5890 size = aDataset->GetSize();
5891 double* anRGB = new double[ size ];
5892 aDataset->ReadFromDisk( anRGB );
5893 aDataset->CloseOnDisk();
5894 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5895 aGroupBaseDS->SetColor( aColor );
5900 aGroup->CloseOnDisk();
5904 // instead of reading mesh data, we read only brief information of all
5905 // objects: mesh, groups, sub-meshes (issue 0021208)
5908 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5909 meshfile.ToCString(), filename.ToCString(),
5913 // read Sub-Mesh ORDER if any
5914 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5915 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5916 aDataset->OpenOnDisk();
5917 size = aDataset->GetSize();
5918 int* smIDs = new int[ size ];
5919 aDataset->ReadFromDisk( smIDs );
5920 aDataset->CloseOnDisk();
5921 TListOfListOfInt anOrderIds;
5922 anOrderIds.push_back( TListOfInt() );
5923 for ( int i = 0; i < size; i++ )
5924 if ( smIDs[ i ] < 0 ) // is separator
5925 anOrderIds.push_back( TListOfInt() );
5927 anOrderIds.back().push_back(smIDs[ i ]);
5929 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5934 // update hyps needing full mesh data restored (issue 20918)
5935 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5937 SMESH_Hypothesis_i* hyp = hyp_data->first;
5938 hyp->UpdateAsMeshesRestored();
5941 // notify algos on completed restoration to set sub-mesh event listeners
5942 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5944 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5945 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5947 TopoDS_Shape myLocShape;
5948 if(myLocMesh.HasShapeToMesh())
5949 myLocShape = myLocMesh.GetShapeToMesh();
5951 myLocShape = SMESH_Mesh::PseudoShape();
5953 myLocMesh.GetSubMesh(myLocShape)->
5954 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5957 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5958 list< SMESH::Filter_var >::iterator f = filters.begin();
5959 for ( ; f != filters.end(); ++f )
5960 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5961 fi->FindBaseObjects();
5966 aTopGroup->CloseOnDisk();
5969 aFile->CloseOnDisk();
5972 // Remove temporary files created from the stream
5975 SMESH_File meshFile( meshfile.ToCString() );
5976 if ( !meshFile ) // no meshfile exists
5978 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5982 Engines::Container_var container = GetContainerRef();
5983 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5985 container_i->registerTemporaryFile( filename.ToCString() );
5986 container_i->registerTemporaryFile( meshfile.ToCString() );
5987 container_i->registerTemporaryFile( tmpDir.ToCString() );
5991 pd << ""; // prevent optimizing pd out
5993 // creation of tree nodes for all data objects in the study
5994 // to support tree representation customization and drag-n-drop:
5995 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
5996 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5997 useCaseBuilder->SetRootCurrent();
5998 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
5999 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6000 for (it->InitEx(true); it->More(); it->Next()) {
6001 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6008 //=============================================================================
6010 * SMESH_Gen_i::LoadASCII
6012 * Load SMESH module's data in ASCII format
6014 //=============================================================================
6016 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6017 const SALOMEDS::TMPFile& theStream,
6019 bool isMultiFile ) {
6020 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6021 return Load( theComponent, theStream, theURL, isMultiFile );
6023 //before call main ::Load method it's need for decipher text format to
6024 //binary ( "|xx" => x' )
6025 int size = theStream.length();
6026 if ( int((size / 3 )*3) != size ) //error size of buffer
6029 int real_size = int(size / 3);
6031 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6034 unsigned int c = -1;
6035 for ( int i = 0; i < real_size; i++ )
6037 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6038 sscanf( tmp, "%x", &c );
6039 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6042 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6044 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6047 //=============================================================================
6049 * SMESH_Gen_i::Close
6051 * Clears study-connected data when it is closed
6053 //=============================================================================
6055 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6057 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6059 // Clear study contexts data
6060 myStudyContext->Clear();
6062 // remove the tmp files meshes are loaded from
6063 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6065 // Clean trace of API methods calls
6071 //=============================================================================
6073 * SMESH_Gen_i::ComponentDataType
6075 * Get component data type
6077 //=============================================================================
6079 char* SMESH_Gen_i::ComponentDataType()
6081 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6082 return CORBA::string_dup( "SMESH" );
6086 //=============================================================================
6088 * SMESH_Gen_i::IORToLocalPersistentID
6090 * Transform data from transient form to persistent
6092 //=============================================================================
6094 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6095 const char* IORString,
6096 CORBA::Boolean /*isMultiFile*/,
6097 CORBA::Boolean /*isASCII*/ )
6099 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6101 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6102 int anId = myStudyContext->findId( IORString );
6104 if(MYDEBUG) MESSAGE( "VSR " << anId )
6106 sprintf( strId, "%d", anId );
6107 return CORBA::string_dup( strId );
6110 return CORBA::string_dup( "" );
6113 //=============================================================================
6115 * SMESH_Gen_i::LocalPersistentIDToIOR
6117 * Transform data from persistent form to transient
6119 //=============================================================================
6121 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6122 const char* aLocalPersistentID,
6123 CORBA::Boolean /*isMultiFile*/,
6124 CORBA::Boolean /*isASCII*/ )
6126 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6128 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6129 int anId = atoi( aLocalPersistentID );
6130 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6132 return CORBA::string_dup( "" );
6135 //=======================================================================
6136 //function : RegisterObject
6138 //=======================================================================
6140 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6142 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6143 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6144 return myStudyContext->addObject( string( iorString.in() ) );
6149 //================================================================================
6151 * \brief Return id of registered object
6152 * \param theObject - the Object
6153 * \retval int - Object id
6155 //================================================================================
6157 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6159 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6160 string iorString = GetORB()->object_to_string( theObject );
6161 return myStudyContext->findId( iorString );
6166 //=============================================================================
6168 * SMESH_Gen_i::SetName
6170 * Set a new object name
6172 //=============================================================================
6173 void SMESH_Gen_i::SetName(const char* theIOR,
6174 const char* theName)
6176 if ( theIOR && strcmp( theIOR, "" ) ) {
6177 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6178 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6179 if ( !aSO->_is_nil() ) {
6180 SetName( aSO, theName );
6185 // Version information
6186 char* SMESH_Gen_i::getVersion()
6188 #if SMESH_DEVELOPMENT
6189 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6191 return CORBA::string_dup(SMESH_VERSION_STR);
6195 //=================================================================================
6196 // function : Move()
6197 // purpose : Moves objects to the specified position.
6198 // Is used in the drag-n-drop functionality.
6199 //=================================================================================
6200 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6201 SALOMEDS::SObject_ptr where,
6204 if ( CORBA::is_nil( where ) ) return;
6206 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6207 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6208 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6209 std::string dataType = father->ComponentDataType();
6210 if ( dataType != "SMESH" ) return; // not a SMESH component
6212 SALOMEDS::SObject_var objAfter;
6213 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6214 // insert at given row -> find insertion position
6215 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6217 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6218 if ( i == row && useCaseIt->More() ) {
6219 objAfter = useCaseIt->Value();
6223 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6224 SALOMEDS::SObject_var sobj = what[i];
6225 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6226 // insert the object to the use case tree
6227 if ( !CORBA::is_nil( objAfter ) )
6228 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6230 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6233 //================================================================================
6235 * \brief Returns true if algorithm can be used to mesh a given geometry
6236 * \param [in] theAlgoType - the algorithm type
6237 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6238 * \param [in] theGeomObject - the geometry to mesh
6239 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6240 * else, returns \c True if at least one shape is meshable
6241 * \return CORBA::Boolean - can or can't
6243 //================================================================================
6245 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6246 const char* theLibName,
6247 GEOM::GEOM_Object_ptr theGeomObject,
6248 CORBA::Boolean toCheckAll)
6252 std::string aPlatformLibName;
6253 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6254 GenericHypothesisCreator_i* aCreator =
6255 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6258 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6259 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6260 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6267 SMESH_CATCH( SMESH::doNothing );
6270 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6275 //=================================================================================
6276 // function : GetInsideSphere
6277 // purpose : Collect indices of elements, which are located inside the sphere
6278 //=================================================================================
6279 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6280 SMESH::ElementType theElemType,
6286 SMESH::long_array_var aResult = new SMESH::long_array();
6287 if ( meshPart->_is_nil() )
6288 return aResult._retn();
6290 // 1. Create geometrical object
6291 gp_Pnt aP( theX, theY, theZ );
6292 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6294 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6296 if ( lst.size() > 0 ) {
6297 aResult->length( lst.size() );
6298 for ( size_t i = 0; i < lst.size(); i++ ) {
6299 aResult[i] = lst[i];
6302 return aResult._retn();
6305 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6306 SMESH::ElementType theElemType,
6307 CORBA::Double theX1,
6308 CORBA::Double theY1,
6309 CORBA::Double theZ1,
6310 CORBA::Double theX2,
6311 CORBA::Double theY2,
6312 CORBA::Double theZ2) {
6313 SMESH::long_array_var aResult = new SMESH::long_array();
6314 if( meshPart->_is_nil() )
6315 return aResult._retn();
6317 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6319 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6321 if( lst.size() > 0 ) {
6322 aResult->length( lst.size() );
6323 for ( size_t i = 0; i < lst.size(); i++ ) {
6324 aResult[i] = lst[i];
6327 return aResult._retn();
6330 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6331 SMESH::ElementType theElemType,
6335 CORBA::Double theDX,
6336 CORBA::Double theDY,
6337 CORBA::Double theDZ,
6339 CORBA::Double theR ){
6340 SMESH::long_array_var aResult = new SMESH::long_array();
6341 if( meshPart->_is_nil() )
6342 return aResult._retn();
6344 gp_Pnt aP( theX, theY, theZ );
6345 gp_Vec aV( theDX, theDY, theDZ );
6346 gp_Ax2 anAxes (aP, aV);
6348 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6350 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6352 if( lst.size() > 0 ) {
6353 aResult->length( lst.size() );
6354 for ( size_t i = 0; i < lst.size(); i++ ) {
6355 aResult[i] = lst[i];
6358 return aResult._retn();
6361 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6362 SMESH::ElementType theElemType,
6363 GEOM::GEOM_Object_ptr theGeom,
6364 CORBA::Double theTolerance ) {
6365 SMESH::long_array_var aResult = new SMESH::long_array();
6366 if( meshPart->_is_nil() || theGeom->_is_nil() )
6367 return aResult._retn();
6369 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6371 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6373 if( lst.size() > 0 ) {
6374 aResult->length( lst.size() );
6375 for ( size_t i = 0; i < lst.size(); i++ ) {
6376 aResult[i] = lst[i];
6379 return aResult._retn();
6384 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6385 SMESH::ElementType theElemType,
6386 TopoDS_Shape& aShape,
6387 double* theTolerance) {
6389 std::vector<long> res;
6390 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6392 if ( mesh->_is_nil() )
6395 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6399 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6404 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6405 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6406 anElementsOnShape->SetAllNodes( true );
6407 anElementsOnShape->SetMesh( meshDS );
6408 anElementsOnShape->SetShape( aShape, aType );
6411 anElementsOnShape->SetTolerance(*theTolerance);
6413 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6414 if ( !msource->_is_nil() ) { // Mesh case
6415 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6417 while ( elemIt->more() ) {
6418 const SMDS_MeshElement* anElem = elemIt->next();
6419 long anId = anElem->GetID();
6420 if ( anElementsOnShape->IsSatisfy( anId ) )
6421 res.push_back( anId );
6425 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6426 if ( !gsource->_is_nil() ) {
6427 if(theElemType == SMESH::NODE) {
6428 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6429 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6430 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6431 long anId = node->GetID();
6432 if ( anElementsOnShape->IsSatisfy( anId ) )
6433 res.push_back( anId );
6436 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6437 SMESH::long_array_var elems = gsource->GetListOfID();
6438 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6439 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6440 long anId = elem->GetID();
6441 if ( anElementsOnShape->IsSatisfy( anId ) )
6442 res.push_back( anId );
6447 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6448 if ( !smsource->_is_nil() ) {
6449 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6450 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6451 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6453 long anId = elem->GetID();
6454 if ( anElementsOnShape->IsSatisfy( anId ) )
6455 res.push_back( anId );
6463 //=============================================================================
6465 * SMESHEngine_factory
6467 * C factory, accessible with dlsym, after dlopen
6469 //=============================================================================
6473 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6474 PortableServer::POA_ptr poa,
6475 PortableServer::ObjectId* contId,
6476 const char* instanceName,
6477 const char* interfaceName )
6479 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6480 if(MYDEBUG) SCRUTE(interfaceName);
6481 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6482 return aSMESHGen->getId() ;