1 // Copyright (C) 2007-2020 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_SetIterator.hxx"
89 #include "SMDS_SpacePosition.hxx"
90 #include "SMDS_VertexPosition.hxx"
91 #include "SMESHDS_Document.hxx"
92 #include "SMESHDS_Group.hxx"
93 #include "SMESHDS_GroupOnGeom.hxx"
94 #include "SMESH_Algo_i.hxx"
95 #include "SMESH_File.hxx"
96 #include "SMESH_Group.hxx"
97 #include "SMESH_Group_i.hxx"
98 #include "SMESH_Hypothesis.hxx"
99 #include "SMESH_Hypothesis_i.hxx"
100 #include "SMESH_Mesh.hxx"
101 #include "SMESH_MeshEditor.hxx"
102 #include "SMESH_Mesh_i.hxx"
103 #include "SMESH_PreMeshInfo.hxx"
104 #include "SMESH_PythonDump.hxx"
105 #include "SMESH_ControlsDef.hxx"
107 // to pass CORBA exception through SMESH_TRY
108 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
109 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
111 #include CORBA_SERVER_HEADER(SMESH_Group)
112 #include CORBA_SERVER_HEADER(SMESH_Filter)
113 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
116 #include <GEOMImpl_Types.hxx>
117 #include <GEOM_Client.hxx>
119 #include <Basics_Utils.hxx>
120 #include <Basics_DirUtils.hxx>
122 #include <OpUtil.hxx>
123 #include <SALOMEDS_Tool.hxx>
124 #include <SALOME_Container_i.hxx>
125 #include <SALOME_LifeCycleCORBA.hxx>
126 #include <SALOME_NamingService.hxx>
127 #include <Utils_CorbaException.hxx>
128 #include <Utils_ExceptHandlers.hxx>
129 #include <Utils_SINGLETON.hxx>
130 #include <utilities.h>
132 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
133 #include CORBA_CLIENT_HEADER(SALOME_Session)
135 // helpers about SALOME::GenericObj
136 #include <SALOMEDS_wrap.hxx>
137 #include <SALOMEDS_Attributes_wrap.hxx>
138 #include <GEOM_wrap.hxx>
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 //================================================================================
736 * \brief Return true if mesh has ICON_SMESH_TREE_GEOM_MODIF icon
738 //================================================================================
740 bool SMESH_Gen_i::isGeomModifIcon( SMESH::SMESH_Mesh_ptr mesh )
742 SALOMEDS::SObject_wrap so = ObjectToSObject( mesh );
743 SALOMEDS::GenericAttribute_wrap attr;
744 if ( ! so->_is_nil() && so->FindAttribute( attr.inout(), "AttributePixMap" ))
746 SALOMEDS::AttributePixMap_wrap pm = attr;
747 CORBA::String_var ico = pm->GetPixMap();
748 return ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 );
753 //=================================================================================
754 // function : hasObjectInfo()
755 // purpose : shows if module provides information for its objects
756 //=================================================================================
758 bool SMESH_Gen_i::hasObjectInfo()
763 //=================================================================================
764 // function : getObjectInfo()
765 // purpose : returns an information for a given object by its entry
766 //=================================================================================
768 char* SMESH_Gen_i::getObjectInfo( const char* entry )
770 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
771 // for the rest, "module 'SMESH', ID=0:1:2:*"
775 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
776 CORBA::Object_var obj = SObjectToObject( so );
777 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
778 if ( isGeomModifIcon( mesh ))
780 txt << "The geometry was changed and the mesh needs to be recomputed";
785 CORBA::String_var compType = ComponentDataType();
786 txt << "module '" << compType << "', ID=" << entry;
788 return CORBA::string_dup( txt );
791 //=============================================================================
793 * SMESH_Gen_i::GetStudyContext
797 //=============================================================================
798 StudyContext* SMESH_Gen_i::GetStudyContext()
800 return myStudyContext;
803 //=============================================================================
805 * SMESH_Gen_i::CreateHypothesis
807 * Create hypothesis/algorithm of given type and publish it in the study
809 //=============================================================================
811 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
812 const char* theLibName )
813 throw ( SALOME::SALOME_Exception )
815 Unexpect aCatch(SALOME_SalomeException);
816 // Create hypothesis/algorithm
817 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
819 // Publish hypothesis/algorithm in the study
820 if ( CanPublishInStudy( hyp ) ) {
821 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
822 if ( !aSO->_is_nil() ) {
823 // Update Python script
824 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
825 << theHypName << "', '" << theLibName << "')";
832 //================================================================================
834 * \brief Return a hypothesis initialized by given average length.
835 * \param theHypType - hypothesis type name
836 * \param theLibName - plugin library name
837 * \param theAverageLength - average length
838 * \param theQuadDominated - is quad-dominated flag
839 * \retval SMESH::SMESH_Hypothesis_ptr - the new hypothesis
841 //================================================================================
843 SMESH::SMESH_Hypothesis_ptr
844 SMESH_Gen_i::CreateHypothesisByAverageLength( const char* theHypType,
845 const char* theLibName,
846 CORBA::Double theAverageLength,
847 CORBA::Boolean theQuadDominated)
848 throw ( SALOME::SALOME_Exception )
850 SMESH::HypInitParams initParams = { ::SMESH_Hypothesis::BY_AVERAGE_LENGTH,
851 theAverageLength, theQuadDominated };
853 SMESH::SMESH_Hypothesis_var hyp =
854 GetHypothesisParameterValues( theHypType, theLibName,
855 SMESH::SMESH_Mesh::_nil(),
856 GEOM::GEOM_Object::_nil(),
858 SALOMEDS::SObject_wrap so = PublishHypothesis( hyp );
860 TPythonDump() << hyp << " = " << this << ".CreateHypothesisByAverageLength( '"
861 << theHypType << "', '"
862 << theLibName << "', "
863 << theAverageLength << ", "
864 << theQuadDominated << " )";
869 //================================================================================
871 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
872 * existing on the given geometry or to size of the geometry.
873 * \param theHypType - hypothesis type name
874 * \param theLibName - plugin library name
875 * \param theMesh - The mesh of interest
876 * \param theGeom - The shape to get parameter values from
877 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
878 * in a study and used to compute the mesh, or a temporary one created just to pass
881 //================================================================================
883 SMESH::SMESH_Hypothesis_ptr
884 SMESH_Gen_i::GetHypothesisParameterValues( const char* theHypType,
885 const char* theLibName,
886 SMESH::SMESH_Mesh_ptr theMesh,
887 GEOM::GEOM_Object_ptr theGeom,
888 const SMESH::HypInitParams& theParams)
889 throw ( SALOME::SALOME_Exception )
891 Unexpect aCatch(SALOME_SalomeException);
893 const bool byMesh = ( theParams.way == ::SMESH_Hypothesis::BY_MESH );
894 if ( byMesh && CORBA::is_nil( theMesh ) )
895 return SMESH::SMESH_Hypothesis::_nil();
896 if ( byMesh && CORBA::is_nil( theGeom ) )
897 return SMESH::SMESH_Hypothesis::_nil();
899 // -----------------------------------------------
900 // find hypothesis used to mesh theGeom
901 // -----------------------------------------------
903 // get mesh and shape
904 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
905 TopoDS_Shape shape = GeomObjectToShape( theGeom );
906 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
907 return SMESH::SMESH_Hypothesis::_nil();
908 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
910 // create a temporary hypothesis to know its dimension
911 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
912 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
914 return SMESH::SMESH_Hypothesis::_nil();
915 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
918 // look for a hypothesis of theHypType used to mesh the shape
919 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
922 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
923 int nbLocalHyps = aHypList->length();
924 for ( int i = 0; i < nbLocalHyps; i++ ) {
925 CORBA::String_var hypName = aHypList[i]->GetName();
926 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
927 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
929 // check super shapes
930 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
931 while ( nbLocalHyps == 0 && itShape.More() ) {
932 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
933 if ( ! CORBA::is_nil( geomObj )) {
934 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
935 nbLocalHyps = aHypList->length();
936 for ( int i = 0; i < nbLocalHyps; i++ )
937 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
938 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
944 // let the temporary hypothesis find out somehow parameter values by mesh
945 if ( hyp->SetParametersByMesh( mesh, shape ))
946 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
950 ::SMESH_Hypothesis::TDefaults dflts;
951 dflts._way = ( ::SMESH_Hypothesis::InitWay) theParams.way;
952 dflts._nbSegments = myGen.GetDefaultNbSegments();
953 dflts._elemLength = theParams.averageLength;
954 dflts._quadDominated = theParams.quadDominated;
955 if ( theParams.way == ::SMESH_Hypothesis::BY_GEOM )
958 dflts._diagonal = mesh->GetShapeDiagonalSize();
960 dflts._diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
961 dflts._elemLength = dflts._diagonal / myGen.GetBoundaryBoxSegmentation();
962 dflts._shape = &shape;
965 // let the hypothesis initialize it's values
966 if ( hyp->SetParametersByDefaults( dflts, mesh ))
967 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
970 return SMESH::SMESH_Hypothesis::_nil();
973 //=============================================================================
975 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
976 * \param [in] theHyp - the hypothesis of interest
977 * \param [out] theMesh - the sole mesh using \a theHyp
978 * \param [out] theShape - the sole geometry \a theHyp is assigned to
979 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
981 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
982 * considered as SAME sub-mesh => result is \c true.
983 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
984 * a shape to which an hyp being edited is assigned.
986 //=============================================================================
988 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
989 SMESH::SMESH_Mesh_out theMesh,
990 GEOM::GEOM_Object_out theShape)
992 if ( CORBA::is_nil( theHyp ))
995 // get Mesh component SO
996 CORBA::String_var compDataType = ComponentDataType();
997 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
998 if ( CORBA::is_nil( comp ))
1001 // look for child SO of meshes
1002 SMESH::SMESH_Mesh_var foundMesh;
1003 TopoDS_Shape foundShape;
1005 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
1006 for ( ; meshIter->More() && isSole; meshIter->Next() )
1008 SALOMEDS::SObject_wrap curSO = meshIter->Value();
1009 CORBA::Object_var obj = SObjectToObject( curSO );
1010 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
1014 // look for a sole shape where theHyp is assigned
1015 bool isHypFound = false;
1016 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
1017 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
1018 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
1020 const THypList& hyps = s2hypsIt.Value();
1021 THypList::const_iterator h = hyps.begin();
1022 for ( ; h != hyps.end(); ++h )
1023 if ( (*h)->GetID() == theHyp->GetId() )
1025 if ( h != hyps.end()) // theHyp found
1028 if ( ! foundShape.IsNull() &&
1029 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
1031 foundShape.Nullify();
1035 foundShape = s2hypsIt.Key();
1037 } // loop on assigned hyps
1039 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
1041 if ( !foundMesh->_is_nil() ) // not a sole mesh
1043 if ( !foundMesh->HasShapeToMesh() ||
1044 !mesh_i ->HasShapeToMesh() )
1046 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
1050 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
1051 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
1052 isSole = s1->IsSame( s2 );
1055 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1061 ! foundMesh->_is_nil() &&
1062 ! foundShape.IsNull() )
1064 theMesh = foundMesh._retn();
1065 theShape = ShapeToGeomObject( foundShape );
1066 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1071 //=============================================================================
1073 * Sets number of segments per diagonal of boundary box of geometry by which
1074 * default segment length of appropriate 1D hypotheses is defined
1076 //=============================================================================
1078 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1079 throw ( SALOME::SALOME_Exception )
1081 if ( theNbSegments > 0 )
1082 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1084 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1086 //=============================================================================
1088 * \brief Sets default number of segments per edge
1090 //=============================================================================
1091 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1092 throw ( SALOME::SALOME_Exception )
1094 if ( theNbSegments > 0 )
1095 myGen.SetDefaultNbSegments( int(theNbSegments) );
1097 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1100 //=============================================================================
1104 //=============================================================================
1106 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1108 if ( name && value && strlen( value ) > 0 )
1111 if ( strcmp(name, "historical_python_dump") == 0 )
1113 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1114 msgToGUI = "preferences/SMESH/historical_python_dump/";
1115 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1117 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1119 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1120 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1121 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1123 else if ( strcmp(name, "default_grp_color") == 0 )
1127 // color must be presented as a string of following form:
1128 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1129 str = str.substr(1);
1130 for ( size_t i = 0; i < str.length()/2; i++ )
1131 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1132 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1134 else if ( value ) { // rgb color ("255,170,0", for example)
1135 string tempValue( value );
1136 char* colorValue = strtok( &tempValue[0], "," );
1137 while ( colorValue != NULL ) {
1138 int c_value = atoi( colorValue );
1139 if ( c_value >= 0 && c_value <= 255 )
1140 color.push_back( c_value );
1141 colorValue = strtok( NULL, "," );
1144 if ( color.size() == 3 ) { // color must have three valid component
1145 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1146 myDefaultGroupColor = value;
1147 msgToGUI = "preferences/SMESH/default_grp_color/";
1152 // update preferences in case if SetOption() is invoked from python console
1153 if ( !msgToGUI.empty() )
1155 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1156 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1157 if ( !CORBA::is_nil( session ) )
1158 session->emitMessageOneWay(msgToGUI.c_str());
1163 //=============================================================================
1165 Return an option value
1167 //=============================================================================
1169 char* SMESH_Gen_i::GetOption(const char* name)
1173 if ( strcmp(name, "historical_python_dump") == 0 )
1175 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1177 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1179 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1181 if ( strcmp(name, "default_grp_color") == 0 )
1183 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1186 return CORBA::string_dup( "" );
1189 //=============================================================================
1191 * SMESH_Gen_i::CreateMesh
1193 * Create empty mesh on a shape and publish it in the study
1195 //=============================================================================
1197 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1198 throw ( SALOME::SALOME_Exception )
1200 Unexpect aCatch(SALOME_SalomeException);
1201 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1203 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1205 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1206 ASSERT( meshServant );
1207 meshServant->SetShape( theShapeObject );
1209 // publish mesh in the study
1210 if ( CanPublishInStudy( mesh ) ) {
1211 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1212 aStudyBuilder->NewCommand(); // There is a transaction
1213 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1214 aStudyBuilder->CommitCommand();
1215 if ( !aSO->_is_nil() ) {
1216 // Update Python script
1217 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1221 return mesh._retn();
1224 //=============================================================================
1226 * SMESH_Gen_i::CreateEmptyMesh
1230 //=============================================================================
1232 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1233 throw ( SALOME::SALOME_Exception )
1235 Unexpect aCatch(SALOME_SalomeException);
1236 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1238 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1240 // publish mesh in the study
1241 if ( CanPublishInStudy( mesh ) ) {
1242 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1243 aStudyBuilder->NewCommand(); // There is a transaction
1244 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1245 aStudyBuilder->CommitCommand();
1246 if ( !aSO->_is_nil() ) {
1247 // Update Python script
1248 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1252 return mesh._retn();
1257 //================================================================================
1259 * \brief Throws an exception in case if the file can't be read
1261 //================================================================================
1263 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1265 SMESH_File f ( theFileName );
1268 if ( !f.error().empty() )
1269 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1271 THROW_SALOME_CORBA_EXCEPTION
1272 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1273 SALOME::BAD_PARAM );
1278 //=============================================================================
1280 * SMESH_Gen_i::CreateMeshFromUNV
1282 * Create mesh and import data from UNV file
1284 //=============================================================================
1286 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1287 throw ( SALOME::SALOME_Exception )
1289 Unexpect aCatch(SALOME_SalomeException);
1291 checkFileReadable( theFileName );
1293 SMESH::SMESH_Mesh_var aMesh = createMesh();
1295 // publish mesh in the study
1296 if ( CanPublishInStudy( aMesh ) ) {
1297 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1298 aStudyBuilder->NewCommand(); // There is a transaction
1299 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1300 aStudyBuilder->CommitCommand();
1301 if ( !aSO->_is_nil() ) {
1302 // Update Python script
1303 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1307 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1309 aServant->ImportUNVFile( theFileName );
1311 // Dump creation of groups
1312 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1314 aServant->GetImpl().GetMeshDS()->Modified();
1315 return aMesh._retn();
1318 //=============================================================================
1320 * SMESH_Gen_i::CreateMeshFromMED
1322 * Create mesh and import data from MED file
1324 //=============================================================================
1326 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1327 SMESH::DriverMED_ReadStatus& theStatus,
1328 const char* theCommandNameForPython,
1329 const char* theFileNameForPython)
1332 char bname[ _MAX_FNAME ];
1333 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1334 string aFileName = bname;
1336 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1338 // Retrieve mesh names from the file
1339 DriverMED_R_SMESHDS_Mesh myReader;
1340 myReader.SetFile( theFileName );
1341 myReader.SetMeshId( -1 );
1342 Driver_Mesh::Status aStatus;
1343 list<string> aNames = myReader.GetMeshNames(aStatus);
1344 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1345 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1347 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1350 TPythonDump aPythonDump;
1351 aPythonDump << "([";
1353 if (theStatus == SMESH::DRS_OK) {
1354 SALOMEDS::StudyBuilder_var aStudyBuilder;
1355 aStudyBuilder = getStudyServant()->NewBuilder();
1356 aStudyBuilder->NewCommand(); // There is a transaction
1358 aResult->length( aNames.size() );
1361 // Iterate through all meshes and create mesh objects
1362 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1365 if (i > 0) aPythonDump << ", ";
1368 SMESH::SMESH_Mesh_var mesh = createMesh();
1370 // publish mesh in the study
1371 SALOMEDS::SObject_wrap aSO;
1372 if ( CanPublishInStudy( mesh ) )
1373 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1374 // - as names of meshes are stored in MED file, we use them for data publishing
1375 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1376 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1379 if ( !aSO->_is_nil() ) {
1382 aPythonDump << "mesh_" << i;
1385 // Read mesh data (groups are published automatically by ImportMEDFile())
1386 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1387 ASSERT( meshServant );
1388 SMESH::DriverMED_ReadStatus status1 =
1389 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1390 if (status1 > theStatus)
1391 theStatus = status1;
1393 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1394 meshServant->GetImpl().GetMeshDS()->Modified();
1396 if ( !aStudyBuilder->_is_nil() )
1397 aStudyBuilder->CommitCommand();
1400 // Update Python script
1401 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1403 // Dump creation of groups
1404 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1405 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1407 return aResult._retn();
1410 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1411 SMESH::DriverMED_ReadStatus& theStatus)
1412 throw ( SALOME::SALOME_Exception )
1414 Unexpect aCatch(SALOME_SalomeException);
1415 checkFileReadable( theFileName );
1417 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1421 //=============================================================================
1423 * SMESH_Gen_i::CreateMeshFromSAUV
1425 * Create mesh and import data from SAUV file
1427 //=============================================================================
1429 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1430 SMESH::DriverMED_ReadStatus& theStatus)
1431 throw ( SALOME::SALOME_Exception )
1433 Unexpect aCatch(SALOME_SalomeException);
1434 checkFileReadable( theFileName );
1436 std::string sauvfilename(theFileName);
1437 std::string medfilename(theFileName);
1438 medfilename += ".med";
1441 cmd = "%PYTHONBIN% ";
1446 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1448 system(cmd.c_str());
1449 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1451 cmd = "%PYTHONBIN% ";
1456 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1458 system(cmd.c_str());
1462 //=============================================================================
1464 * SMESH_Gen_i::CreateMeshFromSTL
1466 * Create mesh and import data from STL file
1468 //=============================================================================
1470 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1471 throw ( SALOME::SALOME_Exception )
1473 Unexpect aCatch(SALOME_SalomeException);
1474 checkFileReadable( theFileName );
1476 SMESH::SMESH_Mesh_var aMesh = createMesh();
1479 char bname[ _MAX_FNAME ];
1480 _splitpath( theFileName, NULL, NULL, bname, NULL );
1481 string aFileName = bname;
1483 string aFileName = basename( const_cast<char *>(theFileName) );
1485 // publish mesh in the study
1486 if ( CanPublishInStudy( aMesh ) ) {
1487 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1488 aStudyBuilder->NewCommand(); // There is a transaction
1489 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1490 aStudyBuilder->CommitCommand();
1491 if ( !aSO->_is_nil() ) {
1492 // Update Python script
1493 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1497 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1499 aServant->ImportSTLFile( theFileName );
1500 aServant->GetImpl().GetMeshDS()->Modified();
1501 return aMesh._retn();
1504 //================================================================================
1506 * \brief Create meshes and import data from the CGSN file
1508 //================================================================================
1510 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1511 SMESH::DriverMED_ReadStatus& theStatus)
1512 throw ( SALOME::SALOME_Exception )
1514 Unexpect aCatch(SALOME_SalomeException);
1515 checkFileReadable( theFileName );
1517 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1520 // Retrieve nb meshes from the file
1521 DriverCGNS_Read myReader;
1522 myReader.SetFile( theFileName );
1523 Driver_Mesh::Status aStatus;
1524 int nbMeshes = myReader.GetNbMeshes(aStatus);
1525 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1527 aResult->length( nbMeshes );
1529 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1532 TPythonDump aPythonDump;
1533 aPythonDump << "([";
1535 if (theStatus == SMESH::DRS_OK)
1537 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1538 aStudyBuilder->NewCommand(); // There is a transaction
1542 // Iterate through all meshes and create mesh objects
1543 for ( ; i < nbMeshes; ++i )
1546 if (i > 0) aPythonDump << ", ";
1549 SMESH::SMESH_Mesh_var mesh = createMesh();
1550 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1552 // Read mesh data (groups are published automatically by ImportMEDFile())
1553 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1554 ASSERT( meshServant );
1556 SMESH::DriverMED_ReadStatus status1 =
1557 meshServant->ImportCGNSFile( theFileName, i, meshName );
1558 if (status1 > theStatus)
1559 theStatus = status1;
1561 meshServant->GetImpl().GetMeshDS()->Modified();
1562 // publish mesh in the study
1563 SALOMEDS::SObject_wrap aSO;
1564 if ( CanPublishInStudy( mesh ) )
1565 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1568 if ( !aSO->_is_nil() ) {
1572 aPythonDump << "mesh_" << i;
1575 aStudyBuilder->CommitCommand();
1578 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1580 // Dump creation of groups
1581 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1582 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1584 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1587 return aResult._retn();
1590 //================================================================================
1592 * \brief Create a mesh and import data from a GMF file
1594 //================================================================================
1596 SMESH::SMESH_Mesh_ptr
1597 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1598 CORBA::Boolean theMakeRequiredGroups,
1599 SMESH::ComputeError_out theError)
1600 throw ( SALOME::SALOME_Exception )
1602 Unexpect aCatch(SALOME_SalomeException);
1603 checkFileReadable( theFileName );
1605 SMESH::SMESH_Mesh_var aMesh = createMesh();
1607 char bname[ _MAX_FNAME ];
1608 _splitpath( theFileName, NULL, NULL, bname, NULL );
1609 string aFileName = bname;
1611 string aFileName = basename( const_cast<char *>(theFileName) );
1613 // publish mesh in the study
1614 if ( CanPublishInStudy( aMesh ) ) {
1615 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1616 aStudyBuilder->NewCommand(); // There is a transaction
1617 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1618 aStudyBuilder->CommitCommand();
1619 if ( !aSO->_is_nil() ) {
1620 // Update Python script
1621 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1622 << theFileName << "', "
1623 << theMakeRequiredGroups << " )";
1626 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1628 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1629 aServant->GetImpl().GetMeshDS()->Modified();
1630 return aMesh._retn();
1634 //=============================================================================
1636 * SMESH_Gen_i::IsReadyToCompute
1638 * Returns true if mesh contains enough data to be computed
1640 //=============================================================================
1642 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1643 GEOM::GEOM_Object_ptr theShapeObject )
1644 throw ( SALOME::SALOME_Exception )
1646 Unexpect aCatch(SALOME_SalomeException);
1647 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1649 if ( CORBA::is_nil( theShapeObject ) )
1650 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1651 SALOME::BAD_PARAM );
1653 if ( CORBA::is_nil( theMesh ) )
1654 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1655 SALOME::BAD_PARAM );
1659 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1660 ASSERT( meshServant );
1661 if ( meshServant ) {
1662 // get local TopoDS_Shape
1663 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1664 // call implementation
1665 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1666 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1669 catch ( SALOME_Exception& S_ex ) {
1670 INFOS( "catch exception "<< S_ex.what() );
1675 //================================================================================
1677 * \brief Find SObject for an algo
1679 //================================================================================
1681 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1684 SALOMEDS::Study_var aStudy = getStudyServant();
1685 if ( !aStudy->_is_nil() ) {
1686 // find algo in the study
1687 CORBA::String_var compDataType = ComponentDataType();
1688 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1689 if ( !father->_is_nil() ) {
1690 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1691 for ( ; itBig->More(); itBig->Next() ) {
1692 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1693 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1694 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1695 for ( ; algoIt->More(); algoIt->Next() ) {
1696 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1697 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1698 if ( !CORBA::is_nil( algoIOR )) {
1699 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1700 if ( impl && impl->GetImpl() == algo )
1701 return algoSO._retn();
1703 } // loop on algo SO's
1706 } // SMESH component iterator
1710 return SALOMEDS::SObject::_nil();
1713 //================================================================================
1715 * \brief Return errors of mesh computation
1717 //================================================================================
1719 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1720 GEOM::GEOM_Object_ptr theSubObject )
1721 throw ( SALOME::SALOME_Exception )
1723 Unexpect aCatch(SALOME_SalomeException);
1724 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1726 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1727 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1729 if ( CORBA::is_nil( theMesh ) )
1730 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1732 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1734 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1737 if(theMesh->HasShapeToMesh())
1738 shape = GeomObjectToShape( theSubObject );
1740 shape = SMESH_Mesh::PseudoShape();
1742 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1744 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1747 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1748 const bool includeSelf = true, complexShapeFirst = true;
1749 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1751 while ( smIt->more() )
1754 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1756 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1757 if ( error && !error->IsOK() )
1759 if ( !( error->myAlgo ) &&
1760 !( error->myAlgo = sm->GetAlgo() ))
1762 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1763 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1764 errStruct.comment = error->myComment.c_str();
1765 errStruct.subShapeID = sm->GetId();
1766 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1767 if ( !algoSO->_is_nil() ) {
1768 CORBA::String_var algoName = algoSO->GetName();
1769 errStruct.algoName = algoName;
1772 errStruct.algoName = error->myAlgo->GetName();
1774 errStruct.hasBadMesh = error->HasBadElems();
1777 error_array->length( nbErr );
1780 catch ( SALOME_Exception& S_ex ) {
1781 INFOS( "catch exception "<< S_ex.what() );
1784 return error_array._retn();
1787 //================================================================================
1789 * \brief Return mesh elements preventing computation of a subshape
1791 //================================================================================
1793 SMESH::MeshPreviewStruct*
1794 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1795 CORBA::Short theSubShapeID )
1796 throw ( SALOME::SALOME_Exception )
1798 Unexpect aCatch(SALOME_SalomeException);
1799 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1801 if ( CORBA::is_nil( theMesh ) )
1802 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1804 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1807 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1809 // mesh implementation
1810 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1811 // submesh by subshape id
1812 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1815 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1816 if ( error && error->HasBadElems() )
1818 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1819 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1821 // get nodes of elements and count elements
1822 TNode2LocalIDMap mapNode2LocalID;
1823 list< TNodeLocalID > connectivity;
1824 int i, nbElements = 0, nbConnNodes = 0;
1826 const list<const SMDS_MeshElement*>& badElems =
1827 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1828 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1829 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1830 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1832 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1833 while ( nIt->more() )
1834 connectivity.push_back
1835 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1837 // fill node coords and assign local ids to the nodes
1838 int nbNodes = mapNode2LocalID.size();
1839 result->nodesXYZ.length( nbNodes );
1840 TNodeLocalID node2ID = mapNode2LocalID.begin();
1841 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1842 node2ID->second = i;
1843 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1844 result->nodesXYZ[i].x = node->X();
1845 result->nodesXYZ[i].y = node->Y();
1846 result->nodesXYZ[i].z = node->Z();
1848 // fill connectivity
1849 result->elementConnectivities.length( nbConnNodes );
1850 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1851 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1852 result->elementConnectivities[i] = (*connIt)->second;
1854 // fill element types
1855 result->elementTypes.length( nbElements );
1856 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1858 const SMDS_MeshElement* elem = *elemIt;
1859 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1860 result->elementTypes[i].isPoly = elem->IsPoly();
1861 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1867 catch ( SALOME_Exception& S_ex ) {
1868 INFOS( "catch exception "<< S_ex.what() );
1871 return result._retn();
1874 //================================================================================
1876 * \brief Create a group of elements preventing computation of a sub-shape
1878 //================================================================================
1880 SMESH::ListOfGroups*
1881 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1882 CORBA::Short theSubShapeID,
1883 const char* theGroupName )
1884 throw ( SALOME::SALOME_Exception )
1886 Unexpect aCatch(SALOME_SalomeException);
1888 SMESH::ListOfGroups_var groups;
1890 if ( CORBA::is_nil( theMesh ) )
1891 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1894 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1896 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1897 TPythonDump() << groups << " = " << this
1898 << ".MakeGroupsOfBadInputElements( "
1899 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1902 catch ( SALOME_Exception& S_ex ) {
1903 INFOS( "catch exception "<< S_ex.what() );
1905 return groups._retn();
1908 //================================================================================
1910 * \brief Returns errors of hypotheses definition
1911 * \param theMesh - the mesh
1912 * \param theSubObject - the main or sub- shape
1913 * \retval SMESH::algo_error_array* - sequence of errors
1915 //================================================================================
1917 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1918 GEOM::GEOM_Object_ptr theSubObject )
1919 throw ( SALOME::SALOME_Exception )
1921 Unexpect aCatch(SALOME_SalomeException);
1922 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1924 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1925 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1927 if ( CORBA::is_nil( theMesh ) )
1928 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1930 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1932 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1933 ASSERT( meshServant );
1934 if ( meshServant ) {
1935 TopoDS_Shape myLocShape;
1936 if(theMesh->HasShapeToMesh())
1937 myLocShape = GeomObjectToShape( theSubObject );
1939 myLocShape = SMESH_Mesh::PseudoShape();
1941 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1942 list< ::SMESH_Gen::TAlgoStateError > error_list;
1943 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1944 // call ::SMESH_Gen::GetAlgoState()
1945 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1946 error_array->length( error_list.size() );
1948 for ( error = error_list.begin(); error != error_list.end(); ++error )
1950 // fill AlgoStateError structure
1951 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1952 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1953 errStruct.algoDim = error->_algoDim;
1954 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1955 errStruct.algoName = "";
1956 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1957 if ( !algoSO->_is_nil() ) {
1958 CORBA::String_var algoName = algoSO->GetName();
1959 errStruct.algoName = algoName.in();
1964 catch ( SALOME_Exception& S_ex ) {
1965 INFOS( "catch exception "<< S_ex.what() );
1967 return error_array._retn();
1970 //=============================================================================
1972 * SMESH_Gen_i::GetSubShapesId
1974 * Get sub-shapes unique ID's list
1976 //=============================================================================
1979 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1980 const SMESH::object_array& theListOfSubShapeObject )
1981 throw ( SALOME::SALOME_Exception )
1983 Unexpect aCatch(SALOME_SalomeException);
1984 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1986 SMESH::long_array_var shapesId = new SMESH::long_array;
1989 if ( CORBA::is_nil( theMainShapeObject ) )
1990 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1994 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1995 TopTools_IndexedMapOfShape myIndexToShape;
1996 TopExp::MapShapes(myMainShape,myIndexToShape);
1998 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
2000 GEOM::GEOM_Object_var aShapeObject
2001 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
2002 if ( CORBA::is_nil( aShapeObject ) )
2003 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
2004 SALOME::BAD_PARAM );
2006 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
2007 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
2009 const TopoDS_Face& F = TopoDS::Face(exp.Current());
2010 setId.insert(myIndexToShape.FindIndex(F));
2011 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
2013 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
2015 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
2016 setId.insert(myIndexToShape.FindIndex(E));
2017 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
2019 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
2021 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
2022 setId.insert(myIndexToShape.FindIndex(V));
2023 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
2026 shapesId->length(setId.size());
2027 set<int>::iterator iind;
2029 for (iind = setId.begin(); iind != setId.end(); iind++)
2031 if(MYDEBUG) SCRUTE((*iind));
2032 shapesId[i] = (*iind);
2033 if(MYDEBUG) SCRUTE(shapesId[i]);
2037 catch (SALOME_Exception& S_ex)
2039 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
2042 return shapesId._retn();
2045 //=============================================================================
2047 * SMESH_Gen_i::Compute
2049 * Compute mesh on a shape
2051 //=============================================================================
2053 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
2054 GEOM::GEOM_Object_ptr theShapeObject )
2055 throw ( SALOME::SALOME_Exception )
2058 Unexpect aCatch(SALOME_SalomeException);
2059 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2061 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2062 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2063 SALOME::BAD_PARAM );
2065 if ( CORBA::is_nil( theMesh ) )
2066 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2067 SALOME::BAD_PARAM );
2069 // Update Python script
2070 TPythonDump() << "isDone = " << this << ".Compute( "
2071 << theMesh << ", " << theShapeObject << ")";
2075 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2076 ASSERT( meshServant );
2077 if ( meshServant ) {
2078 if ( isGeomModifIcon( theMesh ))
2079 meshServant->Clear();
2081 meshServant->Load();
2082 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2083 meshServant->CheckGeomModif();
2084 // get local TopoDS_Shape
2085 TopoDS_Shape myLocShape;
2086 if(theMesh->HasShapeToMesh())
2087 myLocShape = GeomObjectToShape( theShapeObject );
2089 myLocShape = SMESH_Mesh::PseudoShape();
2090 // call implementation compute
2091 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2092 myGen.PrepareCompute( myLocMesh, myLocShape );
2093 int how = ::SMESH_Gen::COMPACT_MESH;
2094 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2095 how |= ::SMESH_Gen::SHAPE_ONLY;
2096 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2097 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2098 myLocMesh.GetMeshDS()->Modified();
2099 UpdateIcons( theMesh );
2101 HighLightInvalid( theMesh, /*isInvalid=*/false );
2105 catch ( std::bad_alloc ) {
2106 INFOS( "Compute(): lack of memory" );
2108 catch ( SALOME_Exception& S_ex ) {
2109 INFOS( "Compute(): catch exception "<< S_ex.what() );
2112 INFOS( "Compute(): unknown exception " );
2117 //=============================================================================
2119 * SMESH_Gen_i::CancelCompute
2121 * Cancel Compute mesh on a shape
2123 //=============================================================================
2125 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2126 GEOM::GEOM_Object_ptr theShapeObject )
2128 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2130 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2131 TopoDS_Shape myLocShape;
2132 if(theMesh->HasShapeToMesh())
2133 myLocShape = GeomObjectToShape( theShapeObject );
2135 myLocShape = SMESH_Mesh::PseudoShape();
2136 myGen.CancelCompute( myLocMesh, myLocShape);
2140 //=============================================================================
2142 * SMESH_Gen_i::Precompute
2144 * Compute mesh as preview till indicated dimension on shape
2146 //=============================================================================
2148 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2149 GEOM::GEOM_Object_ptr theShapeObject,
2150 SMESH::Dimension theDimension,
2151 SMESH::long_array& theShapesId)
2152 throw ( SALOME::SALOME_Exception )
2154 Unexpect aCatch(SALOME_SalomeException);
2155 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2157 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2158 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2159 SALOME::BAD_PARAM );
2161 if ( CORBA::is_nil( theMesh ) )
2162 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2163 SALOME::BAD_PARAM );
2165 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2168 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2169 meshServant->Load();
2170 ASSERT( meshServant );
2171 if ( meshServant ) {
2172 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2173 meshServant->CheckGeomModif();
2174 // get local TopoDS_Shape
2175 TopoDS_Shape myLocShape;
2176 if(theMesh->HasShapeToMesh())
2177 myLocShape = GeomObjectToShape( theShapeObject );
2179 return result._retn();
2181 // call implementation compute
2182 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2184 ::MeshDimension aDim = (MeshDimension)theDimension;
2185 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2187 int nbShapeId = shapeIds.size();
2188 theShapesId.length( nbShapeId );
2189 // iterates on shapes and collect mesh entities into mesh preview
2190 TSetOfInt::const_iterator idIt = shapeIds.begin();
2191 TSetOfInt::const_iterator idEnd = shapeIds.end();
2192 std::map< int, int > mapOfShIdNb;
2193 std::set< SMESH_TLink > setOfEdge;
2194 std::list< SMDSAbs_ElementType > listOfElemType;
2195 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2196 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2197 TNode2LocalIDMap mapNode2LocalID;
2198 list< TNodeLocalID > connectivity;
2199 int i, nbConnNodes = 0;
2200 std::set< const SMESH_subMesh* > setOfVSubMesh;
2201 // iterates on shapes
2202 for ( ; idIt != idEnd; idIt++ )
2204 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2206 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2207 if ( !sm || !sm->IsMeshComputed() )
2210 const TopoDS_Shape& aSh = sm->GetSubShape();
2211 const int shDim = myGen.GetShapeDim( aSh );
2212 if ( shDim < 1 || shDim > theDimension )
2215 mapOfShIdNb[ *idIt ] = 0;
2216 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2218 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2219 if ( !smDS ) continue;
2221 if ( theDimension == SMESH::DIM_2D )
2223 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2224 while ( faceIt->more() )
2226 const SMDS_MeshElement* face = faceIt->next();
2227 int aNbNode = face->NbNodes();
2229 aNbNode /= 2; // do not take into account additional middle nodes
2231 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2232 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2234 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2235 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2237 listOfElemType.push_back( SMDSAbs_Edge );
2238 connectivity.push_back
2239 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2240 connectivity.push_back
2241 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2247 else if ( theDimension == SMESH::DIM_1D )
2249 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2250 while ( nodeIt->more() )
2252 listOfElemType.push_back( SMDSAbs_Node );
2253 connectivity.push_back
2254 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2256 // add corner nodes by first vertex from edge
2257 SMESH_subMeshIteratorPtr edgeSmIt =
2258 sm->getDependsOnIterator(/*includeSelf*/false,
2259 /*complexShapeFirst*/false);
2260 while ( edgeSmIt->more() )
2262 SMESH_subMesh* vertexSM = edgeSmIt->next();
2263 // check that vertex is not already treated
2264 if ( !setOfVSubMesh.insert( vertexSM ).second )
2266 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2269 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2270 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2271 while ( nodeIt->more() )
2273 listOfElemType.push_back( SMDSAbs_Node );
2274 connectivity.push_back
2275 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2281 // fill node coords and assign local ids to the nodes
2282 int nbNodes = mapNode2LocalID.size();
2283 result->nodesXYZ.length( nbNodes );
2284 TNodeLocalID node2ID = mapNode2LocalID.begin();
2285 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2286 node2ID->second = i;
2287 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2288 result->nodesXYZ[i].x = node->X();
2289 result->nodesXYZ[i].y = node->Y();
2290 result->nodesXYZ[i].z = node->Z();
2292 // fill connectivity
2293 result->elementConnectivities.length( nbConnNodes );
2294 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2295 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2296 result->elementConnectivities[i] = (*connIt)->second;
2299 // fill element types
2300 result->elementTypes.length( listOfElemType.size() );
2301 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2302 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2303 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2305 SMDSAbs_ElementType elemType = *typeIt;
2306 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2307 result->elementTypes[i].isPoly = false;
2308 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2311 // correct number of shapes
2312 theShapesId.length( mapOfShIdNb.size() );
2316 catch ( std::bad_alloc ) {
2317 INFOS( "Precompute(): lack of memory" );
2319 catch ( SALOME_Exception& S_ex ) {
2320 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2323 INFOS( "Precompute(): unknown exception " );
2325 return result._retn();
2329 //=============================================================================
2331 * SMESH_Gen_i::Evaluate
2333 * Evaluate mesh on a shape
2335 //=============================================================================
2337 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2338 GEOM::GEOM_Object_ptr theShapeObject)
2339 // SMESH::long_array& theNbElems)
2340 throw ( SALOME::SALOME_Exception )
2342 Unexpect aCatch(SALOME_SalomeException);
2343 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2345 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2346 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2347 SALOME::BAD_PARAM );
2349 if ( CORBA::is_nil( theMesh ) )
2350 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2351 SALOME::BAD_PARAM );
2353 SMESH::long_array_var nbels = new SMESH::long_array;
2354 nbels->length(SMESH::Entity_Last);
2355 int i = SMESH::Entity_Node;
2356 for (; i < SMESH::Entity_Last; i++)
2359 // Update Python script
2360 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2361 << theMesh << ", " << theShapeObject << ")";
2365 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2366 ASSERT( meshServant );
2367 if ( meshServant ) {
2368 meshServant->Load();
2369 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2370 meshServant->CheckGeomModif();
2371 // get local TopoDS_Shape
2372 TopoDS_Shape myLocShape;
2373 if(theMesh->HasShapeToMesh())
2374 myLocShape = GeomObjectToShape( theShapeObject );
2376 myLocShape = SMESH_Mesh::PseudoShape();
2377 // call implementation compute
2378 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2379 MapShapeNbElems aResMap;
2380 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2381 MapShapeNbElemsItr anIt = aResMap.begin();
2382 for(; anIt!=aResMap.end(); anIt++) {
2383 const vector<int>& aVec = (*anIt).second;
2384 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2385 int nbElem = aVec[i];
2386 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2388 SMESH_subMesh* sm = anIt->first;
2389 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2390 const SMESH_Algo* algo = sm->GetAlgo();
2391 if ( (algo && !error.get()) || error->IsOK() )
2392 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2396 nbels[i] += aVec[i];
2400 return nbels._retn();
2403 catch ( std::bad_alloc ) {
2404 INFOS( "Evaluate(): lack of memory" );
2406 catch ( SALOME_Exception& S_ex ) {
2407 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2410 INFOS( "Evaluate(): unknown exception " );
2413 return nbels._retn();
2416 //================================================================================
2418 * \brief Return geometrical object the given element is built on
2419 * \param theMesh - the mesh the element is in
2420 * \param theElementID - the element ID
2421 * \param theGeomName - the name of the result geom object if it is not yet published
2422 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2424 //================================================================================
2426 GEOM::GEOM_Object_ptr
2427 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2428 CORBA::Long theElementID,
2429 const char* theGeomName)
2430 throw ( SALOME::SALOME_Exception )
2432 Unexpect aCatch(SALOME_SalomeException);
2434 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2435 if ( !geom->_is_nil() ) {
2436 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2437 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2439 // try to find the corresponding SObject
2440 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2441 if ( SObj->_is_nil() ) // submesh can be not found even if published
2443 // try to find published submesh
2444 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2445 if ( !geom->IsMainShape() && list->length() == 1 ) {
2446 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2447 SALOMEDS::ChildIterator_wrap it;
2448 if ( !mainSO->_is_nil() ) {
2449 it = getStudyServant()->NewChildIterator( mainSO );
2451 if ( !it->_is_nil() ) {
2452 for ( it->InitEx(true); it->More(); it->Next() ) {
2453 SALOMEDS::SObject_wrap so = it->Value();
2454 CORBA::Object_var obj = SObjectToObject( so );
2455 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2456 if ( !subGeom->_is_nil() ) {
2457 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2458 if ( subList->length() == 1 && list[0] == subList[0] ) {
2468 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2469 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2471 // return only published geometry
2472 if ( !SObj->_is_nil() ) {
2473 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2474 CORBA::Object_var obj = SObjectToObject( SObj );
2475 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2479 return GEOM::GEOM_Object::_nil();
2482 //================================================================================
2484 * \brief Return geometrical object the given element is built on.
2485 * \param theMesh - the mesh the element is in
2486 * \param theElementID - the element ID
2487 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2489 //================================================================================
2491 GEOM::GEOM_Object_ptr
2492 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2493 CORBA::Long theElementID)
2494 throw ( SALOME::SALOME_Exception )
2496 Unexpect aCatch(SALOME_SalomeException);
2497 if ( CORBA::is_nil( theMesh ) )
2498 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2500 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2501 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2503 // get a core mesh DS
2504 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2505 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2507 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2508 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2509 // find the element in mesh
2510 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2511 // find a shape id by the element
2512 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2513 // get a geom object by the shape id
2514 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2515 if ( geom->_is_nil() ) {
2516 // try to find a published sub-shape
2517 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2518 SALOMEDS::ChildIterator_wrap it;
2519 if ( !mainSO->_is_nil() ) {
2520 it = getStudyServant()->NewChildIterator( mainSO );
2522 if ( !it->_is_nil() ) {
2523 for ( it->InitEx(true); it->More(); it->Next() ) {
2524 SALOMEDS::SObject_wrap so = it->Value();
2525 CORBA::Object_var obj = SObjectToObject( so );
2526 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2527 if ( !subGeom->_is_nil() ) {
2528 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2529 if ( subList->length() == 1 && shapeID == subList[0] ) {
2537 if ( geom->_is_nil() ) {
2539 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2540 if ( !op->_is_nil() )
2541 geom = op->GetSubShape( mainShape, shapeID );
2546 if ( !geom->_is_nil() ) {
2547 GeomObjectToShape( geom ); // let geom client remember the found shape
2548 return geom._retn();
2553 return GEOM::GEOM_Object::_nil();
2556 //================================================================================
2558 * SMESH_Gen_i::Concatenate
2560 * Concatenate the given meshes into one mesh
2562 //================================================================================
2564 SMESH::SMESH_Mesh_ptr
2565 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2566 CORBA::Boolean theUniteIdenticalGroups,
2567 CORBA::Boolean theMergeNodesAndElements,
2568 CORBA::Double theMergeTolerance,
2569 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2570 throw ( SALOME::SALOME_Exception )
2572 return ConcatenateCommon(theMeshesArray,
2573 theUniteIdenticalGroups,
2574 theMergeNodesAndElements,
2580 //================================================================================
2582 * SMESH_Gen_i::ConcatenateWithGroups
2584 * Concatenate the given meshes into one mesh
2585 * Create the groups of all elements from initial meshes
2587 //================================================================================
2589 SMESH::SMESH_Mesh_ptr
2590 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2591 CORBA::Boolean theUniteIdenticalGroups,
2592 CORBA::Boolean theMergeNodesAndElements,
2593 CORBA::Double theMergeTolerance,
2594 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2595 throw ( SALOME::SALOME_Exception )
2597 return ConcatenateCommon(theMeshesArray,
2598 theUniteIdenticalGroups,
2599 theMergeNodesAndElements,
2605 //================================================================================
2607 * SMESH_Gen_i::ConcatenateCommon
2609 * Concatenate the given meshes into one mesh
2611 //================================================================================
2613 SMESH::SMESH_Mesh_ptr
2614 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2615 CORBA::Boolean theUniteIdenticalGroups,
2616 CORBA::Boolean theMergeNodesAndElements,
2617 CORBA::Double theMergeTolerance,
2618 CORBA::Boolean theCommonGroups,
2619 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2620 throw ( SALOME::SALOME_Exception )
2622 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2623 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2625 // create mesh if theMeshToAppendTo not provided
2626 SMESH::SMESH_Mesh_var newMesh;
2627 if ( CORBA::is_nil( theMeshToAppendTo ))
2628 newMesh = CreateEmptyMesh();
2630 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2631 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2632 if ( !newImpl ) return newMesh._retn();
2635 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2636 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2638 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2639 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2640 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2641 TGroupsMap groupsMap;
2642 TListOfNewGroups listOfNewGroups;
2644 if ( !CORBA::is_nil( theMeshToAppendTo ))
2646 // fill groupsMap with existing groups
2647 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2648 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2650 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2651 if ( !group->_is_nil() )
2653 CORBA::String_var name = group->GetName();
2654 SMESH::ElementType type = group->GetType();
2655 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2660 ::SMESH_MeshEditor newEditor( &locMesh );
2661 ::SMESH_MeshEditor::ElemFeatures elemType;
2663 // loop on sub-meshes
2664 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2666 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2667 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2668 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2669 if ( !initImpl ) continue;
2670 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2674 // assure that IDs increment by one during iteration
2675 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2676 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2677 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2678 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2680 initMeshDS->Modified();
2681 initMeshDS->CompactMesh();
2684 // remember nb of elements before filling in
2685 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2689 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2690 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2691 while ( elemIt->more() )
2693 SMESH_NodeXYZ node = elemIt->next();
2694 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2699 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2700 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2702 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2703 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2704 while ( elemIt->more() )
2706 const SMDS_MeshElement* elem = elemIt->next();
2707 elemType.myNodes.resize( elem->NbNodes() );
2709 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2710 for ( int k = 0; itNodes->more(); k++)
2712 const SMDS_MeshNode* node = itNodes->next();
2713 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2716 // creates a corresponding element on existent nodes in new mesh
2717 newElems[ elem->GetID() ] =
2718 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2720 newEditor.ClearLastCreated(); // forget the history
2723 // create groups of just added elements
2724 SMESH::SMESH_Group_var newGroup;
2725 SMESH::ElementType groupType;
2726 if ( theCommonGroups )
2729 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2730 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2731 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2732 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2735 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2737 for( groupType = SMESH::NODE;
2738 groupType < SMESH::NB_ELEMENT_TYPES;
2739 groupType = (SMESH::ElementType)( groupType + 1 ))
2741 if ( curState[ groupType ] <= prevState[ groupType ])
2742 continue; // no elements of groupType added from the i-th mesh
2744 // make a group name
2745 std::string groupName = "Gr";
2746 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2748 CORBA::String_var name = meshSO->GetName();
2752 groupName += typeNames[ groupType ];
2754 // make and fill a group
2755 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2756 std::vector< const SMDS_MeshElement* > & elemVec =
2757 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2758 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2760 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2762 for ( size_t j = 0; j < elemVec.size(); ++j )
2764 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2765 grpDS->Add( elemVec[j] );
2769 listOfNewGroups.clear();
2770 listOfNewGroups.push_back( newGroup );
2771 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2776 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2780 SMESH::SMESH_GroupBase_ptr group;
2781 CORBA::String_var groupName;
2782 SMESH::long_array_var newIDs = new SMESH::long_array();
2784 // loop on groups of a source mesh
2785 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2786 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2788 group = listOfGroups[iG];
2789 groupType = group->GetType();
2790 groupName = group->GetName();
2791 std::string name = groupName.in();
2793 // convert a list of IDs
2794 newIDs->length( group->Size() );
2795 std::vector< const SMDS_MeshElement* > & elemVec =
2796 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2797 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2799 while ( itGrElems->more() )
2801 const SMDS_MeshElement* elem = itGrElems->next();
2802 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2804 newIDs[ nbElems++ ] = newElem->GetID();
2806 newIDs->length( nbElems );
2808 // check that a current group name and type don't have identical ones in final mesh
2809 listOfNewGroups.clear();
2810 TNameAndType nameAndType( name, groupType );
2811 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2812 if ( anIter == groupsMap.end() )
2814 // add a new group in the mesh
2815 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2816 newGroup->Add( newIDs );
2818 listOfNewGroups.push_back( newGroup );
2819 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2821 else if ( theUniteIdenticalGroups )
2823 // unite identical groups
2824 TListOfNewGroups& aNewGroups = anIter->second;
2825 aNewGroups.front()->Add( newIDs );
2829 // rename identical groups
2830 newGroup = newImpl->CreateGroup( groupType, groupName );
2831 newGroup->Add( newIDs );
2833 TListOfNewGroups& newGroups = anIter->second;
2834 std::string newGroupName;
2835 if ( newGroups.size() == 1 )
2837 newGroupName = name + "_1";
2838 newGroups.front()->SetName( newGroupName.c_str() );
2840 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2841 newGroup->SetName( newGroupName.c_str() );
2842 newGroups.push_back( newGroup );
2845 } // if an IDSource is a mesh
2848 if ( theMergeNodesAndElements ) // merge nodes
2850 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2851 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2852 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2853 /*SeparateCornersAndMedium=*/ false );
2854 newEditor.MergeNodes( groupsOfNodes );
2856 newEditor.MergeEqualElements();
2859 // Update Python script
2860 pythonDump << newMesh << " = " << this
2861 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2862 << theMeshesArray << ", "
2863 << theUniteIdenticalGroups << ", "
2864 << theMergeNodesAndElements << ", "
2865 << TVar( theMergeTolerance ) << ", "
2866 << theMeshToAppendTo << " )";
2868 pPythonDump.reset(); // enable python dump from GetGroups()
2870 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2871 if ( !newMesh->_is_nil() )
2873 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2876 // IPAL21468 Change icon of compound because it need not be computed.
2877 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2878 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2880 newMeshDS->Modified();
2882 return newMesh._retn();
2885 //================================================================================
2887 * \brief Create a mesh by copying a part of another mesh
2888 * \param meshPart - a part of mesh to copy
2889 * \param toCopyGroups - to create in the new mesh groups
2890 * the copied elements belongs to
2891 * \param toKeepIDs - to preserve IDs of the copied elements or not
2892 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2894 //================================================================================
2896 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2897 const char* meshName,
2898 CORBA::Boolean toCopyGroups,
2899 CORBA::Boolean toKeepIDs)
2900 throw ( SALOME::SALOME_Exception )
2902 Unexpect aCatch(SALOME_SalomeException);
2904 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2905 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2907 // 1. Get source mesh
2909 if ( CORBA::is_nil( meshPart ))
2910 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2912 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2913 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2915 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2917 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2919 // 2. Make a new mesh
2921 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2922 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2924 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2925 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2926 if ( !meshSO->_is_nil() )
2928 SetName( meshSO, meshName, "Mesh" );
2929 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2931 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2932 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2933 ::SMESH_MeshEditor::ElemFeatures elemType;
2935 // 3. Get elements to copy
2937 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2938 TIDSortedElemSet srcElems;
2939 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2940 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2943 srcElemIt = srcMeshDS->elementsIterator();
2944 srcNodeIt = srcMeshDS->nodesIterator();
2948 SMESH::long_array_var ids = meshPart->GetIDs();
2949 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2951 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2952 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2953 srcElems.insert( elem );
2957 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2958 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2959 srcElems.insert( elem );
2961 if ( srcElems.empty() )
2962 return newMesh._retn();
2964 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2965 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2970 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2971 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2972 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2974 const SMDS_MeshNode *nSrc, *nTgt;
2975 vector< const SMDS_MeshNode* > nodes;
2976 while ( srcElemIt->more() )
2978 const SMDS_MeshElement * elem = srcElemIt->next();
2980 nodes.resize( elem->NbNodes());
2981 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2983 for ( iN = 0; nIt->more(); ++iN )
2985 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2986 nTgt = newMeshDS->FindNode( nSrc->GetID());
2988 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2993 for ( iN = 0; nIt->more(); ++iN )
2995 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2996 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2998 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2999 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
3003 if ( elem->GetType() != SMDSAbs_Node )
3005 elemType.Init( elem, /*basicOnly=*/false );
3006 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
3008 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
3009 if ( toCopyGroups && !toKeepIDs )
3010 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
3012 } // while ( srcElemIt->more() )
3014 // 4(b). Copy free nodes
3016 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
3018 while ( srcNodeIt->more() )
3020 nSrc = srcNodeIt->next();
3021 if ( nSrc->NbInverseElements() == 0 )
3024 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
3026 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
3033 int nbNewGroups = 0;
3036 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
3037 while ( gIt->more() )
3039 SMESH_Group* group = gIt->next();
3040 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
3042 // Check group type. We copy nodal groups containing nodes of copied element
3043 SMDSAbs_ElementType groupType = groupDS->GetType();
3044 if ( groupType != SMDSAbs_Node &&
3045 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
3046 continue; // group type differs from types of meshPart
3048 // Find copied elements in the group
3049 vector< const SMDS_MeshElement* > groupElems;
3050 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
3053 const SMDS_MeshElement* foundElem;
3054 if ( groupType == SMDSAbs_Node )
3056 while ( eIt->more() )
3057 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3058 groupElems.push_back( foundElem );
3062 while ( eIt->more() )
3063 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3064 groupElems.push_back( foundElem );
3069 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3070 if ( e2eMap.empty() ) continue;
3071 int minID = e2eMap.begin()->first->GetID();
3072 int maxID = e2eMap.rbegin()->first->GetID();
3073 TE2EMap::iterator e2e;
3074 while ( eIt->more() && groupElems.size() < e2eMap.size())
3076 const SMDS_MeshElement* e = eIt->next();
3077 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3078 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3079 groupElems.push_back( e2e->second );
3083 if ( !groupElems.empty() )
3085 SMESH::SMESH_Group_var newGroupObj =
3086 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3087 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3089 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3090 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3091 for ( unsigned i = 0; i < groupElems.size(); ++i )
3092 smdsGroup.Add( groupElems[i] );
3100 newMeshDS->Modified();
3102 *pyDump << newMesh << " = " << this
3103 << ".CopyMesh( " << meshPart << ", "
3104 << "'" << meshName << "', "
3105 << toCopyGroups << ", "
3106 << toKeepIDs << ")";
3108 pyDumpDeleter.reset(); // allow dump in GetGroups()
3110 if ( nbNewGroups > 0 ) // dump created groups
3111 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3113 return newMesh._retn();
3117 namespace // utils for CopyMeshWithGeom()
3119 typedef std::map< std::string, std::string > TStr2StrMap;
3120 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3121 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3122 typedef std::map< std::string, int > TName2IndexMap;
3124 //================================================================================
3126 * \brief Return a new sub-shape corresponding to an old one
3128 //================================================================================
3132 SMESH_Mesh_i* mySrcMesh_i;
3133 SMESH_Mesh_i* myNewMesh_i;
3134 SMESH_Gen_i* myGen_i;
3138 TStr2StrMap myOld2NewEntryMap; // map of study entries
3140 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3141 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3142 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3145 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3147 // not directly relating to shape search
3148 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3150 //================================================================================
3152 * \brief Constructor
3154 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3155 SMESH_Mesh_i* newMesh_i,
3156 SMESH_Gen_i* smeshGen_i )
3157 : mySrcMesh_i( srcMesh_i ),
3158 myNewMesh_i( newMesh_i ),
3159 myGen_i ( smeshGen_i ),
3160 myToPublish( smeshGen_i->IsEnablePublish() ),
3161 myGIPMapDone( false )
3163 // retrieve from the study shape mapping made thanks to
3164 // "Set presentation parameters and sub-shapes from arguments" option
3166 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3167 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3168 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3169 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3170 if ( newSO->_is_nil() )
3172 myToPublish = false;
3175 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3177 CORBA::String_var oldEntry = oldSO->GetID();
3178 CORBA::String_var newEntry = newSO->GetID();
3179 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3180 std::string( newEntry.in() )));
3181 std::string newMainEntry = newEntry.in();
3183 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3184 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3185 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3186 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3187 /*groupsOnly=*/false );
3188 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3190 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3191 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3192 bool refFound = false;
3193 for ( ; anIter->More(); anIter->Next() )
3195 SALOMEDS::SObject_wrap so = anIter->Value();
3196 if ( so->ReferencedObject( oldSO.inout() ))
3198 oldEntry = oldSO->GetID();
3199 newEntry = newSO->GetID();
3200 if (( refFound = ( newMainEntry != oldEntry.in() )))
3201 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3202 std::string( newEntry.in() )));
3207 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3208 if ( father->_is_equivalent( mainShapeNew ))
3210 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3211 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3212 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3213 CORBA::String_var name = newSO->GetName();
3215 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3221 //================================================================================
3223 * \brief Find a new sub-shape corresponding to an old one
3225 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3228 return GEOM::GEOM_Object::_duplicate( oldShape );
3230 GEOM::GEOM_Object_var newShape;
3232 if ( CORBA::is_nil( oldShape ))
3233 return newShape._retn();
3235 if ( !isChildOfOld( oldShape ))
3236 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3238 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3239 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3241 // try to find by entry or name
3244 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3245 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3246 if ( o2nID != myOld2NewEntryMap.end() )
3248 newShape = getShapeByEntry( o2nID->second );
3250 if ( newShape->_is_nil() )
3252 CORBA::String_var name = oldShape->GetName();
3253 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3254 if ( n2ind != myName2SubshapeIndex.end() )
3256 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3257 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3258 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3259 if ( oldIndices->length() == 0 ||
3260 newIndices->length() == 0 ||
3261 getShapeType( myNewMesh_i, newIndices[0] ) !=
3262 getShapeType( mySrcMesh_i, oldIndices[0] ))
3263 newShape = GEOM::GEOM_Object::_nil();
3268 if ( newShape->_is_nil() )
3270 // try to construct a new sub-shape using myGIPMap
3272 std::vector< int > newIndices;
3273 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3274 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3276 findNewIDs( oldIndices[i], newIndices );
3278 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3281 newShape = getInPlace( oldShape );
3283 if ( !newIndices.empty() && newShape->_is_nil() )
3285 // search for a sub-shape with same ids
3286 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3287 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3288 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3289 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3291 if ( newShape->_is_nil() )
3294 // create a new shape
3295 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3297 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3299 GEOM::GEOM_IGroupOperations_wrap grOp = geomGen->GetIGroupOperations();
3300 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3302 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3303 newIndicesList->length( newIndices.size() );
3304 for ( size_t i = 0; i < newIndices.size(); ++i )
3305 newIndicesList[ i ] = newIndices[ i ];
3306 grOp->UnionIDs( newShape, newIndicesList );
3310 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3311 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3320 if ( !newShape->_is_nil() && myToPublish )
3322 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3323 if ( !newEntry.in() || !newEntry.in()[0] )
3325 CORBA::String_var name = oldShape->GetName();
3326 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3327 newEntry = newShape->GetStudyEntry();
3328 oldEntry = oldShape->GetStudyEntry();
3329 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3330 std::string( newEntry.in() )));
3334 return newShape._retn();
3337 //================================================================================
3339 * \brief Return a study entry of a new shape by study entry of the old one
3341 std::string FindNew( const std::string & oldEntry )
3346 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3347 if ( o2nID != myOld2NewEntryMap.end() )
3348 return o2nID->second;
3350 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3351 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3354 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3355 if ( newShape->_is_nil() )
3356 return std::string();
3358 CORBA::String_var newEntry = newShape->GetStudyEntry();
3359 return newEntry.in();
3362 //================================================================================
3364 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3365 * Return zero if not found or there are more than one new ID
3367 int FindNew( int oldID )
3376 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3378 if ( myGIPMap[ oldID ].length() == 1 )
3380 newID = myGIPMap[ oldID ][ 0 ];
3382 else if ( myGIPMap[ oldID ].length() > 1 &&
3383 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3385 // select a meshed VERTEX
3386 SMESH_subMesh* newSM;
3387 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3388 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3389 ( !newSM->IsEmpty() ))
3390 newID = myGIPMap[ oldID ][ i ];
3396 //================================================================================
3398 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3399 * Return zero if the old shape is not kept as is in the new shape.
3401 int FindNewNotChanged( SMESH_subMesh* oldSM )
3404 return oldSM->GetId();
3406 int newID = FindNew( oldSM->GetId() );
3410 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3414 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3415 // one new sub-shape of the same type.
3417 if ( oldSM->DependsOn().size() !=
3418 newSM->DependsOn().size() )
3421 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3422 while ( srcSMIt->more() )
3424 oldSM = srcSMIt->next();
3425 int newSubID = FindNew( oldSM->GetId() );
3426 if ( getShapeType( myNewMesh_i, newSubID ) !=
3427 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3433 //================================================================================
3435 * \brief Return shape by study entry
3437 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3439 GEOM::GEOM_Object_var shape;
3440 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3441 if ( !so->_is_nil() )
3443 CORBA::Object_var obj = so->GetObject();
3444 shape = GEOM::GEOM_Object::_narrow( obj );
3446 return shape._retn();
3449 //================================================================================
3451 * \brief Fill myGIPMap by calling GetInPlaceMap()
3455 if ( !myGIPMapDone )
3457 myGIPMapDone = true;
3459 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3460 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3461 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3462 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3465 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3469 myGIPMap = new GEOM::ListOfListOfLong();
3474 //================================================================================
3476 * \brief Get new sub-shape by calling GetInPlace()
3478 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3480 GEOM::GEOM_Object_var newShape;
3482 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3483 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3484 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3487 newShape = op->GetInPlace( mainShapeNew, oldShape );
3492 return newShape._retn();
3495 //================================================================================
3497 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3498 * number of found IDs
3500 int findNewIDs( int oldID, std::vector< int >& newIDs )
3502 size_t prevNbIDs = newIDs.size();
3504 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3506 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3507 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3509 return newIDs.size() - prevNbIDs;
3512 //================================================================================
3514 * \brief Check if an object relates to the old shape
3516 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3518 if ( CORBA::is_nil( oldShape ))
3520 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3521 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3522 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3523 mainShapeOld1->_is_equivalent( oldShape ));
3526 //================================================================================
3528 * \brief Return shape type by shape ID
3530 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3532 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3533 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3534 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3537 //================================================================================
3539 * \brief Store a source sub-shape for which a counterpart not found and
3540 * a smesh object invalid due to that
3542 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3543 SALOMEDS::SObject_wrap smeshSO )
3545 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3546 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3548 CORBA::String_var smeshEntry = smeshSO->GetID();
3549 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3553 //================================================================================
3555 * \brief Store a source sub-shape for which a counterpart not found and
3556 * a smesh object invalid due to that
3558 void AddInvalid( std::string geomEntry,
3559 SALOMEDS::SObject_wrap smeshSO )
3561 if ( !geomEntry.empty() )
3563 CORBA::String_var smeshEntry = smeshSO->GetID();
3564 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3568 //================================================================================
3570 * \brief Store a source sub-shape for which a counterpart not found and
3571 * a smesh object invalid due to that
3573 void AddInvalid( int oldGeomID,
3574 SALOMEDS::SObject_wrap smeshSO )
3576 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3577 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3580 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3581 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3583 SMESH_Comment geomName( typeName[ shapeType ]);
3584 geomName << " #" << oldGeomID;
3586 CORBA::String_var smeshEntry = smeshSO->GetID();
3587 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3590 //================================================================================
3592 * \brief Return entries of a source sub-shape for which a counterpart not found and
3593 * of smesh objects invalid due to that
3595 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3596 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3599 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3600 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3602 nbSO += 1 + entry2entrySet->second.size();
3604 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3605 theInvalidEntries->length ( nbSO );
3606 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3608 entry2entrySet = myInvalidMap.begin();
3609 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3611 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3613 std::set< std::string > & entrySet = entry2entrySet->second;
3614 std::set< std::string >::iterator entry = entrySet.begin();
3615 for ( ; entry != entrySet.end(); ++entry )
3617 theInvalidEntries[ iEntry++ ] = entry->c_str();
3619 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3620 if ( !so->_is_nil() )
3621 theInvalidMeshSObjects[ iSO++ ] = so;
3626 }; // struct ShapeMapper
3628 //================================================================================
3630 * \brief Append an item to a CORBA sequence
3632 template < class CORBA_seq, class ITEM >
3633 void append( CORBA_seq& seq, ITEM item )
3635 if ( !CORBA::is_nil( item ))
3637 seq->length( 1 + seq->length() );
3638 seq[ seq->length() - 1 ] = item;
3641 } // namespace // utils for CopyMeshWithGeom()
3643 //================================================================================
3645 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3646 * \param [in] sourceMesh - a mesh to copy
3647 * \param [in] newGeometry - a new geometry
3648 * \param [in] toCopyGroups - to create groups in the new mesh
3649 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3650 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3651 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3652 * \param [out] newMesh - return a new mesh
3653 * \param [out] newGroups - return new groups
3654 * \param [out] newSubmeshes - return new sub-meshes
3655 * \param [out] newHypotheses - return new algorithms and hypotheses
3656 * \param [out] invalidEntries - return study entries of objects whose
3657 * counterparts are not found in the newGeometry, followed by entries
3658 * of mesh sub-objects that are invalid because they depend on a not found
3659 * preceding sub-shape
3660 * \return CORBA::Boolean - is a success
3662 //================================================================================
3664 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3665 GEOM::GEOM_Object_ptr theNewGeometry,
3666 const char* theMeshName,
3667 CORBA::Boolean theToCopyGroups,
3668 CORBA::Boolean theToReuseHypotheses,
3669 CORBA::Boolean theToCopyElements,
3670 SMESH::SMESH_Mesh_out theNewMesh,
3671 SMESH::ListOfGroups_out theNewGroups,
3672 SMESH::submesh_array_out theNewSubmeshes,
3673 SMESH::ListOfHypothesis_out theNewHypotheses,
3674 SMESH::string_array_out theInvalidEntries)
3675 throw ( SALOME::SALOME_Exception )
3677 if ( CORBA::is_nil( theSourceMesh ) ||
3678 CORBA::is_nil( theNewGeometry ))
3679 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3681 if ( !theSourceMesh->HasShapeToMesh() )
3682 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3687 TPythonDump pyDump; // prevent dump from CreateMesh()
3689 theNewMesh = CreateMesh( theNewGeometry );
3690 theNewGroups = new SMESH::ListOfGroups();
3691 theNewSubmeshes = new SMESH::submesh_array();
3692 theNewHypotheses = new SMESH::ListOfHypothesis();
3693 theInvalidEntries = new SMESH::string_array();
3695 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3697 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3698 GEOM::GEOM_Object_var geom, newGeom;
3699 SALOMEDS::SObject_wrap so;
3701 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3702 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3705 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3707 // treat hypotheses of mesh and sub-meshes
3708 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3709 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3711 bool isSubMesh = ( iSM < smList->length() );
3714 // create a new sub-mesh
3715 SMESH::SMESH_subMesh_var newSM;
3716 geom = smList[iSM]->GetSubShape();
3717 so = ObjectToSObject( smList[iSM] );
3718 CORBA::String_var name;
3719 if ( !so->_is_nil() )
3720 name = so->GetName();
3721 newGeom = shapeMapper.FindNew( geom );
3722 if ( newGeom->_is_nil() )
3724 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3725 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3730 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3732 append( theNewSubmeshes, newSM );
3734 if ( newGeom->_is_nil() )
3735 continue; // don't assign hypotheses
3739 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3741 so = ObjectToSObject( theNewMesh );
3742 SetName( so, theMeshName, "Mesh" );
3745 // assign hypotheses
3746 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3747 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3749 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3750 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3752 // get geometry hyp depends on
3753 std::vector< std::string > entryArray;
3754 std::vector< int > subIDArray;
3755 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3757 if ( !theToReuseHypotheses || dependsOnGeom )
3759 // create a new hypothesis
3760 CORBA::String_var type = hyp->GetName();
3761 CORBA::String_var lib = hyp->GetLibName();
3762 CORBA::String_var data = hyp_i->SaveTo();
3765 hyp = CreateHypothesis( type, lib );
3766 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3767 hyp_i->LoadFrom( data.in() );
3768 append( theNewHypotheses, hyp );
3772 // update geometry hyp depends on
3773 if ( dependsOnGeom )
3775 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3777 if ( !entryArray[ iGeo ].empty() )
3779 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3780 if ( newEntry.empty() )
3783 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3784 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3786 entryArray[ iGeo ] = newEntry;
3789 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3791 if ( subIDArray[ iGeo ] > 0 )
3793 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3797 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3798 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3800 subIDArray[ iGeo ] = newID;
3803 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3807 CORBA::String_var errorText;
3808 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3809 if ( errorText.in()[0] )
3812 } // loop on hypotheses
3813 } // loop on sub-meshes and mesh
3816 // copy mesh elements, keeping IDs
3817 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3818 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3820 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3821 ::SMESH_MeshEditor::ElemFeatures elemData;
3823 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3824 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3825 /*vertexLast=*/false);
3826 while ( srcSMIt->more() )
3828 SMESH_subMesh* srcSM = srcSMIt->next();
3829 if ( srcSM->IsEmpty() )
3830 continue; // not yet computed
3831 int newID = shapeMapper.FindNewNotChanged( srcSM );
3835 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3836 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3837 while ( nIt->more() )
3839 SMESH_NodeXYZ node( nIt->next() );
3840 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3842 const SMDS_PositionPtr pos = node->GetPosition();
3843 const double* uv = pos->GetParameters();
3844 switch ( pos->GetTypeOfPosition() )
3846 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3847 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3848 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3849 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3853 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3854 while( eIt->more() )
3856 const SMDS_MeshElement* e = eIt->next();
3857 elemData.Init( e, /*basicOnly=*/false );
3858 elemData.SetID( e->GetID() );
3859 elemData.myNodes.resize( e->NbNodes() );
3860 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3862 for ( iN = 0; nnIt->more(); ++iN )
3864 const SMDS_MeshNode* srcNode = nnIt->next();
3865 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3866 if ( !elemData.myNodes[ iN ])
3869 if ( iN == elemData.myNodes.size() )
3870 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3871 newMeshDS->SetMeshElementOnShape( newElem, newID );
3873 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3874 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3877 newMeshDS->Modified();
3883 TStr2StrMap old2newGroupMap;
3885 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3887 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3888 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3889 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3891 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3892 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3893 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3895 CORBA::String_var name = groups[ i ]->GetName();
3896 SMESH::ElementType elemType = groups[ i ]->GetType();
3898 SMESH::SMESH_GroupBase_var newGroup;
3900 if ( !stdlGroup->_is_nil() )
3902 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3904 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3905 const bool isElem = ( elemType != SMESH::NODE );
3906 CORBA::ULong iE = 0;
3907 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3908 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3910 if ( iE < elemIDs->length() )
3912 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3913 stdlGroup->Add( elemIDs );
3914 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3918 else if ( !geomGroup->_is_nil() )
3920 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3921 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3922 if ( newGeom->_is_nil() )
3924 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3925 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3930 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3933 else if ( !fltrGroup->_is_nil() )
3935 // replace geometry in a filter
3936 SMESH::Filter_var filter = fltrGroup->GetFilter();
3937 SMESH::Filter::Criteria_var criteria;
3938 filter->GetCriteria( criteria.out() );
3940 bool isMissingGroup = false;
3941 std::vector< std::string > badEntries;
3943 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3945 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3946 switch ( criteria[ iCr ].Type )
3948 case SMESH::FT_BelongToMeshGroup:
3950 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3951 btgg->SetGroupID( thresholdID );
3952 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3953 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3954 if ( refGroupSO->_is_nil() )
3956 CORBA::String_var refID = refGroupSO->GetID();
3957 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3958 if ( o2nID == old2newGroupMap.end() )
3960 isMissingGroup = true; // corresponding new group not yet created
3963 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3965 if ( o2nID->second.empty() ) // new referred group is invalid
3966 badEntries.push_back( refID.in() );
3969 case SMESH::FT_BelongToGeom:
3970 case SMESH::FT_BelongToPlane:
3971 case SMESH::FT_BelongToCylinder:
3972 case SMESH::FT_BelongToGenSurface:
3973 case SMESH::FT_LyingOnGeom:
3975 std::string newID = shapeMapper.FindNew( thresholdID );
3976 criteria[ iCr ].ThresholdID = newID.c_str();
3977 if ( newID.empty() )
3978 badEntries.push_back( thresholdID );
3981 case SMESH::FT_ConnectedElements:
3983 if ( thresholdID && thresholdID[0] )
3985 std::string newID = shapeMapper.FindNew( thresholdID );
3986 criteria[ iCr ].ThresholdID = newID.c_str();
3987 if ( newID.empty() )
3988 badEntries.push_back( thresholdID );
3994 } // loop on criteria
3996 if ( isMissingGroup && i < nbGroups )
3998 // to treat the group again
3999 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
4003 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
4004 newFilter->SetCriteria( criteria );
4006 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
4007 newFilter->UnRegister();
4009 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4010 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
4011 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
4013 if ( isMissingGroup ) // all groups treated but a referred groups still not found
4015 invalidSObjects.push_back( ObjectToSObject( newGroup ));
4018 if ( !badEntries.empty() )
4021 } // treat a group on filter
4023 append( theNewGroups, newGroup );
4025 // fill old2newGroupMap
4026 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
4027 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
4028 if ( !srcSO->_is_nil() )
4030 CORBA::String_var srcID, newID("");
4031 srcID = srcSO->GetID();
4032 if ( !newSO->_is_nil() )
4033 newID = newSO->GetID();
4034 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
4035 std::string( newID.in() )));
4038 if ( newGroup->_is_nil() )
4043 newMeshDS->CompactMesh();
4046 if ( !theMeshName || !theMeshName[0] )
4048 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
4049 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
4050 CORBA::String_var oldName = soOld->GetName();
4051 SetName( soNew, oldName.in(), "Mesh" );
4053 // mark invalid objects
4054 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
4056 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4057 highLightInvalid( invalidSObjects[i].in(), true );
4060 << theNewMesh << ", "
4061 << theNewGroups << ", "
4062 << *theNewSubmeshes.ptr() << ", "
4063 << *theNewHypotheses.ptr() << ", "
4064 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4065 << theSourceMesh << ", "
4066 << theNewGeometry << ", "
4067 << "'" << theMeshName << "', "
4068 << theToCopyGroups << ", "
4069 << theToReuseHypotheses << ", "
4070 << theToCopyElements << " )";
4072 SMESH_CATCH( SMESH::throwCorbaException );
4077 //================================================================================
4079 * \brief Get version of MED format being used.
4081 //================================================================================
4083 char* SMESH_Gen_i::GetMEDFileVersion()
4085 MED::TInt majeur, mineur, release;
4086 majeur = mineur = release = 0;
4087 MED::GetVersionRelease(majeur, mineur, release);
4088 std::ostringstream version;
4089 version << majeur << "." << mineur << "." << release;
4090 return CORBA::string_dup( version.str().c_str() );
4093 //================================================================================
4095 * SMESH_Gen_i::GetMEDVersion
4097 * Get MED version of the file by its name
4099 //================================================================================
4100 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4102 std::string version = MED::GetMEDVersion( theFileName );
4103 return CORBA::string_dup( version.c_str() );
4106 //================================================================================
4108 * SMESH_Gen_i::CheckCompatibility
4110 * Check compatibility of file with MED format being used, read only.
4112 //================================================================================
4113 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4115 return MED::CheckCompatibility( theFileName );
4118 //================================================================================
4120 * SMESH_Gen_i::CheckWriteCompatibility
4122 * Check compatibility of file with MED format being used, for append on write.
4124 //================================================================================
4125 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4127 return MED::CheckCompatibility( theFileName, true );
4130 //================================================================================
4132 * SMESH_Gen_i::GetMeshNames
4134 * Get names of meshes defined in file with the specified name
4136 //================================================================================
4137 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4139 //MESSAGE("GetMeshNames " << theFileName);
4140 SMESH::string_array_var aResult = new SMESH::string_array();
4141 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4143 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4144 //MESSAGE("---" << aNbMeshes);
4146 aResult->length( aNbMeshes );
4147 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4148 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4149 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4152 return aResult._retn();
4155 //=============================================================================
4159 * Save SMESH module's data
4161 //=============================================================================
4162 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4167 Kernel_Utils::Localizer loc;
4169 if (!myStudyContext)
4172 // Store study contents as a set of python commands
4175 SALOMEDS::Study_var aStudy = getStudyServant();
4177 // Declare a byte stream
4178 SALOMEDS::TMPFile_var aStreamFile;
4180 // Obtain a temporary dir
4181 TCollection_AsciiString tmpDir =
4182 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4184 // Create a sequence of files processed
4185 SALOMEDS_Tool::ListOfFiles aFileSeq;
4186 aFileSeq.reserve( NUM_TMP_FILES );
4188 TCollection_AsciiString aStudyName( "" );
4190 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4192 // Set names of temporary files
4193 TCollection_AsciiString filename =
4194 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4195 TCollection_AsciiString meshfile =
4196 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4197 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4198 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4199 filename = tmpDir + filename;
4200 meshfile = tmpDir + meshfile;
4203 HDFdataset* aDataset;
4204 HDFgroup* aTopGroup;
4206 HDFgroup* aSubGroup;
4207 HDFgroup* aSubSubGroup;
4208 hdf_size aSize[ 1 ];
4211 //Remove the files if they exist: BugID: 11225
4212 #ifndef WIN32 /* unix functionality */
4213 TCollection_AsciiString cmd("rm -f \"");
4215 TCollection_AsciiString cmd("del /F \"");
4225 system(cmd.ToCString());
4227 // MED writer to be used by storage process
4228 DriverMED_W_SMESHDS_Mesh myWriter;
4229 myWriter.SetFile( meshfile.ToCString() );
4232 // SetStoreName() to groups before storing hypotheses to let them refer to
4233 // groups using "store name", which is "Group <group_persistent_id>"
4235 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4236 for ( ; itBig->More(); itBig->Next() ) {
4237 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4238 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4239 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4240 if ( !CORBA::is_nil( anObject ) ) {
4241 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4242 if ( !myMesh->_is_nil() ) {
4243 myMesh->Load(); // load from study file if not yet done
4244 TPythonDump pd; // not to dump GetGroups()
4245 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4246 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4248 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4251 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4252 int anId = myStudyContext->findId( string( objStr.in() ) );
4254 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4255 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4256 aGrpBaseDS->SetStoreName( grpName );
4266 // ---> create HDF file
4267 aFile = new HDFfile( (char*) filename.ToCString() );
4268 aFile->CreateOnDisk();
4270 // --> iterator for top-level objects
4271 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4272 for ( ; itBig->More(); itBig->Next() ) {
4273 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4275 // --> hypotheses root branch (only one for the study)
4276 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4277 // create hypotheses root HDF group
4278 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4279 aTopGroup->CreateOnDisk();
4281 // iterator for all hypotheses
4282 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4283 for ( ; it->More(); it->Next() ) {
4284 SALOMEDS::SObject_wrap mySObject = it->Value();
4285 CORBA::Object_var anObject = SObjectToObject( mySObject );
4286 if ( !CORBA::is_nil( anObject ) ) {
4287 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4288 if ( !myHyp->_is_nil() ) {
4289 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4291 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4292 std::string hypname = hn.in();
4293 std::string libname = ln.in();
4295 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4296 // WIN32 and ".so" for X-system) must be deleted
4297 int libname_len = libname.length();
4299 if( libname_len > 4 )
4300 libname.resize( libname_len - 4 );
4302 // PAL17753 (Regression: missing hypothesis in restored study)
4303 // "lib" also should be removed from the beginning
4304 //if( libname_len > 3 )
4305 //libname.resize( libname_len - 3 );
4306 if( libname_len > 6 )
4307 libname = libname.substr( 3, libname_len - 3 - 3 );
4309 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4310 CORBA::String_var hypdata = myImpl->SaveTo();
4311 int id = myStudyContext->findId( string( objStr.in() ));
4313 // for each hypothesis create HDF group basing on its id
4314 char hypGrpName[30];
4315 sprintf( hypGrpName, "Hypothesis %d", id );
4316 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4317 aGroup->CreateOnDisk();
4318 // --> type name of hypothesis
4319 aSize[ 0 ] = hypname.length() + 1;
4320 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4321 aDataset->CreateOnDisk();
4322 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4323 aDataset->CloseOnDisk();
4324 // --> server plugin library name of hypothesis
4325 aSize[ 0 ] = libname.length() + 1;
4326 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4327 aDataset->CreateOnDisk();
4328 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4329 aDataset->CloseOnDisk();
4330 // --> persistent data of hypothesis
4331 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4332 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4333 aDataset->CreateOnDisk();
4334 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4335 aDataset->CloseOnDisk();
4336 // close hypothesis HDF group
4337 aGroup->CloseOnDisk();
4342 // close hypotheses root HDF group
4343 aTopGroup->CloseOnDisk();
4345 // --> algorithms root branch (only one for the study)
4346 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4347 // create algorithms root HDF group
4348 aTopGroup = new HDFgroup( "Algorithms", aFile );
4349 aTopGroup->CreateOnDisk();
4351 // iterator for all algorithms
4352 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4353 for ( ; it->More(); it->Next() ) {
4354 SALOMEDS::SObject_wrap mySObject = it->Value();
4355 CORBA::Object_var anObject = SObjectToObject( mySObject );
4356 if ( !CORBA::is_nil( anObject ) ) {
4357 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4358 if ( !myHyp->_is_nil() ) {
4359 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4361 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4362 std::string hypname = hn.in();
4363 std::string libname = ln.in();
4365 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4366 // WIN32 and ".so" for X-system) must be deleted
4367 int libname_len = libname.length();
4369 if( libname_len > 4 )
4370 libname.resize( libname_len - 4 );
4372 // PAL17753 (Regression: missing hypothesis in restored study)
4373 // "lib" also should be removed from the beginning
4374 //if( libname_len > 3 )
4375 //libname.resize( libname_len - 3 );
4376 if( libname_len > 6 )
4377 libname = libname.substr( 3, libname_len - 3 - 3 );
4379 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4380 CORBA::String_var hypdata = myImpl->SaveTo();
4381 int id = myStudyContext->findId( string( objStr.in() ) );
4383 // for each algorithm create HDF group basing on its id
4384 char hypGrpName[30];
4385 sprintf( hypGrpName, "Algorithm %d", id );
4386 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4387 aGroup->CreateOnDisk();
4388 // --> type name of algorithm
4389 aSize[0] = hypname.length() + 1;
4390 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4391 aDataset->CreateOnDisk();
4392 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4393 aDataset->CloseOnDisk();
4394 // --> server plugin library name of hypothesis
4395 aSize[0] = libname.length() + 1;
4396 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4397 aDataset->CreateOnDisk();
4398 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4399 aDataset->CloseOnDisk();
4400 // --> persistent data of algorithm
4401 aSize[0] = strlen( hypdata.in() ) + 1;
4402 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4403 aDataset->CreateOnDisk();
4404 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4405 aDataset->CloseOnDisk();
4406 // close algorithm HDF group
4407 aGroup->CloseOnDisk();
4412 // close algorithms root HDF group
4413 aTopGroup->CloseOnDisk();
4415 // --> mesh objects roots branches
4416 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4417 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4418 if ( !CORBA::is_nil( anObject ) ) {
4419 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4420 if ( !myMesh->_is_nil() ) {
4421 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4423 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4424 int id = myStudyContext->findId( string( objStr.in() ) );
4425 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4426 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4427 bool hasShape = myLocMesh.HasShapeToMesh();
4429 // for each mesh open the HDF group basing on its id
4430 char meshGrpName[ 30 ];
4431 sprintf( meshGrpName, "Mesh %d", id );
4432 aTopGroup = new HDFgroup( meshGrpName, aFile );
4433 aTopGroup->CreateOnDisk();
4435 // --> put dataset to hdf file which is a flag that mesh has data
4436 string strHasData = "0";
4437 // check if the mesh is not empty
4438 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4439 // write mesh data to med file
4440 myWriter.SetMesh( mySMESHDSMesh );
4441 myWriter.SetMeshId( id );
4444 aSize[ 0 ] = strHasData.length() + 1;
4445 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4446 aDataset->CreateOnDisk();
4447 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4448 aDataset->CloseOnDisk();
4451 // for each mesh open the HDF group basing on its auto color parameter
4452 char meshAutoColorName[ 30 ];
4453 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4455 anAutoColor[0] = myImpl->GetAutoColor();
4457 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4458 aDataset->CreateOnDisk();
4459 aDataset->WriteOnDisk( anAutoColor );
4460 aDataset->CloseOnDisk();
4462 // issue 0020693. Store _isModified flag
4463 int isModified = myLocMesh.GetIsModified();
4465 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4466 aDataset->CreateOnDisk();
4467 aDataset->WriteOnDisk( &isModified );
4468 aDataset->CloseOnDisk();
4470 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4471 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4473 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4474 aDataset->CreateOnDisk();
4475 aDataset->WriteOnDisk( &meshPersistentId );
4476 aDataset->CloseOnDisk();
4478 // Store SMESH_Mesh_i::_mainShapeTick
4479 int shapeTick = myImpl->MainShapeTick();
4481 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4482 aDataset->CreateOnDisk();
4483 aDataset->WriteOnDisk( &shapeTick );
4484 aDataset->CloseOnDisk();
4486 // write reference on a shape if exists
4487 SALOMEDS::SObject_wrap myRef;
4488 bool shapeRefFound = false;
4489 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4491 SALOMEDS::SObject_wrap myShape;
4492 bool ok = myRef->ReferencedObject( myShape.inout() );
4494 CORBA::Object_var shapeObj = myShape->GetObject();
4495 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4496 CORBA::String_var myRefOnObject = myShape->GetID();
4497 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4498 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4499 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4500 aDataset->CreateOnDisk();
4501 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4502 aDataset->CloseOnDisk();
4508 std::string info = myImpl->FileInfoToString();
4509 if ( !info.empty() )
4511 aSize[ 0 ] = info.size();
4512 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4513 aDataset->CreateOnDisk();
4514 aDataset->WriteOnDisk( (char*) info.data() );
4515 aDataset->CloseOnDisk();
4518 // write applied hypotheses if exist
4519 SALOMEDS::SObject_wrap myHypBranch;
4520 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4521 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4522 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4524 if ( found && (shapeRefFound || !hasShape) ) {
4525 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4526 aGroup->CreateOnDisk();
4528 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4530 for ( ; it->More(); it->Next() ) {
4531 SALOMEDS::SObject_wrap mySObject = it->Value();
4532 SALOMEDS::SObject_wrap myRefOnHyp;
4533 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4535 // san - it is impossible to recover applied hypotheses
4536 // using their entries within Load() method,
4537 // for there are no AttributeIORs in the study when Load() is working.
4538 // Hence, it is better to store persistent IDs of hypotheses as references to them
4540 //string myRefOnObject = myRefOnHyp->GetID();
4541 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4542 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4543 int id = myStudyContext->findId( string( objStr.in() ) );
4544 //if ( myRefOnObject.length() > 0 ) {
4545 //aSize[ 0 ] = myRefOnObject.length() + 1;
4546 char hypName[ 30 ], hypId[ 30 ];
4547 sprintf( hypName, "Hyp %d", ++hypNb );
4548 sprintf( hypId, "%d", id );
4549 aSize[ 0 ] = strlen( hypId ) + 1;
4550 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4551 aDataset->CreateOnDisk();
4552 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4553 aDataset->WriteOnDisk( hypId );
4554 aDataset->CloseOnDisk();
4558 aGroup->CloseOnDisk();
4561 // write applied algorithms if exist
4562 SALOMEDS::SObject_wrap myAlgoBranch;
4563 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4564 myAlgoBranch.inout() );
4565 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4566 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4568 if ( found && (shapeRefFound || !hasShape)) {
4569 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4570 aGroup->CreateOnDisk();
4572 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4574 for ( ; it->More(); it->Next() ) {
4575 SALOMEDS::SObject_wrap mySObject = it->Value();
4576 SALOMEDS::SObject_wrap myRefOnAlgo;
4577 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4579 // san - it is impossible to recover applied algorithms
4580 // using their entries within Load() method,
4581 // for there are no AttributeIORs in the study when Load() is working.
4582 // Hence, it is better to store persistent IDs of algorithms as references to them
4584 //string myRefOnObject = myRefOnAlgo->GetID();
4585 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4586 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4587 int id = myStudyContext->findId( string( objStr.in() ) );
4588 //if ( myRefOnObject.length() > 0 ) {
4589 //aSize[ 0 ] = myRefOnObject.length() + 1;
4590 char algoName[ 30 ], algoId[ 30 ];
4591 sprintf( algoName, "Algo %d", ++algoNb );
4592 sprintf( algoId, "%d", id );
4593 aSize[ 0 ] = strlen( algoId ) + 1;
4594 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4595 aDataset->CreateOnDisk();
4596 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4597 aDataset->WriteOnDisk( algoId );
4598 aDataset->CloseOnDisk();
4602 aGroup->CloseOnDisk();
4605 // --> submesh objects sub-branches
4607 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4608 SALOMEDS::SObject_wrap mySubmeshBranch;
4609 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4611 if ( found ) // check if there is shape reference in submeshes
4613 bool hasShapeRef = false;
4614 SALOMEDS::ChildIterator_wrap itSM =
4615 aStudy->NewChildIterator( mySubmeshBranch );
4616 for ( ; itSM->More(); itSM->Next() ) {
4617 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4618 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4619 mySubRef->ReferencedObject( myShape.inout() );
4620 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4623 { // remove one submesh
4624 if ( shapeRefFound )
4625 { // unassign hypothesis
4626 SMESH::SMESH_subMesh_var mySubMesh =
4627 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4628 if ( !mySubMesh->_is_nil() ) {
4629 int shapeID = mySubMesh->GetId();
4630 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4631 const list<const SMESHDS_Hypothesis*>& hypList =
4632 mySMESHDSMesh->GetHypothesis( S );
4633 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4634 while ( hyp != hypList.end() ) {
4635 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4636 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4640 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4642 } // loop on submeshes of a type
4643 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4644 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4647 } // end check if there is shape reference in submeshes
4649 char name_meshgroup[ 30 ];
4650 if ( i == GetSubMeshOnVertexTag() )
4651 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4652 else if ( i == GetSubMeshOnEdgeTag() )
4653 strcpy( name_meshgroup, "SubMeshes On Edge" );
4654 else if ( i == GetSubMeshOnWireTag() )
4655 strcpy( name_meshgroup, "SubMeshes On Wire" );
4656 else if ( i == GetSubMeshOnFaceTag() )
4657 strcpy( name_meshgroup, "SubMeshes On Face" );
4658 else if ( i == GetSubMeshOnShellTag() )
4659 strcpy( name_meshgroup, "SubMeshes On Shell" );
4660 else if ( i == GetSubMeshOnSolidTag() )
4661 strcpy( name_meshgroup, "SubMeshes On Solid" );
4662 else if ( i == GetSubMeshOnCompoundTag() )
4663 strcpy( name_meshgroup, "SubMeshes On Compound" );
4665 // for each type of submeshes create container HDF group
4666 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4667 aGroup->CreateOnDisk();
4669 // iterator for all submeshes of given type
4670 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4671 for ( ; itSM->More(); itSM->Next() ) {
4672 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4673 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4674 if ( !CORBA::is_nil( anSubObject ))
4676 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4677 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4678 int subid = myStudyContext->findId( string( objStr.in() ) );
4680 // for each mesh open the HDF group basing on its id
4681 char submeshGrpName[ 30 ];
4682 sprintf( submeshGrpName, "SubMesh %d", subid );
4683 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4684 aSubGroup->CreateOnDisk();
4686 // write reference on a shape, already checked if it exists
4687 SALOMEDS::SObject_wrap mySubRef, myShape;
4688 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4689 mySubRef->ReferencedObject( myShape.inout() );
4690 string myRefOnObject = myShape->GetID();
4691 if ( myRefOnObject.length() > 0 ) {
4692 aSize[ 0 ] = myRefOnObject.length() + 1;
4693 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4694 aDataset->CreateOnDisk();
4695 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4696 aDataset->CloseOnDisk();
4699 // write applied hypotheses if exist
4700 SALOMEDS::SObject_wrap mySubHypBranch;
4701 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4702 mySubHypBranch.inout() );
4704 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4705 aSubSubGroup->CreateOnDisk();
4707 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4709 for ( ; it->More(); it->Next() ) {
4710 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4711 SALOMEDS::SObject_wrap myRefOnHyp;
4712 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4714 //string myRefOnObject = myRefOnHyp->GetID();
4715 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4716 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4717 int id = myStudyContext->findId( string( objStr.in() ) );
4718 //if ( myRefOnObject.length() > 0 ) {
4719 //aSize[ 0 ] = myRefOnObject.length() + 1;
4720 char hypName[ 30 ], hypId[ 30 ];
4721 sprintf( hypName, "Hyp %d", ++hypNb );
4722 sprintf( hypId, "%d", id );
4723 aSize[ 0 ] = strlen( hypId ) + 1;
4724 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4725 aDataset->CreateOnDisk();
4726 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4727 aDataset->WriteOnDisk( hypId );
4728 aDataset->CloseOnDisk();
4732 aSubSubGroup->CloseOnDisk();
4735 // write applied algorithms if exist
4736 SALOMEDS::SObject_wrap mySubAlgoBranch;
4737 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4738 mySubAlgoBranch.inout() );
4740 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4741 aSubSubGroup->CreateOnDisk();
4743 SALOMEDS::ChildIterator_wrap it =
4744 aStudy->NewChildIterator( mySubAlgoBranch );
4746 for ( ; it->More(); it->Next() ) {
4747 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4748 SALOMEDS::SObject_wrap myRefOnAlgo;
4749 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4751 //string myRefOnObject = myRefOnAlgo->GetID();
4752 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4753 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4754 int id = myStudyContext->findId( string( objStr.in() ) );
4755 //if ( myRefOnObject.length() > 0 ) {
4756 //aSize[ 0 ] = myRefOnObject.length() + 1;
4757 char algoName[ 30 ], algoId[ 30 ];
4758 sprintf( algoName, "Algo %d", ++algoNb );
4759 sprintf( algoId, "%d", id );
4760 aSize[ 0 ] = strlen( algoId ) + 1;
4761 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4762 aDataset->CreateOnDisk();
4763 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4764 aDataset->WriteOnDisk( algoId );
4765 aDataset->CloseOnDisk();
4769 aSubSubGroup->CloseOnDisk();
4771 // close submesh HDF group
4772 aSubGroup->CloseOnDisk();
4775 // close container of submeshes by type HDF group
4776 aGroup->CloseOnDisk();
4779 // All sub-meshes will be stored in MED file
4780 // .. will NOT (PAL 12992)
4781 //if ( shapeRefFound )
4782 //myWriter.AddAllSubMeshes();
4784 // store submesh order if any
4785 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4786 if ( theOrderIds.size() ) {
4787 char order_list[ 30 ];
4788 strcpy( order_list, "Mesh Order" );
4789 // count number of submesh ids
4791 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4792 for ( ; idIt != theOrderIds.end(); idIt++ )
4793 nbIDs += (*idIt).size();
4794 // number of values = number of IDs +
4795 // number of lists (for separators) - 1
4796 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4797 idIt = theOrderIds.begin();
4798 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4799 const TListOfInt& idList = *idIt;
4800 if (idIt != theOrderIds.begin()) // not first list
4801 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4802 // dump submesh ids from current list
4803 TListOfInt::const_iterator id_smId = idList.begin();
4804 for( ; id_smId != idList.end(); id_smId++ )
4805 smIDs[ i++ ] = *id_smId;
4808 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4810 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4811 aDataset->CreateOnDisk();
4812 aDataset->WriteOnDisk( smIDs );
4813 aDataset->CloseOnDisk();
4818 // groups root sub-branch
4819 SALOMEDS::SObject_wrap myGroupsBranch;
4820 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4821 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4823 char name_group[ 30 ];
4824 if ( i == GetNodeGroupsTag() )
4825 strcpy( name_group, "Groups of Nodes" );
4826 else if ( i == GetEdgeGroupsTag() )
4827 strcpy( name_group, "Groups of Edges" );
4828 else if ( i == GetFaceGroupsTag() )
4829 strcpy( name_group, "Groups of Faces" );
4830 else if ( i == GetVolumeGroupsTag() )
4831 strcpy( name_group, "Groups of Volumes" );
4832 else if ( i == Get0DElementsGroupsTag() )
4833 strcpy( name_group, "Groups of 0D Elements" );
4834 else if ( i == GetBallElementsGroupsTag() )
4835 strcpy( name_group, "Groups of Balls" );
4837 aGroup = new HDFgroup( name_group, aTopGroup );
4838 aGroup->CreateOnDisk();
4840 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4841 for ( ; it->More(); it->Next() ) {
4842 SALOMEDS::SObject_wrap mySObject = it->Value();
4843 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4844 if ( !CORBA::is_nil( aSubObject ) ) {
4845 SMESH_GroupBase_i* myGroupImpl =
4846 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4849 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4853 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4854 int anId = myStudyContext->findId( string( objStr.in() ) );
4856 // For each group, create a dataset named "Group <group_persistent_id>"
4857 // and store the group's user name into it
4858 const char* grpName = aGrpBaseDS->GetStoreName();
4859 CORBA::String_var aUserName = myGroupImpl->GetName();
4860 aSize[ 0 ] = strlen( aUserName ) + 1;
4862 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4863 aDataset->CreateOnDisk();
4864 aDataset->WriteOnDisk( aUserName );
4865 aDataset->CloseOnDisk();
4868 // For each group, create a dataset named "Group <group_persistent_id> Color"
4869 // and store the group's color into it
4870 char grpColorName[ 30 ];
4871 sprintf( grpColorName, "ColorGroup %d", anId );
4872 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4874 anRGB[ 0 ] = aColor.R;
4875 anRGB[ 1 ] = aColor.G;
4876 anRGB[ 2 ] = aColor.B;
4878 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4879 aDataset->CreateOnDisk();
4880 aDataset->WriteOnDisk( anRGB );
4881 aDataset->CloseOnDisk();
4883 // Pass SMESHDS_Group to MED writer
4884 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4886 myWriter.AddGroup( aGrpDS );
4888 // write reference on a shape if exists
4889 SMESHDS_GroupOnGeom* aGeomGrp =
4890 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4892 SALOMEDS::SObject_wrap mySubRef, myShape;
4893 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4894 mySubRef->ReferencedObject( myShape.inout() ) &&
4895 !CORBA::is_nil( myShape->GetObject() ))
4897 CORBA::String_var myRefOnObject = myShape->GetID();
4898 if ( myRefOnObject.in()[0] ) {
4899 char aRefName[ 30 ];
4900 sprintf( aRefName, "Ref on shape %d", anId);
4901 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4902 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4903 aDataset->CreateOnDisk();
4904 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4905 aDataset->CloseOnDisk();
4908 else // shape ref is invalid:
4910 // save a group on geometry as ordinary group
4911 myWriter.AddGroup( aGeomGrp );
4914 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4915 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4917 std::string str = aFilterGrp_i->FilterToString();
4918 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4919 aSize[ 0 ] = str.length() + 1;
4920 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4921 aDataset->CreateOnDisk();
4922 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4923 aDataset->CloseOnDisk();
4927 aGroup->CloseOnDisk();
4931 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4933 // Flush current mesh information into MED file
4936 // save info on nb of elements
4937 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4939 // maybe a shape was deleted in the study
4940 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4941 TopoDS_Shape nullShape;
4942 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4945 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4950 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4951 aGroup->CreateOnDisk();
4953 // each element belongs to one or none submesh,
4954 // so for each node/element, we store a submesh ID
4956 // Store submesh IDs
4957 for ( int isNode = 0; isNode < 2; ++isNode )
4959 SMDS_ElemIteratorPtr eIt =
4960 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4961 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4964 std::vector<int> smIDs; smIDs.reserve( nbElems );
4965 while ( eIt->more() )
4966 if ( const SMDS_MeshElement* e = eIt->next())
4967 smIDs.push_back( e->getshapeId() );
4969 aSize[ 0 ] = nbElems;
4970 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4971 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4972 aDataset->CreateOnDisk();
4973 aDataset->WriteOnDisk( & smIDs[0] );
4974 aDataset->CloseOnDisk();
4977 aGroup->CloseOnDisk();
4979 // Store node positions on sub-shapes (SMDS_Position):
4980 // ----------------------------------------------------
4982 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4983 aGroup->CreateOnDisk();
4985 // in aGroup, create 5 datasets to contain:
4986 // "Nodes on Edges" - ID of node on edge
4987 // "Edge positions" - U parameter on node on edge
4988 // "Nodes on Faces" - ID of node on face
4989 // "Face U positions" - U parameter of node on face
4990 // "Face V positions" - V parameter of node on face
4992 // Find out nb of nodes on edges and faces
4993 // Collect corresponding sub-meshes
4994 int nbEdgeNodes = 0, nbFaceNodes = 0;
4995 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4996 // loop on SMESHDS_SubMesh'es
4997 while ( smIt->more() )
4999 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
5000 if ( aSubMesh->IsComplexSubmesh() )
5001 continue; // submesh containing other submeshs
5002 int nbNodes = aSubMesh->NbNodes();
5003 if ( nbNodes == 0 ) continue;
5005 int aShapeID = aSubMesh->GetID();
5006 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
5008 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
5009 // write only SMDS_FacePosition and SMDS_EdgePosition
5010 switch ( aShapeType ) {
5012 nbFaceNodes += nbNodes;
5013 aFaceSM.push_back( aSubMesh );
5016 nbEdgeNodes += nbNodes;
5017 aEdgeSM.push_back( aSubMesh );
5023 // Treat positions on edges or faces
5024 for ( int onFace = 0; onFace < 2; onFace++ )
5026 // Create arrays to store in datasets
5027 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
5028 if (!nbNodes) continue;
5029 int* aNodeIDs = new int [ nbNodes ];
5030 double* aUPos = new double [ nbNodes ];
5031 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
5034 // loop on sub-meshes
5035 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
5036 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
5037 for ( ; itSM != pListSM->end(); itSM++ )
5039 SMESHDS_SubMesh* aSubMesh = (*itSM);
5041 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
5042 // loop on nodes in aSubMesh
5043 while ( itNode->more() )
5046 const SMDS_MeshNode* node = itNode->next();
5047 aNodeIDs [ iNode ] = node->GetID();
5050 const SMDS_PositionPtr pos = node->GetPosition();
5051 if ( onFace ) { // on FACE
5052 SMDS_FacePositionPtr fPos = pos;
5054 aUPos[ iNode ] = fPos->GetUParameter();
5055 aVPos[ iNode ] = fPos->GetVParameter();
5062 SMDS_EdgePositionPtr ePos = pos;
5064 aUPos[ iNode ] = ePos->GetUParameter();
5070 } // loop on nodes in aSubMesh
5071 } // loop on sub-meshes
5076 aSize[ 0 ] = nbNodes;
5078 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5079 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5080 aDataset->CreateOnDisk();
5081 aDataset->WriteOnDisk( aNodeIDs );
5082 aDataset->CloseOnDisk();
5085 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5086 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5087 aDataset->CreateOnDisk();
5088 aDataset->WriteOnDisk( aUPos );
5089 aDataset->CloseOnDisk();
5092 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5093 aDataset->CreateOnDisk();
5094 aDataset->WriteOnDisk( aVPos );
5095 aDataset->CloseOnDisk();
5100 if ( aVPos ) delete [] aVPos;
5102 } // treat positions on edges or faces
5104 // close "Node Positions" group
5105 aGroup->CloseOnDisk();
5107 } // if ( there are submeshes in SMESHDS_Mesh )
5110 // close mesh HDF group
5111 aTopGroup->CloseOnDisk();
5119 aFile->CloseOnDisk();
5122 // Convert temporary files to stream
5123 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5125 // Remove temporary files and directory
5127 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5129 return aStreamFile._retn();
5132 //=============================================================================
5134 * SMESH_Gen_i::SaveASCII
5136 * Save SMESH module's data in ASCII format
5138 //=============================================================================
5140 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5142 bool isMultiFile ) {
5143 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5144 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5145 return aStreamFile._retn();
5147 //after usual saving needs to encipher binary to text string
5148 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5149 int size = aStreamFile.in().length();
5150 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5151 for ( int i = 0; i < size; i++ )
5152 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5154 buffer[size * 3] = '\0';
5156 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5158 return anAsciiStreamFile._retn();
5161 //=============================================================================
5165 * Load SMESH module's data
5167 //=============================================================================
5169 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5170 const SALOMEDS::TMPFile& theStream,
5174 UpdateStudy(); // load geom data
5175 Kernel_Utils::Localizer loc;
5177 SALOMEDS::Study_var aStudy = getStudyServant();
5179 // Get temporary files location
5180 TCollection_AsciiString tmpDir =
5181 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5183 // Convert the stream into sequence of files to process
5184 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5187 TCollection_AsciiString aStudyName( "" );
5188 if ( isMultiFile ) {
5189 CORBA::WString_var url = aStudy->URL();
5190 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5192 // Set names of temporary files
5193 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5194 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5198 HDFdataset* aDataset;
5199 HDFgroup* aTopGroup;
5201 HDFgroup* aSubGroup;
5202 HDFgroup* aSubSubGroup;
5205 // ---> open HDF file
5206 aFile = new HDFfile( (char*) filename.ToCString() );
5208 aFile->OpenOnDisk( HDF_RDONLY );
5210 catch ( HDFexception ) {
5211 INFOS( "Load(): " << filename << " not found!" );
5215 TPythonDump pd; // prevent dump during loading
5217 // DriverMED_R_SMESHDS_Mesh myReader;
5218 // myReader.SetFile( meshfile.ToCString() );
5220 // For PAL13473 ("Repetitive mesh") implementation.
5221 // New dependencies between SMESH objects are established:
5222 // now hypotheses can refer to meshes, shapes and other hypotheses.
5223 // To keep data consistent, the following order of data restoration
5225 // 1. Create hypotheses
5226 // 2. Create all meshes
5227 // 3. Load hypotheses' data
5230 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5231 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5232 list< SMESH::Filter_var > filters;
5234 // get total number of top-level groups
5235 int aNbGroups = aFile->nInternalObjects();
5236 if ( aNbGroups > 0 ) {
5237 // --> in first turn we should read&create hypotheses
5238 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5239 // open hypotheses root HDF group
5240 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5241 aTopGroup->OpenOnDisk();
5243 // get number of hypotheses
5244 int aNbObjects = aTopGroup->nInternalObjects();
5245 for ( int j = 0; j < aNbObjects; j++ ) {
5246 // try to identify hypothesis
5247 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5248 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5250 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5251 // open hypothesis group
5252 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5253 aGroup->OpenOnDisk();
5255 // --> get hypothesis id
5256 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5261 // get number of datasets
5262 int aNbSubObjects = aGroup->nInternalObjects();
5263 for ( int k = 0; k < aNbSubObjects; k++ ) {
5265 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5266 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5267 // --> get hypothesis name
5268 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5269 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5270 aDataset->OpenOnDisk();
5271 size = aDataset->GetSize();
5272 char* hypname_str = new char[ size ];
5273 aDataset->ReadFromDisk( hypname_str );
5274 hypname = string( hypname_str );
5275 delete [] hypname_str;
5276 aDataset->CloseOnDisk();
5278 // --> get hypothesis plugin library name
5279 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5280 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5281 aDataset->OpenOnDisk();
5282 size = aDataset->GetSize();
5283 char* libname_str = new char[ size ];
5284 aDataset->ReadFromDisk( libname_str );
5285 if(MYDEBUG) SCRUTE( libname_str );
5286 libname = string( libname_str );
5287 delete [] libname_str;
5288 aDataset->CloseOnDisk();
5290 // --> get hypothesis data
5291 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5292 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5293 aDataset->OpenOnDisk();
5294 size = aDataset->GetSize();
5295 char* hypdata_str = new char[ size ];
5296 aDataset->ReadFromDisk( hypdata_str );
5297 hypdata = string( hypdata_str );
5298 delete [] hypdata_str;
5299 aDataset->CloseOnDisk();
5302 // close hypothesis HDF group
5303 aGroup->CloseOnDisk();
5305 // --> restore hypothesis from data
5306 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5307 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5308 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5309 SMESH::SMESH_Hypothesis_var myHyp;
5311 try { // protect persistence mechanism against exceptions
5312 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5315 INFOS( "Exception during hypothesis creation" );
5318 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5320 // myImpl->LoadFrom( hypdata.c_str() );
5321 hypDataList.push_back( make_pair( myImpl, hypdata ));
5322 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5323 int newId = myStudyContext->findId( iorString.in() );
5324 myStudyContext->mapOldToNew( id, newId );
5327 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5331 // close hypotheses root HDF group
5332 aTopGroup->CloseOnDisk();
5336 // --> then we should read&create algorithms
5337 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5338 // open algorithms root HDF group
5339 aTopGroup = new HDFgroup( "Algorithms", aFile );
5340 aTopGroup->OpenOnDisk();
5342 // get number of algorithms
5343 int aNbObjects = aTopGroup->nInternalObjects();
5344 for ( int j = 0; j < aNbObjects; j++ ) {
5345 // try to identify algorithm
5346 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5347 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5349 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5350 // open algorithm group
5351 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5352 aGroup->OpenOnDisk();
5354 // --> get algorithm id
5355 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5360 // get number of datasets
5361 int aNbSubObjects = aGroup->nInternalObjects();
5362 for ( int k = 0; k < aNbSubObjects; k++ ) {
5364 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5365 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5366 // --> get algorithm name
5367 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5368 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5369 aDataset->OpenOnDisk();
5370 size = aDataset->GetSize();
5371 char* hypname_str = new char[ size ];
5372 aDataset->ReadFromDisk( hypname_str );
5373 hypname = string( hypname_str );
5374 delete [] hypname_str;
5375 aDataset->CloseOnDisk();
5377 // --> get algorithm plugin library name
5378 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5379 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5380 aDataset->OpenOnDisk();
5381 size = aDataset->GetSize();
5382 char* libname_str = new char[ size ];
5383 aDataset->ReadFromDisk( libname_str );
5384 if(MYDEBUG) SCRUTE( libname_str );
5385 libname = string( libname_str );
5386 delete [] libname_str;
5387 aDataset->CloseOnDisk();
5389 // --> get algorithm data
5390 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5391 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5392 aDataset->OpenOnDisk();
5393 size = aDataset->GetSize();
5394 char* hypdata_str = new char[ size ];
5395 aDataset->ReadFromDisk( hypdata_str );
5396 if(MYDEBUG) SCRUTE( hypdata_str );
5397 hypdata = string( hypdata_str );
5398 delete [] hypdata_str;
5399 aDataset->CloseOnDisk();
5402 // close algorithm HDF group
5403 aGroup->CloseOnDisk();
5405 // --> restore algorithm from data
5406 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5407 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5408 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5409 SMESH::SMESH_Hypothesis_var myHyp;
5411 try { // protect persistence mechanism against exceptions
5412 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5414 catch( SALOME::SALOME_Exception& ex )
5416 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5419 INFOS( "Exception during hypothesis creation" );
5422 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5424 //myImpl->LoadFrom( hypdata.c_str() );
5425 hypDataList.push_back( make_pair( myImpl, hypdata ));
5426 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5427 int newId = myStudyContext->findId( iorString.in() );
5428 myStudyContext->mapOldToNew( id, newId );
5431 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5435 // close algorithms root HDF group
5436 aTopGroup->CloseOnDisk();
5440 // --> the rest groups should be meshes
5441 for ( int i = 0; i < aNbGroups; i++ ) {
5442 // identify next group
5443 char meshName[ HDF_NAME_MAX_LEN+1 ];
5444 aFile->InternalObjectIndentify( i, meshName );
5446 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5448 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5452 // open mesh HDF group
5453 aTopGroup = new HDFgroup( meshName, aFile );
5454 aTopGroup->OpenOnDisk();
5456 // get number of child HDF objects
5457 int aNbObjects = aTopGroup->nInternalObjects();
5458 if ( aNbObjects > 0 ) {
5460 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5461 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5462 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5463 if ( !myNewMeshImpl )
5465 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5467 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5468 int newId = myStudyContext->findId( iorString.in() );
5469 myStudyContext->mapOldToNew( id, newId );
5472 // try to read and set auto color flag
5473 char aMeshAutoColorName[ 30 ];
5474 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5475 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5477 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5478 aDataset->OpenOnDisk();
5479 size = aDataset->GetSize();
5480 int* anAutoColor = new int[ size ];
5481 aDataset->ReadFromDisk( anAutoColor );
5482 aDataset->CloseOnDisk();
5483 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5484 delete [] anAutoColor;
5487 // try to read and set reference to shape
5488 GEOM::GEOM_Object_var aShapeObject;
5489 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5490 // load mesh "Ref on shape" - it's an entry to SObject
5491 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5492 aDataset->OpenOnDisk();
5493 size = aDataset->GetSize();
5494 char* refFromFile = new char[ size ];
5495 aDataset->ReadFromDisk( refFromFile );
5496 aDataset->CloseOnDisk();
5497 if ( strlen( refFromFile ) > 0 ) {
5498 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5499 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5500 if ( !CORBA::is_nil( shapeObject ) ) {
5501 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5502 if ( !aShapeObject->_is_nil() )
5503 myNewMeshImpl->SetShape( aShapeObject );
5506 delete [] refFromFile;
5509 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5510 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5512 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5513 aDataset->OpenOnDisk();
5514 size = aDataset->GetSize();
5515 int* meshPersistentId = new int[ size ];
5516 aDataset->ReadFromDisk( meshPersistentId );
5517 aDataset->CloseOnDisk();
5518 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5519 delete [] meshPersistentId;
5522 // Restore SMESH_Mesh_i::_mainShapeTick
5523 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5525 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5526 aDataset->OpenOnDisk();
5527 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5528 aDataset->ReadFromDisk( shapeTick );
5529 aDataset->CloseOnDisk();
5532 // Restore file info
5533 if ( aTopGroup->ExistInternalObject( "file info" ))
5535 aDataset = new HDFdataset( "file info", aTopGroup );
5536 aDataset->OpenOnDisk();
5537 size = aDataset->GetSize();
5538 std::string info( size, ' ');
5539 aDataset->ReadFromDisk( (char*) info.data() );
5540 aDataset->CloseOnDisk();
5541 myNewMeshImpl->FileInfoFromString( info );
5547 // As all object that can be referred by hypothesis are created,
5548 // we can restore hypothesis data
5550 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5551 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5553 SMESH_Hypothesis_i* hyp = hyp_data->first;
5554 string & data = hyp_data->second;
5555 hyp->LoadFrom( data.c_str() );
5558 // Restore the rest mesh data
5560 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5561 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5563 aTopGroup = meshi_group->second;
5564 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5565 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5566 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5568 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5569 bool hasData = false;
5572 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5573 int newId = myStudyContext->findId( iorString.in() );
5574 int meshOldId = myStudyContext->getOldId( newId );
5576 // try to find mesh data dataset
5577 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5578 // load mesh "has data" flag
5579 aDataset = new HDFdataset( "Has data", aTopGroup );
5580 aDataset->OpenOnDisk();
5581 size = aDataset->GetSize();
5582 char* strHasData = new char[ size ];
5583 aDataset->ReadFromDisk( strHasData );
5584 aDataset->CloseOnDisk();
5585 if ( strcmp( strHasData, "1") == 0 ) {
5588 delete [] strHasData;
5591 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5592 // nodes and elements are not yet put into sub-meshes)
5593 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5594 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5595 aGroup->OpenOnDisk();
5596 // get number of applied algorithms
5597 int aNbSubObjects = aGroup->nInternalObjects();
5598 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5599 for ( int j = 0; j < aNbSubObjects; j++ ) {
5600 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5601 aGroup->InternalObjectIndentify( j, name_dataset );
5602 // check if it is an algorithm
5603 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5604 aDataset = new HDFdataset( name_dataset, aGroup );
5605 aDataset->OpenOnDisk();
5606 size = aDataset->GetSize();
5607 char* refFromFile = new char[ size ];
5608 aDataset->ReadFromDisk( refFromFile );
5609 aDataset->CloseOnDisk();
5610 // san - it is impossible to recover applied algorithms using their entries within Load() method
5611 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5612 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5613 int id = atoi( refFromFile );
5614 delete [] refFromFile;
5615 string anIOR = myStudyContext->getIORbyOldId( id );
5616 if ( !anIOR.empty() ) {
5617 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5618 if ( !CORBA::is_nil( hypObject ) ) {
5619 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5620 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5621 || !myNewMeshImpl->HasShapeToMesh()) )
5622 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5627 aGroup->CloseOnDisk();
5630 // try to get applied hypotheses
5631 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5632 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5633 aGroup->OpenOnDisk();
5634 // get number of applied hypotheses
5635 int aNbSubObjects = aGroup->nInternalObjects();
5636 for ( int j = 0; j < aNbSubObjects; j++ ) {
5637 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5638 aGroup->InternalObjectIndentify( j, name_dataset );
5639 // check if it is a hypothesis
5640 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5641 aDataset = new HDFdataset( name_dataset, aGroup );
5642 aDataset->OpenOnDisk();
5643 size = aDataset->GetSize();
5644 char* refFromFile = new char[ size ];
5645 aDataset->ReadFromDisk( refFromFile );
5646 aDataset->CloseOnDisk();
5647 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5648 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5649 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5650 int id = atoi( refFromFile );
5651 delete [] refFromFile;
5652 string anIOR = myStudyContext->getIORbyOldId( id );
5653 if ( !anIOR.empty() ) {
5654 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5655 if ( !CORBA::is_nil( hypObject ) ) {
5656 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5657 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5658 || !myNewMeshImpl->HasShapeToMesh()) )
5659 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5664 aGroup->CloseOnDisk();
5667 // --> try to find SUB-MESHES containers for each type of submesh
5668 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5669 const char* name_meshgroup = 0;
5670 if ( j == GetSubMeshOnVertexTag() )
5671 name_meshgroup = "SubMeshes On Vertex";
5672 else if ( j == GetSubMeshOnEdgeTag() )
5673 name_meshgroup = "SubMeshes On Edge";
5674 else if ( j == GetSubMeshOnWireTag() )
5675 name_meshgroup = "SubMeshes On Wire";
5676 else if ( j == GetSubMeshOnFaceTag() )
5677 name_meshgroup = "SubMeshes On Face";
5678 else if ( j == GetSubMeshOnShellTag() )
5679 name_meshgroup = "SubMeshes On Shell";
5680 else if ( j == GetSubMeshOnSolidTag() )
5681 name_meshgroup = "SubMeshes On Solid";
5682 else if ( j == GetSubMeshOnCompoundTag() )
5683 name_meshgroup = "SubMeshes On Compound";
5685 // try to get submeshes container HDF group
5686 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5687 // open submeshes containers HDF group
5688 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5689 aGroup->OpenOnDisk();
5691 // get number of submeshes
5692 int aNbSubMeshes = aGroup->nInternalObjects();
5693 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5695 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5696 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5697 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5698 // --> get submesh id
5699 int subid = atoi( name_submeshgroup + 7 );
5702 // open submesh HDF group
5703 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5704 aSubGroup->OpenOnDisk();
5706 // try to read and set reference to subshape
5707 GEOM::GEOM_Object_var aSubShapeObject;
5708 SMESH::SMESH_subMesh_var aSubMesh;
5710 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5711 // load submesh "Ref on shape" - it's an entry to SObject
5712 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5713 aDataset->OpenOnDisk();
5714 size = aDataset->GetSize();
5715 char* refFromFile = new char[ size ];
5716 aDataset->ReadFromDisk( refFromFile );
5717 aDataset->CloseOnDisk();
5718 if ( strlen( refFromFile ) > 0 ) {
5719 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5720 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5721 if ( !CORBA::is_nil( subShapeObject ) ) {
5722 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5723 if ( !aSubShapeObject->_is_nil() )
5724 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5725 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5726 if ( aSubMesh->_is_nil() )
5728 string iorSubString = GetORB()->object_to_string( aSubMesh );
5729 int newSubId = myStudyContext->findId( iorSubString );
5730 myStudyContext->mapOldToNew( subid, newSubId );
5733 delete [] refFromFile;
5736 if ( aSubMesh->_is_nil() )
5739 // try to get applied algorithms
5740 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5741 // open "applied algorithms" HDF group
5742 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5743 aSubSubGroup->OpenOnDisk();
5744 // get number of applied algorithms
5745 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5746 for ( int l = 0; l < aNbSubObjects; l++ ) {
5747 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5748 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5749 // check if it is an algorithm
5750 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5751 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5752 aDataset->OpenOnDisk();
5753 size = aDataset->GetSize();
5754 char* refFromFile = new char[ size ];
5755 aDataset->ReadFromDisk( refFromFile );
5756 aDataset->CloseOnDisk();
5758 int id = atoi( refFromFile );
5759 string anIOR = myStudyContext->getIORbyOldId( id );
5760 if ( !anIOR.empty() ) {
5761 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5762 if ( !CORBA::is_nil( hypObject ) ) {
5763 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5764 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5765 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5768 delete [] refFromFile;
5771 // close "applied algorithms" HDF group
5772 aSubSubGroup->CloseOnDisk();
5775 // try to get applied hypotheses
5776 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5777 // open "applied hypotheses" HDF group
5778 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5779 aSubSubGroup->OpenOnDisk();
5780 // get number of applied hypotheses
5781 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5782 for ( int l = 0; l < aNbSubObjects; l++ ) {
5783 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5784 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5785 // check if it is a hypothesis
5786 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5787 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5788 aDataset->OpenOnDisk();
5789 size = aDataset->GetSize();
5790 char* refFromFile = new char[ size ];
5791 aDataset->ReadFromDisk( refFromFile );
5792 aDataset->CloseOnDisk();
5794 int id = atoi( refFromFile );
5795 string anIOR = myStudyContext->getIORbyOldId( id );
5796 if ( !anIOR.empty() ) {
5797 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5798 if ( !CORBA::is_nil( hypObject ) ) {
5799 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5800 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5801 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5804 delete [] refFromFile;
5807 // close "APPLIED HYPOTHESES" hdf group
5808 aSubSubGroup->CloseOnDisk();
5811 // close SUB-MESH hdf group
5812 aSubGroup->CloseOnDisk();
5815 // close SUB-MESHES containers hdf group
5816 aGroup->CloseOnDisk();
5820 // try to get GROUPS
5821 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5822 char name_group[ 30 ];
5823 if ( ii == GetNodeGroupsTag() )
5824 strcpy( name_group, "Groups of Nodes" );
5825 else if ( ii == GetEdgeGroupsTag() )
5826 strcpy( name_group, "Groups of Edges" );
5827 else if ( ii == GetFaceGroupsTag() )
5828 strcpy( name_group, "Groups of Faces" );
5829 else if ( ii == GetVolumeGroupsTag() )
5830 strcpy( name_group, "Groups of Volumes" );
5831 else if ( ii == Get0DElementsGroupsTag() )
5832 strcpy( name_group, "Groups of 0D Elements" );
5833 else if ( ii == GetBallElementsGroupsTag() )
5834 strcpy( name_group, "Groups of Balls" );
5836 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5837 aGroup = new HDFgroup( name_group, aTopGroup );
5838 aGroup->OpenOnDisk();
5839 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5840 // within aGroup->ExistInternalObject( name )
5841 std::vector< std::string > subNames;
5842 TColStd_MapOfAsciiString mapOfNames;
5843 aGroup->GetAllObjects( subNames );
5844 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5845 mapOfNames.Add( subNames[ iN ].c_str() );
5847 for ( size_t j = 0; j < subNames.size(); j++ ) {
5848 const std::string& name_dataset = subNames[ j ];
5849 // check if it is a group
5850 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5853 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5856 int groupID = -1; // group local ID (also persistent)
5858 groupID = atoi( endptr + 1 );
5859 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5860 aDataset->OpenOnDisk();
5862 // Retrieve actual group name
5863 size = aDataset->GetSize();
5864 char* nameFromFile = new char[ size ];
5865 aDataset->ReadFromDisk( nameFromFile );
5866 aDataset->CloseOnDisk();
5868 // Try to find a shape reference
5869 TopoDS_Shape aShape;
5870 char aRefName[ 30 ];
5871 sprintf( aRefName, "Ref on shape %d", subid);
5872 if ( mapOfNames.Contains( aRefName ))
5874 // load mesh "Ref on shape" - it's an entry to SObject
5875 aDataset = new HDFdataset( aRefName, aGroup );
5876 aDataset->OpenOnDisk();
5877 size = aDataset->GetSize();
5878 char* refFromFile = new char[ size ];
5879 aDataset->ReadFromDisk( refFromFile );
5880 aDataset->CloseOnDisk();
5881 if ( strlen( refFromFile ) > 0 ) {
5882 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5883 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5884 if ( !CORBA::is_nil( shapeObject ) ) {
5885 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5886 if ( !aShapeObject->_is_nil() )
5887 aShape = GeomObjectToShape( aShapeObject );
5890 delete [] refFromFile;
5892 // Try to read a filter of SMESH_GroupOnFilter
5893 SMESH::Filter_var filter;
5894 SMESH_PredicatePtr predicate;
5895 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5896 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5898 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5899 aDataset->OpenOnDisk();
5900 size = aDataset->GetSize();
5901 char* persistStr = new char[ size ];
5902 aDataset->ReadFromDisk( persistStr );
5903 aDataset->CloseOnDisk();
5904 if ( strlen( persistStr ) > 0 ) {
5905 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5906 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5907 filters.push_back( filter );
5909 delete [] persistStr;
5912 // Create group servant
5913 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5914 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5915 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5916 delete [] nameFromFile;
5917 // Obtain a SMESHDS_Group object
5918 if ( aNewGroup->_is_nil() )
5921 string iorSubString = GetORB()->object_to_string( aNewGroup );
5922 int newSubId = myStudyContext->findId( iorSubString );
5923 myStudyContext->mapOldToNew( subid, newSubId );
5925 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5929 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5930 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5932 aFilterGroup->SetFilter( filter );
5933 filter->UnRegister();
5935 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5936 if ( !aGroupBaseDS )
5939 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5942 // Read color of the group
5943 char aGroupColorName[ 30 ];
5944 sprintf( aGroupColorName, "ColorGroup %d", subid);
5945 if ( mapOfNames.Contains( aGroupColorName ))
5947 aDataset = new HDFdataset( aGroupColorName, aGroup );
5948 aDataset->OpenOnDisk();
5949 size = aDataset->GetSize();
5950 double* anRGB = new double[ size ];
5951 aDataset->ReadFromDisk( anRGB );
5952 aDataset->CloseOnDisk();
5953 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5954 aGroupBaseDS->SetColor( aColor );
5959 aGroup->CloseOnDisk();
5963 // instead of reading mesh data, we read only brief information of all
5964 // objects: mesh, groups, sub-meshes (issue 0021208)
5967 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5968 meshfile.ToCString(), filename.ToCString(),
5972 // read Sub-Mesh ORDER if any
5973 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5974 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5975 aDataset->OpenOnDisk();
5976 size = aDataset->GetSize();
5977 int* smIDs = new int[ size ];
5978 aDataset->ReadFromDisk( smIDs );
5979 aDataset->CloseOnDisk();
5980 TListOfListOfInt anOrderIds;
5981 anOrderIds.push_back( TListOfInt() );
5982 for ( int i = 0; i < size; i++ )
5983 if ( smIDs[ i ] < 0 ) // is separator
5984 anOrderIds.push_back( TListOfInt() );
5986 anOrderIds.back().push_back(smIDs[ i ]);
5988 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5993 // update hyps needing full mesh data restored (issue 20918)
5994 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5996 SMESH_Hypothesis_i* hyp = hyp_data->first;
5997 hyp->UpdateAsMeshesRestored();
6000 // notify algos on completed restoration to set sub-mesh event listeners
6001 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
6003 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
6004 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
6006 TopoDS_Shape myLocShape;
6007 if(myLocMesh.HasShapeToMesh())
6008 myLocShape = myLocMesh.GetShapeToMesh();
6010 myLocShape = SMESH_Mesh::PseudoShape();
6012 myLocMesh.GetSubMesh(myLocShape)->
6013 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
6016 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
6017 list< SMESH::Filter_var >::iterator f = filters.begin();
6018 for ( ; f != filters.end(); ++f )
6019 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
6020 fi->FindBaseObjects();
6025 aTopGroup->CloseOnDisk();
6028 aFile->CloseOnDisk();
6031 // Remove temporary files created from the stream
6034 SMESH_File meshFile( meshfile.ToCString() );
6035 if ( !meshFile ) // no meshfile exists
6037 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
6041 Engines::Container_var container = GetContainerRef();
6042 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
6044 container_i->registerTemporaryFile( filename.ToCString() );
6045 container_i->registerTemporaryFile( meshfile.ToCString() );
6046 container_i->registerTemporaryFile( tmpDir.ToCString() );
6050 pd << ""; // prevent optimizing pd out
6052 // creation of tree nodes for all data objects in the study
6053 // to support tree representation customization and drag-n-drop:
6054 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
6055 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
6056 useCaseBuilder->SetRootCurrent();
6057 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6058 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6059 for (it->InitEx(true); it->More(); it->Next()) {
6060 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6067 //=============================================================================
6069 * SMESH_Gen_i::LoadASCII
6071 * Load SMESH module's data in ASCII format
6073 //=============================================================================
6075 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6076 const SALOMEDS::TMPFile& theStream,
6078 bool isMultiFile ) {
6079 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6080 return Load( theComponent, theStream, theURL, isMultiFile );
6082 //before call main ::Load method it's need for decipher text format to
6083 //binary ( "|xx" => x' )
6084 int size = theStream.length();
6085 if ( int((size / 3 )*3) != size ) //error size of buffer
6088 int real_size = int(size / 3);
6090 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6093 unsigned int c = -1;
6094 for ( int i = 0; i < real_size; i++ )
6096 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6097 sscanf( tmp, "%x", &c );
6098 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6101 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6103 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6106 //=============================================================================
6108 * SMESH_Gen_i::Close
6110 * Clears study-connected data when it is closed
6112 //=============================================================================
6114 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6116 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6118 // Clear study contexts data
6119 myStudyContext->Clear();
6121 // remove the tmp files meshes are loaded from
6122 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6124 // Clean trace of API methods calls
6130 //=============================================================================
6132 * SMESH_Gen_i::ComponentDataType
6134 * Get component data type
6136 //=============================================================================
6138 char* SMESH_Gen_i::ComponentDataType()
6140 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6141 return CORBA::string_dup( "SMESH" );
6145 //=============================================================================
6147 * SMESH_Gen_i::IORToLocalPersistentID
6149 * Transform data from transient form to persistent
6151 //=============================================================================
6153 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6154 const char* IORString,
6155 CORBA::Boolean /*isMultiFile*/,
6156 CORBA::Boolean /*isASCII*/ )
6158 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6160 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6161 int anId = myStudyContext->findId( IORString );
6163 if(MYDEBUG) MESSAGE( "VSR " << anId )
6165 sprintf( strId, "%d", anId );
6166 return CORBA::string_dup( strId );
6169 return CORBA::string_dup( "" );
6172 //=============================================================================
6174 * SMESH_Gen_i::LocalPersistentIDToIOR
6176 * Transform data from persistent form to transient
6178 //=============================================================================
6180 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6181 const char* aLocalPersistentID,
6182 CORBA::Boolean /*isMultiFile*/,
6183 CORBA::Boolean /*isASCII*/ )
6185 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6187 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6188 int anId = atoi( aLocalPersistentID );
6189 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6191 return CORBA::string_dup( "" );
6194 //=======================================================================
6195 //function : RegisterObject
6197 //=======================================================================
6199 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6201 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6202 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6203 return myStudyContext->addObject( string( iorString.in() ) );
6208 //================================================================================
6210 * \brief Return id of registered object
6211 * \param theObject - the Object
6212 * \retval int - Object id
6214 //================================================================================
6216 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6218 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6219 string iorString = GetORB()->object_to_string( theObject );
6220 return myStudyContext->findId( iorString );
6225 //=============================================================================
6227 * SMESH_Gen_i::SetName
6229 * Set a new object name
6231 //=============================================================================
6232 void SMESH_Gen_i::SetName(const char* theIOR,
6233 const char* theName)
6235 if ( theIOR && strcmp( theIOR, "" ) ) {
6236 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6237 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6238 if ( !aSO->_is_nil() ) {
6239 SetName( aSO, theName );
6244 // Version information
6245 char* SMESH_Gen_i::getVersion()
6247 #if SMESH_DEVELOPMENT
6248 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6250 return CORBA::string_dup(SMESH_VERSION_STR);
6254 //=================================================================================
6255 // function : Move()
6256 // purpose : Moves objects to the specified position.
6257 // Is used in the drag-n-drop functionality.
6258 //=================================================================================
6259 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6260 SALOMEDS::SObject_ptr where,
6263 if ( CORBA::is_nil( where ) ) return;
6265 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6266 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6267 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6268 std::string dataType = father->ComponentDataType();
6269 if ( dataType != "SMESH" ) return; // not a SMESH component
6271 SALOMEDS::SObject_var objAfter;
6272 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6273 // insert at given row -> find insertion position
6274 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6276 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6277 if ( i == row && useCaseIt->More() ) {
6278 objAfter = useCaseIt->Value();
6282 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6283 SALOMEDS::SObject_var sobj = what[i];
6284 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6285 // insert the object to the use case tree
6286 if ( !CORBA::is_nil( objAfter ) )
6287 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6289 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6292 //================================================================================
6294 * \brief Returns true if algorithm can be used to mesh a given geometry
6295 * \param [in] theAlgoType - the algorithm type
6296 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6297 * \param [in] theGeomObject - the geometry to mesh
6298 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6299 * else, returns \c True if at least one shape is meshable
6300 * \return CORBA::Boolean - can or can't
6302 //================================================================================
6304 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6305 const char* theLibName,
6306 GEOM::GEOM_Object_ptr theGeomObject,
6307 CORBA::Boolean toCheckAll)
6311 std::string aPlatformLibName;
6312 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6313 GenericHypothesisCreator_i* aCreator =
6314 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6317 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6318 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6319 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6326 SMESH_CATCH( SMESH::doNothing );
6329 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6334 //=================================================================================
6335 // function : GetInsideSphere
6336 // purpose : Collect indices of elements, which are located inside the sphere
6337 //=================================================================================
6338 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6339 SMESH::ElementType theElemType,
6345 SMESH::long_array_var aResult = new SMESH::long_array();
6346 if ( meshPart->_is_nil() )
6347 return aResult._retn();
6349 // 1. Create geometrical object
6350 gp_Pnt aP( theX, theY, theZ );
6351 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6353 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6355 if ( lst.size() > 0 ) {
6356 aResult->length( lst.size() );
6357 for ( size_t i = 0; i < lst.size(); i++ ) {
6358 aResult[i] = lst[i];
6361 return aResult._retn();
6364 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6365 SMESH::ElementType theElemType,
6366 CORBA::Double theX1,
6367 CORBA::Double theY1,
6368 CORBA::Double theZ1,
6369 CORBA::Double theX2,
6370 CORBA::Double theY2,
6371 CORBA::Double theZ2) {
6372 SMESH::long_array_var aResult = new SMESH::long_array();
6373 if( meshPart->_is_nil() )
6374 return aResult._retn();
6376 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6378 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6380 if( lst.size() > 0 ) {
6381 aResult->length( lst.size() );
6382 for ( size_t i = 0; i < lst.size(); i++ ) {
6383 aResult[i] = lst[i];
6386 return aResult._retn();
6389 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6390 SMESH::ElementType theElemType,
6394 CORBA::Double theDX,
6395 CORBA::Double theDY,
6396 CORBA::Double theDZ,
6398 CORBA::Double theR ){
6399 SMESH::long_array_var aResult = new SMESH::long_array();
6400 if( meshPart->_is_nil() )
6401 return aResult._retn();
6403 gp_Pnt aP( theX, theY, theZ );
6404 gp_Vec aV( theDX, theDY, theDZ );
6405 gp_Ax2 anAxes (aP, aV);
6407 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6409 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6411 if( lst.size() > 0 ) {
6412 aResult->length( lst.size() );
6413 for ( size_t i = 0; i < lst.size(); i++ ) {
6414 aResult[i] = lst[i];
6417 return aResult._retn();
6420 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6421 SMESH::ElementType theElemType,
6422 GEOM::GEOM_Object_ptr theGeom,
6423 CORBA::Double theTolerance ) {
6424 SMESH::long_array_var aResult = new SMESH::long_array();
6425 if( meshPart->_is_nil() || theGeom->_is_nil() )
6426 return aResult._retn();
6428 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6430 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6432 if( lst.size() > 0 ) {
6433 aResult->length( lst.size() );
6434 for ( size_t i = 0; i < lst.size(); i++ ) {
6435 aResult[i] = lst[i];
6438 return aResult._retn();
6443 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6444 SMESH::ElementType theElemType,
6445 TopoDS_Shape& aShape,
6446 double* theTolerance) {
6448 std::vector<long> res;
6449 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6451 if ( mesh->_is_nil() )
6454 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6458 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6463 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6464 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6465 anElementsOnShape->SetAllNodes( true );
6466 anElementsOnShape->SetMesh( meshDS );
6467 anElementsOnShape->SetShape( aShape, aType );
6470 anElementsOnShape->SetTolerance(*theTolerance);
6472 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6473 if ( !msource->_is_nil() ) { // Mesh case
6474 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6476 while ( elemIt->more() ) {
6477 const SMDS_MeshElement* anElem = elemIt->next();
6478 long anId = anElem->GetID();
6479 if ( anElementsOnShape->IsSatisfy( anId ) )
6480 res.push_back( anId );
6484 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6485 if ( !gsource->_is_nil() ) {
6486 if(theElemType == SMESH::NODE) {
6487 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6488 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6489 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6490 long anId = node->GetID();
6491 if ( anElementsOnShape->IsSatisfy( anId ) )
6492 res.push_back( anId );
6495 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6496 SMESH::long_array_var elems = gsource->GetListOfID();
6497 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6498 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6499 long anId = elem->GetID();
6500 if ( anElementsOnShape->IsSatisfy( anId ) )
6501 res.push_back( anId );
6506 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6507 if ( !smsource->_is_nil() ) {
6508 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6509 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6510 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6512 long anId = elem->GetID();
6513 if ( anElementsOnShape->IsSatisfy( anId ) )
6514 res.push_back( anId );
6522 //=============================================================================
6524 * SMESHEngine_factory
6526 * C factory, accessible with dlsym, after dlopen
6528 //=============================================================================
6532 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6533 PortableServer::POA_ptr poa,
6534 PortableServer::ObjectId* contId,
6535 const char* instanceName,
6536 const char* interfaceName )
6538 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6539 if(MYDEBUG) SCRUTE(interfaceName);
6540 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6541 return aSMESHGen->getId() ;