1 // Copyright (C) 2007-2019 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License, or (at your option) any later version.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : SMESH_Gen_i.cxx
23 // Author : Paul RASCLE, EDF
26 #include <BRepPrimAPI_MakeBox.hxx>
27 #include <BRepPrimAPI_MakeCylinder.hxx>
28 #include <BRepPrimAPI_MakeSphere.hxx>
29 #include <BRep_Tool.hxx>
31 #include <TColStd_MapOfAsciiString.hxx>
32 #include <TCollection_AsciiString.hxx>
34 #include <TopExp_Explorer.hxx>
35 #include <TopTools_IndexedMapOfShape.hxx>
36 #include <TopTools_ListIteratorOfListOfShape.hxx>
37 #include <TopTools_ListOfShape.hxx>
38 #include <TopTools_MapOfShape.hxx>
40 #include <TopoDS_CompSolid.hxx>
41 #include <TopoDS_Compound.hxx>
42 #include <TopoDS_Edge.hxx>
43 #include <TopoDS_Face.hxx>
44 #include <TopoDS_Iterator.hxx>
45 #include <TopoDS_Shape.hxx>
46 #include <TopoDS_Shell.hxx>
47 #include <TopoDS_Solid.hxx>
48 #include <TopoDS_Vertex.hxx>
49 #include <TopoDS_Wire.hxx>
58 #include <libgen.h> // for basename function
62 #define LibHandle HMODULE
63 #define LoadLib( name ) LoadLibrary( name )
64 #define GetProc GetProcAddress
65 #define UnLoadLib( handle ) FreeLibrary( handle );
67 #define LibHandle void*
69 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_LOCAL )
70 #else // DYNLOAD_LOCAL
71 #define LoadLib( name ) dlopen( name, RTLD_LAZY | RTLD_GLOBAL )
72 #endif // DYNLOAD_LOCAL
74 #define UnLoadLib( handle ) dlclose( handle );
77 #include "SMESH_Gen_i.hxx"
78 #include "SMESH_version.h"
80 #include "DriverMED_W_SMESHDS_Mesh.h"
81 #include "DriverMED_R_SMESHDS_Mesh.h"
83 #include "DriverCGNS_Read.hxx"
85 #include "MED_Factory.hxx"
86 #include "SMDS_EdgePosition.hxx"
87 #include "SMDS_FacePosition.hxx"
88 #include "SMDS_SetIterator.hxx"
89 #include "SMDS_SpacePosition.hxx"
90 #include "SMDS_VertexPosition.hxx"
91 #include "SMESHDS_Document.hxx"
92 #include "SMESHDS_Group.hxx"
93 #include "SMESHDS_GroupOnGeom.hxx"
94 #include "SMESH_Algo_i.hxx"
95 #include "SMESH_File.hxx"
96 #include "SMESH_Group.hxx"
97 #include "SMESH_Group_i.hxx"
98 #include "SMESH_Hypothesis.hxx"
99 #include "SMESH_Hypothesis_i.hxx"
100 #include "SMESH_Mesh.hxx"
101 #include "SMESH_MeshEditor.hxx"
102 #include "SMESH_Mesh_i.hxx"
103 #include "SMESH_PreMeshInfo.hxx"
104 #include "SMESH_PythonDump.hxx"
105 #include "SMESH_ControlsDef.hxx"
107 // to pass CORBA exception through SMESH_TRY
108 #define SMY_OWN_CATCH catch( SALOME::SALOME_Exception& se ) { throw se; }
109 #include "SMESH_TryCatch.hxx" // to include after OCC headers!
111 #include CORBA_SERVER_HEADER(SMESH_Group)
112 #include CORBA_SERVER_HEADER(SMESH_Filter)
113 #include CORBA_SERVER_HEADER(SMESH_MeshEditor)
116 #include <GEOMImpl_Types.hxx>
117 #include <GEOM_Client.hxx>
119 #include <Basics_Utils.hxx>
120 #include <Basics_DirUtils.hxx>
122 #include <OpUtil.hxx>
123 #include <SALOMEDS_Tool.hxx>
124 #include <SALOME_Container_i.hxx>
125 #include <SALOME_LifeCycleCORBA.hxx>
126 #include <SALOME_NamingService.hxx>
127 #include <Utils_CorbaException.hxx>
128 #include <Utils_ExceptHandlers.hxx>
129 #include <Utils_SINGLETON.hxx>
130 #include <utilities.h>
132 #include CORBA_CLIENT_HEADER(SALOME_ModuleCatalog)
133 #include CORBA_CLIENT_HEADER(SALOME_Session)
135 // helpers about SALOME::GenericObj
136 #include <SALOMEDS_wrap.hxx>
137 #include <SALOMEDS_Attributes_wrap.hxx>
138 #include <GEOM_wrap.hxx>
148 using SMESH::TPythonDump;
151 #define NUM_TMP_FILES 2
154 static int MYDEBUG = 0;
156 static int MYDEBUG = 0;
159 // Static variables definition
160 GEOM::GEOM_Gen_var SMESH_Gen_i::myGeomGen;
161 CORBA::ORB_var SMESH_Gen_i::myOrb;
162 PortableServer::POA_var SMESH_Gen_i::myPoa;
163 SALOME_NamingService* SMESH_Gen_i::myNS = NULL;
164 SALOME_LifeCycleCORBA* SMESH_Gen_i::myLCC = NULL;
165 SMESH_Gen_i* SMESH_Gen_i::mySMESHGen = NULL;
168 const int nbElemPerDiagonal = 10;
170 //=============================================================================
172 * GetServant [ static ]
174 * Get servant of the CORBA object
176 //=============================================================================
178 PortableServer::ServantBase_var SMESH_Gen_i::GetServant( CORBA::Object_ptr theObject )
180 if( CORBA::is_nil( theObject ) || CORBA::is_nil( GetPOA() ) )
183 PortableServer::Servant aServant = GetPOA()->reference_to_servant( theObject );
186 catch (PortableServer::POA::ObjectNotActive &ex)
188 INFOS("GetServant: ObjectNotActive");
191 catch (PortableServer::POA::WrongAdapter &ex)
193 INFOS("GetServant: WrongAdapter: OK when several servants used to build several mesh in parallel...");
196 catch (PortableServer::POA::WrongPolicy &ex)
198 INFOS("GetServant: WrongPolicy");
203 INFOS( "GetServant - Unknown exception was caught!!!" );
208 //=============================================================================
210 * SObjectToObject [ static ]
212 * Get CORBA object corresponding to the SALOMEDS::SObject
214 //=============================================================================
216 CORBA::Object_var SMESH_Gen_i::SObjectToObject( SALOMEDS::SObject_ptr theSObject )
218 SALOMEDS::GenericAttribute_wrap anAttr;
219 CORBA::Object_var anObj;
220 if ( !theSObject->_is_nil() ) {
222 if( theSObject->FindAttribute( anAttr.inout(), "AttributeIOR" ) ) {
223 SALOMEDS::AttributeIOR_wrap anIOR = anAttr;
224 CORBA::String_var aValue = anIOR->Value();
225 if( strcmp( aValue, "" ) != 0 )
226 anObj = GetORB()->string_to_object( aValue );
230 INFOS( "SObjectToObject - Unknown exception was caught!!!" );
236 //=============================================================================
240 * Get SALOME_NamingService object
242 //=============================================================================
244 SALOME_NamingService* SMESH_Gen_i::GetNS()
246 if ( myNS == NULL ) {
247 myNS = SINGLETON_<SALOME_NamingService>::Instance();
248 ASSERT(SINGLETON_<SALOME_NamingService>::IsAlreadyExisting());
249 myNS->init_orb( GetORB() );
254 //=============================================================================
258 * Get SALOME_LifeCycleCORBA object
260 //=============================================================================
262 SALOME_LifeCycleCORBA* SMESH_Gen_i::GetLCC()
264 if ( myLCC == NULL ) {
265 myLCC = new SALOME_LifeCycleCORBA( GetNS() );
270 //=============================================================================
272 * GetGeomEngine [ static ]
274 * Get GEOM::GEOM_Gen reference
276 //=============================================================================
278 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( bool isShaper )
280 Engines::EngineComponent_ptr temp =
281 GetLCC()->FindOrLoad_Component( isShaper ? "FactoryServer" : "FactoryServer",
282 isShaper ? "SHAPERSTUDY" : "GEOM" );
283 myGeomGen = GEOM::GEOM_Gen::_narrow( temp );
288 //=============================================================================
290 * GetGeomEngine [ static ]
292 * Get GEOM::GEOM_Gen reference
294 //=============================================================================
296 GEOM::GEOM_Gen_var SMESH_Gen_i::GetGeomEngine( GEOM::GEOM_Object_ptr go )
298 GEOM::GEOM_Gen_ptr gen;
299 if ( !CORBA::is_nil( go ))
304 //=============================================================================
306 * SMESH_Gen_i::SMESH_Gen_i
308 * Default constructor: not for use
310 //=============================================================================
312 SMESH_Gen_i::SMESH_Gen_i()
316 //=============================================================================
318 * SMESH_Gen_i::SMESH_Gen_i
320 * Standard constructor, used with Container
322 //=============================================================================
324 SMESH_Gen_i::SMESH_Gen_i( CORBA::ORB_ptr orb,
325 PortableServer::POA_ptr poa,
326 PortableServer::ObjectId* contId,
327 const char* instanceName,
328 const char* interfaceName )
329 : Engines_Component_i( orb, poa, contId, instanceName, interfaceName )
332 myOrb = CORBA::ORB::_duplicate(orb);
333 myPoa = PortableServer::POA::_duplicate(poa);
336 _id = myPoa->activate_object( _thisObj );
338 myStudyContext = new StudyContext;
340 myIsEmbeddedMode = false;
341 myIsEnablePublish = true;
342 myShapeReader = NULL; // shape reader
344 myIsHistoricalPythonDump = true;
345 myToForgetMeshDataOnHypModif = false;
347 // set it in standalone mode only
348 //OSD::SetSignal( true );
350 // 0020605: EDF 1190 SMESH: Display performance. 80 seconds for 52000 cells.
351 // find out mode (embedded or standalone) here else
352 // meshes created before calling SMESH_Client::GetSMESHGen(), which calls
353 // SMESH_Gen_i::SetEmbeddedMode(), have wrong IsEmbeddedMode flag
354 if ( SALOME_NamingService* ns = GetNS() )
356 CORBA::Object_var obj = ns->Resolve( "/Kernel/Session" );
357 SALOME::Session_var session = SALOME::Session::_narrow( obj ) ;
358 if ( !session->_is_nil() )
360 CORBA::String_var str_host = session->getHostname();
361 CORBA::Long s_pid = session->getPID();
362 string my_host = Kernel_Utils::GetHostname();
364 long my_pid = (long)_getpid();
366 long my_pid = (long) getpid();
368 SetEmbeddedMode( s_pid == my_pid && my_host == str_host.in() );
373 //=============================================================================
375 * SMESH_Gen_i::~SMESH_Gen_i
379 //=============================================================================
381 SMESH_Gen_i::~SMESH_Gen_i()
383 // delete hypothesis creators
384 map<string, GenericHypothesisCreator_i*>::iterator itHyp, itHyp2;
385 for (itHyp = myHypCreatorMap.begin(); itHyp != myHypCreatorMap.end(); itHyp++)
387 // same creator can be mapped under different names
388 GenericHypothesisCreator_i* creator = (*itHyp).second;
392 for (itHyp2 = itHyp; itHyp2 != myHypCreatorMap.end(); itHyp2++)
393 if ( creator == (*itHyp2).second )
394 (*itHyp2).second = 0;
396 myHypCreatorMap.clear();
398 // Clear study contexts data
399 delete myStudyContext;
401 // delete shape reader
403 delete myShapeReader;
405 //=============================================================================
407 * SMESH_Gen_i::getHypothesisCreator
409 * Get hypothesis creator
411 //=============================================================================
412 GenericHypothesisCreator_i* SMESH_Gen_i::getHypothesisCreator(const char* theHypName,
413 const char* theLibName,
414 std::string& thePlatformLibName)
415 throw (SALOME::SALOME_Exception)
417 std::string aPlatformLibName;
418 /* It's Need to translate lib name for WIN32 or X platform */
419 if ( theLibName && theLibName[0] != '\0' )
421 int libNameLen = strlen(theLibName);
422 //check for old format "libXXXXXXX.so"
423 if (libNameLen > 7 &&
424 !strncmp( theLibName, "lib", 3 ) &&
425 !strcmp( theLibName+libNameLen-3, ".so" ))
429 aPlatformLibName = std::string( theLibName+3, libNameLen-6 ) + ".dll";
430 #elif defined(__APPLE__)
431 aPlatformLibName = std::string( theLibName, libNameLen-3 ) + ".dylib";
433 aPlatformLibName = theLibName;
438 //try to use new format
440 aPlatformLibName = theLibName;
441 aPlatformLibName += ".dll";
442 #elif defined(__APPLE__)
443 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".dylib";
445 aPlatformLibName = std::string( "lib" ) + std::string( theLibName ) + ".so";
449 thePlatformLibName = aPlatformLibName;
451 Unexpect aCatch(SALOME_SalomeException);
452 if(MYDEBUG) MESSAGE( "Create Hypothesis <" << theHypName << "> from " << aPlatformLibName);
454 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char* );
455 GenericHypothesisCreator_i* aCreator;
458 // check, if creator for this hypothesis type already exists
459 if (myHypCreatorMap.find(string(theHypName)) == myHypCreatorMap.end())
461 // load plugin library
462 if(MYDEBUG) MESSAGE("Loading server meshers plugin library ...");
465 const wchar_t* path = Kernel_Utils::decode_s(aPlatformLibName);
467 const char* path = aPlatformLibName.c_str();
470 const char* path = aPlatformLibName.c_str();
472 LibHandle libHandle = LoadLib( path );
473 #if defined(WIN32) && defined(UNICODE)
478 // report any error, if occurred
480 const char* anError = dlerror();
481 throw(SALOME_Exception( anError ));
483 throw(SALOME_Exception ( SMESH_Comment("Can't load meshers plugin library " )
484 << aPlatformLibName));
488 // get method, returning hypothesis creator
489 if(MYDEBUG) MESSAGE("Find GetHypothesisCreator() method ...");
490 GetHypothesisCreator procHandle =
491 (GetHypothesisCreator)GetProc( libHandle, "GetHypothesisCreator" );
494 throw(SALOME_Exception(SMESH_Comment("bad hypothesis plugin library")
495 << aPlatformLibName ));
496 UnLoadLib(libHandle);
499 // get hypothesis creator
500 if(MYDEBUG) MESSAGE("Get Hypothesis Creator for " << theHypName);
501 aCreator = procHandle(theHypName);
504 throw(SALOME_Exception( SMESH_Comment( theHypName ) << " is missing from "
505 << aPlatformLibName));
507 // map hypothesis creator to a hypothesis name
508 myHypCreatorMap[string(theHypName)] = aCreator;
513 return myHypCreatorMap[string(theHypName)];
516 catch (SALOME_Exception& S_ex)
518 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
523 //=============================================================================
525 * SMESH_Gen_i::createHypothesis
527 * Create hypothesis of given type
529 //=============================================================================
530 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::createHypothesis(const char* theHypName,
531 const char* theLibName)
533 SMESH_Hypothesis_i* myHypothesis_i = 0;
534 SMESH::SMESH_Hypothesis_var hypothesis_i;
535 std::string aPlatformLibName;
536 GenericHypothesisCreator_i* aCreator =
537 getHypothesisCreator(theHypName, theLibName, aPlatformLibName);
539 // create a new hypothesis object, store its ref. in studyContext
540 myHypothesis_i = aCreator->Create(myPoa, &myGen);
543 myHypothesis_i->SetLibName( aPlatformLibName.c_str() ); // for persistency assurance
544 CORBA::String_var hypName = myHypothesis_i->GetName();
545 myHypCreatorMap[ hypName.in() ] = aCreator;
547 // activate the CORBA servant of hypothesis
548 hypothesis_i = myHypothesis_i->_this();
549 int nextId = RegisterObject( hypothesis_i );
550 if(MYDEBUG) { MESSAGE( "Add hypo to map with id = "<< nextId ); }
551 else { nextId = 0; } // avoid "unused variable" warning in release mode
553 return hypothesis_i._retn();
556 //=============================================================================
558 * SMESH_Gen_i::createMesh
560 * Create empty mesh on shape
562 //=============================================================================
563 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::createMesh()
564 throw ( SALOME::SALOME_Exception )
566 Unexpect aCatch(SALOME_SalomeException);
567 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::createMesh" );
569 // Get or create the GEOM_Client instance
571 // create a new mesh object servant, store it in a map in study context
572 SMESH_Mesh_i* meshServant = new SMESH_Mesh_i( GetPOA(), this );
573 // create a new mesh object
574 if(MYDEBUG) MESSAGE("myIsEmbeddedMode " << myIsEmbeddedMode);
575 meshServant->SetImpl( myGen.CreateMesh( myIsEmbeddedMode ));
577 // activate the CORBA servant of Mesh
578 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( meshServant->_this() );
579 int nextId = RegisterObject( mesh );
580 if(MYDEBUG) { MESSAGE( "Add mesh to map with id = "<< nextId); }
581 else { nextId = 0; } // avoid "unused variable" warning in release mode
584 catch (SALOME_Exception& S_ex) {
585 THROW_SALOME_CORBA_EXCEPTION( S_ex.what(), SALOME::BAD_PARAM );
587 return SMESH::SMESH_Mesh::_nil();
590 //=============================================================================
592 * SMESH_Gen_i::GetShapeReader
596 //=============================================================================
597 GEOM_Client* SMESH_Gen_i::GetShapeReader()
599 // create shape reader if necessary
600 if ( !myShapeReader )
601 myShapeReader = new GEOM_Client(GetContainerRef());
602 ASSERT( myShapeReader );
603 return myShapeReader;
606 //=============================================================================
608 * SMESH_Gen_i::SetGeomEngine
610 * Set GEOM::GEOM_Gen reference
612 //=============================================================================
613 //GEOM::GEOM_Gen_ptr SMESH_Gen_i::SetGeomEngine( const char* containerLoc )
614 void SMESH_Gen_i::SetGeomEngine( GEOM::GEOM_Gen_ptr geomcompo )
616 //Engines::Component_ptr temp=GetLCC()->FindOrLoad_Component(containerLoc,"GEOM");
617 //myGeomGen=GEOM::GEOM_Gen::_narrow(temp);
618 myGeomGen=GEOM::GEOM_Gen::_duplicate(geomcompo);
622 //=============================================================================
624 * SMESH_Gen_i::SetEmbeddedMode
628 //=============================================================================
630 void SMESH_Gen_i::SetEmbeddedMode( CORBA::Boolean theMode )
632 myIsEmbeddedMode = theMode;
634 if ( !myIsEmbeddedMode ) {
635 //PAL10867: disable signals catching with "noexcepthandler" option
636 char* envNoCatchSignals = getenv("NOT_INTERCEPT_SIGNALS");
637 if (!envNoCatchSignals || !atoi(envNoCatchSignals))
642 char* envDisableFPE = getenv("DISABLE_FPE");
643 if (envDisableFPE && atoi(envDisableFPE))
648 OSD::SetSignal( raiseFPE );
650 // else OSD::SetSignal() is called in GUI
654 //=============================================================================
656 * SMESH_Gen_i::IsEmbeddedMode
660 //=============================================================================
662 CORBA::Boolean SMESH_Gen_i::IsEmbeddedMode()
664 return myIsEmbeddedMode;
667 //=============================================================================
669 * SMESH_Gen_i::SetEnablePublish
671 * Set enable publishing in the study
673 //=============================================================================
674 void SMESH_Gen_i::SetEnablePublish( CORBA::Boolean theIsEnablePublish )
676 myIsEnablePublish = theIsEnablePublish;
679 //=============================================================================
681 * SMESH_Gen_i::IsEnablePublish
683 * Check enable publishing
685 //=============================================================================
687 CORBA::Boolean SMESH_Gen_i::IsEnablePublish()
689 return myIsEnablePublish;
692 //=============================================================================
694 * SMESH_Gen_i::UpdateStudy
696 * Update study (needed at switching GEOM->SMESH)
698 //=============================================================================
700 void SMESH_Gen_i::UpdateStudy()
702 if ( !myStudyContext )
703 myStudyContext = new StudyContext;
705 SALOMEDS::Study_var aStudy = getStudyServant();
706 if ( !CORBA::is_nil( aStudy ) )
708 SALOMEDS::StudyBuilder_var aStudyBuilder = aStudy->NewBuilder();
710 SALOMEDS::SComponent_wrap GEOM_var = aStudy->FindComponent( "GEOM" );
711 if( !GEOM_var->_is_nil() )
712 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/false ) );
714 GEOM_var = aStudy->FindComponent( "SHAPERSTUDY" );
715 if( !GEOM_var->_is_nil() )
716 aStudyBuilder->LoadWith( GEOM_var, GetGeomEngine( /*isShaper=*/true ) );
718 // NPAL16168, issue 0020210
719 // Let meshes update their data depending on GEOM groups that could change
720 CORBA::String_var compDataType = ComponentDataType();
721 SALOMEDS::SComponent_wrap me = aStudy->FindComponent( compDataType.in() );
722 if ( !me->_is_nil() ) {
723 SALOMEDS::ChildIterator_wrap anIter = aStudy->NewChildIterator( me );
724 for ( ; anIter->More(); anIter->Next() ) {
725 SALOMEDS::SObject_wrap so = anIter->Value();
726 CORBA::Object_var ior = SObjectToObject( so );
727 if ( SMESH_Mesh_i* mesh = SMESH::DownCast<SMESH_Mesh_i*>( ior ))
728 mesh->CheckGeomModif();
734 //=================================================================================
735 // function : hasObjectInfo()
736 // purpose : shows if module provides information for its objects
737 //=================================================================================
739 bool SMESH_Gen_i::hasObjectInfo()
744 //=================================================================================
745 // function : getObjectInfo()
746 // purpose : returns an information for a given object by its entry
747 //=================================================================================
749 char* SMESH_Gen_i::getObjectInfo( const char* entry )
751 // for a mesh with icon == ICON_SMESH_TREE_GEOM_MODIF show a warning;
752 // for the rest, "module 'SMESH', ID=0:1:2:*"
756 SALOMEDS::SObject_wrap so = getStudyServant()->FindObjectID( entry );
757 CORBA::Object_var obj = SObjectToObject( so );
758 SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
759 if ( !mesh->_is_nil() )
761 SALOMEDS::GenericAttribute_wrap attr;
762 if ( so->FindAttribute( attr.inout(), "AttributePixMap" ))
764 SALOMEDS::AttributePixMap_wrap pm = attr;
765 CORBA::String_var ico = pm->GetPixMap();
766 if ( strcmp( ico.in(), "ICON_SMESH_TREE_GEOM_MODIF" ) == 0 )
768 txt << "The geometry was changed and the mesh needs to be recomputed";
775 CORBA::String_var compType = ComponentDataType();
776 txt << "module '" << compType << "', ID=" << entry;
778 return CORBA::string_dup( txt );
781 //=============================================================================
783 * SMESH_Gen_i::GetStudyContext
787 //=============================================================================
788 StudyContext* SMESH_Gen_i::GetStudyContext()
790 return myStudyContext;
793 //=============================================================================
795 * SMESH_Gen_i::CreateHypothesis
797 * Create hypothesis/algorithm of given type and publish it in the study
799 //=============================================================================
801 SMESH::SMESH_Hypothesis_ptr SMESH_Gen_i::CreateHypothesis( const char* theHypName,
802 const char* theLibName )
803 throw ( SALOME::SALOME_Exception )
805 Unexpect aCatch(SALOME_SalomeException);
806 // Create hypothesis/algorithm
807 SMESH::SMESH_Hypothesis_var hyp = this->createHypothesis( theHypName, theLibName );
809 // Publish hypothesis/algorithm in the study
810 if ( CanPublishInStudy( hyp ) ) {
811 SALOMEDS::SObject_wrap aSO = PublishHypothesis( hyp );
812 if ( !aSO->_is_nil() ) {
813 // Update Python script
814 TPythonDump() << aSO << " = " << this << ".CreateHypothesis('"
815 << theHypName << "', '" << theLibName << "')";
822 //================================================================================
824 * \brief Return a hypothesis holding parameter values corresponding either to the mesh
825 * existing on the given geometry or to size of the geometry.
826 * \param theHypType - hypothesis type name
827 * \param theLibName - plugin library name
828 * \param theMesh - The mesh of interest
829 * \param theGeom - The shape to get parameter values from
830 * \retval SMESH::SMESH_Hypothesis_ptr - The returned hypothesis may be the one existing
831 * in a study and used to compute the mesh, or a temporary one created just to pass
834 //================================================================================
836 SMESH::SMESH_Hypothesis_ptr
837 SMESH_Gen_i::GetHypothesisParameterValues (const char* theHypType,
838 const char* theLibName,
839 SMESH::SMESH_Mesh_ptr theMesh,
840 GEOM::GEOM_Object_ptr theGeom,
841 CORBA::Boolean byMesh)
842 throw ( SALOME::SALOME_Exception )
844 Unexpect aCatch(SALOME_SalomeException);
845 if ( byMesh && CORBA::is_nil( theMesh ) )
846 return SMESH::SMESH_Hypothesis::_nil();
847 if ( byMesh && CORBA::is_nil( theGeom ) )
848 return SMESH::SMESH_Hypothesis::_nil();
850 // -----------------------------------------------
851 // find hypothesis used to mesh theGeom
852 // -----------------------------------------------
854 // get mesh and shape
855 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
856 TopoDS_Shape shape = GeomObjectToShape( theGeom );
857 if ( byMesh && ( !meshServant || meshServant->NbNodes()==0 || shape.IsNull() ))
858 return SMESH::SMESH_Hypothesis::_nil();
859 ::SMESH_Mesh* mesh = meshServant ? &meshServant->GetImpl() : (::SMESH_Mesh*)0;
861 // create a temporary hypothesis to know its dimension
862 SMESH::SMESH_Hypothesis_var tmpHyp = this->createHypothesis( theHypType, theLibName );
863 SMESH_Hypothesis_i* hypServant = SMESH::DownCast<SMESH_Hypothesis_i*>( tmpHyp );
865 return SMESH::SMESH_Hypothesis::_nil();
866 ::SMESH_Hypothesis* hyp = hypServant->GetImpl();
869 // look for a hypothesis of theHypType used to mesh the shape
870 if ( myGen.GetShapeDim( shape ) == hyp->GetDim() )
873 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( theGeom );
874 int nbLocalHyps = aHypList->length();
875 for ( int i = 0; i < nbLocalHyps; i++ ) {
876 CORBA::String_var hypName = aHypList[i]->GetName();
877 if ( strcmp( theHypType, hypName.in() ) == 0 ) // FOUND local!
878 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
880 // check super shapes
881 TopTools_ListIteratorOfListOfShape itShape( mesh->GetAncestors( shape ));
882 while ( nbLocalHyps == 0 && itShape.More() ) {
883 GEOM::GEOM_Object_ptr geomObj = ShapeToGeomObject( itShape.Value() );
884 if ( ! CORBA::is_nil( geomObj )) {
885 SMESH::ListOfHypothesis_var aHypList = theMesh->GetHypothesisList( geomObj );
886 nbLocalHyps = aHypList->length();
887 for ( int i = 0; i < nbLocalHyps; i++ )
888 if ( strcmp( theHypType, aHypList[i]->GetName() ) == 0 ) // FOUND global!
889 return SMESH::SMESH_Hypothesis::_duplicate( aHypList[i] );
895 // let the temporary hypothesis find out somehow parameter values by mesh
896 if ( hyp->SetParametersByMesh( mesh, shape ))
897 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
902 diagonal = mesh->GetShapeDiagonalSize();
904 diagonal = ::SMESH_Mesh::GetShapeDiagonalSize( shape );
905 ::SMESH_Hypothesis::TDefaults dflts;
906 dflts._elemLength = diagonal / myGen.GetBoundaryBoxSegmentation();
907 dflts._nbSegments = myGen.GetDefaultNbSegments();
908 dflts._shape = &shape;
909 // let the temporary hypothesis initialize it's values
910 if ( hyp->SetParametersByDefaults( dflts, mesh ))
911 return SMESH::SMESH_Hypothesis::_duplicate( tmpHyp );
914 return SMESH::SMESH_Hypothesis::_nil();
917 //=============================================================================
919 * Returns \c True if a hypothesis is assigned to a sole sub-mesh in a current Study
920 * \param [in] theHyp - the hypothesis of interest
921 * \param [out] theMesh - the sole mesh using \a theHyp
922 * \param [out] theShape - the sole geometry \a theHyp is assigned to
923 * \return boolean - \c True if \a theMesh and \a theShape are sole using \a theHyp
925 * If two meshes on same shape have theHyp assigned to the same sub-shape, they are
926 * considered as SAME sub-mesh => result is \c true.
927 * This method ids used to initialize SMESHGUI_GenericHypothesisCreator with
928 * a shape to which an hyp being edited is assigned.
930 //=============================================================================
932 CORBA::Boolean SMESH_Gen_i::GetSoleSubMeshUsingHyp( SMESH::SMESH_Hypothesis_ptr theHyp,
933 SMESH::SMESH_Mesh_out theMesh,
934 GEOM::GEOM_Object_out theShape)
936 if ( CORBA::is_nil( theHyp ))
939 // get Mesh component SO
940 CORBA::String_var compDataType = ComponentDataType();
941 SALOMEDS::SComponent_wrap comp = getStudyServant()->FindComponent( compDataType.in() );
942 if ( CORBA::is_nil( comp ))
945 // look for child SO of meshes
946 SMESH::SMESH_Mesh_var foundMesh;
947 TopoDS_Shape foundShape;
949 SALOMEDS::ChildIterator_wrap meshIter = getStudyServant()->NewChildIterator( comp );
950 for ( ; meshIter->More() && isSole; meshIter->Next() )
952 SALOMEDS::SObject_wrap curSO = meshIter->Value();
953 CORBA::Object_var obj = SObjectToObject( curSO );
954 SMESH_Mesh_i* mesh_i = SMESH::DownCast< SMESH_Mesh_i* >( obj );
958 // look for a sole shape where theHyp is assigned
959 bool isHypFound = false;
960 const ShapeToHypothesis & s2hyps = mesh_i->GetImpl().GetMeshDS()->GetHypotheses();
961 ShapeToHypothesis::Iterator s2hypsIt( s2hyps );
962 for ( ; s2hypsIt.More() && isSole; s2hypsIt.Next() )
964 const THypList& hyps = s2hypsIt.Value();
965 THypList::const_iterator h = hyps.begin();
966 for ( ; h != hyps.end(); ++h )
967 if ( (*h)->GetID() == theHyp->GetId() )
969 if ( h != hyps.end()) // theHyp found
972 if ( ! foundShape.IsNull() &&
973 ! foundShape.IsSame( s2hypsIt.Key() )) // not a sole sub-shape
975 foundShape.Nullify();
979 foundShape = s2hypsIt.Key();
981 } // loop on assigned hyps
983 if ( isHypFound && !foundShape.IsNull() ) // a mesh using theHyp is found
985 if ( !foundMesh->_is_nil() ) // not a sole mesh
987 if ( !foundMesh->HasShapeToMesh() ||
988 !mesh_i ->HasShapeToMesh() )
990 isSole = ( foundMesh->HasShapeToMesh() == mesh_i->HasShapeToMesh() );
994 GEOM::GEOM_Object_var s1 = mesh_i ->GetShapeToMesh();
995 GEOM::GEOM_Object_var s2 = foundMesh->GetShapeToMesh();
996 isSole = s1->IsSame( s2 );
999 foundMesh = SMESH::SMESH_Mesh::_narrow( obj );
1005 ! foundMesh->_is_nil() &&
1006 ! foundShape.IsNull() )
1008 theMesh = foundMesh._retn();
1009 theShape = ShapeToGeomObject( foundShape );
1010 return ( !theMesh->_is_nil() && !theShape->_is_nil() );
1015 //=============================================================================
1017 * Sets number of segments per diagonal of boundary box of geometry by which
1018 * default segment length of appropriate 1D hypotheses is defined
1020 //=============================================================================
1022 void SMESH_Gen_i::SetBoundaryBoxSegmentation( CORBA::Long theNbSegments )
1023 throw ( SALOME::SALOME_Exception )
1025 if ( theNbSegments > 0 )
1026 myGen.SetBoundaryBoxSegmentation( int( theNbSegments ));
1028 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1030 //=============================================================================
1032 * \brief Sets default number of segments per edge
1034 //=============================================================================
1035 void SMESH_Gen_i::SetDefaultNbSegments(CORBA::Long theNbSegments)
1036 throw ( SALOME::SALOME_Exception )
1038 if ( theNbSegments > 0 )
1039 myGen.SetDefaultNbSegments( int(theNbSegments) );
1041 THROW_SALOME_CORBA_EXCEPTION( "non-positive number of segments", SALOME::BAD_PARAM );
1044 //=============================================================================
1048 //=============================================================================
1050 void SMESH_Gen_i::SetOption(const char* name, const char* value)
1052 if ( name && value && strlen( value ) > 0 )
1055 if ( strcmp(name, "historical_python_dump") == 0 )
1057 myIsHistoricalPythonDump = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1058 msgToGUI = "preferences/SMESH/historical_python_dump/";
1059 msgToGUI += myIsHistoricalPythonDump ? "true" : "false";
1061 else if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1063 myToForgetMeshDataOnHypModif = ( value[0] == '1' || toupper(value[0]) == 'T' ); // 1 || true
1064 msgToGUI = "preferences/SMESH/forget_mesh_on_hyp_modif/";
1065 msgToGUI += myToForgetMeshDataOnHypModif ? "true" : "false";
1067 else if ( strcmp(name, "default_grp_color") == 0 )
1071 // color must be presented as a string of following form:
1072 if ( str.at(0) == '#' && str.length() == 7 ) { // hexadecimal color ("#ffaa00", for example)
1073 str = str.substr(1);
1074 for ( size_t i = 0; i < str.length()/2; i++ )
1075 if ( str.at(i*2) >= '0' && str.at(i*2) <= 'f' && str.at(i*2+1) >= '0' && str.at(i*2+1) <= 'f' )
1076 color.push_back( strtol( str.substr( i*2, 2 ).c_str(), NULL, 16 ) );
1078 else if ( value ) { // rgb color ("255,170,0", for example)
1079 string tempValue( value );
1080 char* colorValue = strtok( &tempValue[0], "," );
1081 while ( colorValue != NULL ) {
1082 int c_value = atoi( colorValue );
1083 if ( c_value >= 0 && c_value <= 255 )
1084 color.push_back( c_value );
1085 colorValue = strtok( NULL, "," );
1088 if ( color.size() == 3 ) { // color must have three valid component
1089 SMESHDS_GroupBase::SetDefaultColor( Quantity_Color( color[0]/255., color[1]/255., color[2]/255., Quantity_TOC_RGB ) );
1090 myDefaultGroupColor = value;
1091 msgToGUI = "preferences/SMESH/default_grp_color/";
1096 // update preferences in case if SetOption() is invoked from python console
1097 if ( !msgToGUI.empty() )
1099 CORBA::Object_var obj = SMESH_Gen_i::GetNS()->Resolve( "/Kernel/Session" );
1100 SALOME::Session_var session = SALOME::Session::_narrow( obj );
1101 if ( !CORBA::is_nil( session ) )
1102 session->emitMessageOneWay(msgToGUI.c_str());
1107 //=============================================================================
1109 Return an option value
1111 //=============================================================================
1113 char* SMESH_Gen_i::GetOption(const char* name)
1117 if ( strcmp(name, "historical_python_dump") == 0 )
1119 return CORBA::string_dup( myIsHistoricalPythonDump ? "true" : "false" );
1121 if ( strcmp(name, "forget_mesh_on_hyp_modif") == 0 )
1123 return CORBA::string_dup( myToForgetMeshDataOnHypModif ? "true" : "false" );
1125 if ( strcmp(name, "default_grp_color") == 0 )
1127 return CORBA::string_dup( myDefaultGroupColor.c_str() );
1130 return CORBA::string_dup( "" );
1133 //=============================================================================
1135 * SMESH_Gen_i::CreateMesh
1137 * Create empty mesh on a shape and publish it in the study
1139 //=============================================================================
1141 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMesh( GEOM::GEOM_Object_ptr theShapeObject )
1142 throw ( SALOME::SALOME_Exception )
1144 Unexpect aCatch(SALOME_SalomeException);
1145 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1147 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1149 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( mesh );
1150 ASSERT( meshServant );
1151 meshServant->SetShape( theShapeObject );
1153 // publish mesh in the study
1154 if ( CanPublishInStudy( mesh ) ) {
1155 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1156 aStudyBuilder->NewCommand(); // There is a transaction
1157 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1158 aStudyBuilder->CommitCommand();
1159 if ( !aSO->_is_nil() ) {
1160 // Update Python script
1161 TPythonDump() << aSO << " = " << this << ".CreateMesh(" << theShapeObject << ")";
1165 return mesh._retn();
1168 //=============================================================================
1170 * SMESH_Gen_i::CreateEmptyMesh
1174 //=============================================================================
1176 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateEmptyMesh()
1177 throw ( SALOME::SALOME_Exception )
1179 Unexpect aCatch(SALOME_SalomeException);
1180 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::CreateMesh" );
1182 SMESH::SMESH_Mesh_var mesh = this->createMesh();
1184 // publish mesh in the study
1185 if ( CanPublishInStudy( mesh ) ) {
1186 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1187 aStudyBuilder->NewCommand(); // There is a transaction
1188 SALOMEDS::SObject_wrap aSO = PublishMesh( mesh.in() );
1189 aStudyBuilder->CommitCommand();
1190 if ( !aSO->_is_nil() ) {
1191 // Update Python script
1192 TPythonDump() << aSO << " = " << this << ".CreateEmptyMesh()";
1196 return mesh._retn();
1201 //================================================================================
1203 * \brief Throws an exception in case if the file can't be read
1205 //================================================================================
1207 void checkFileReadable( const char* theFileName ) throw ( SALOME::SALOME_Exception )
1209 SMESH_File f ( theFileName );
1212 if ( !f.error().empty() )
1213 THROW_SALOME_CORBA_EXCEPTION( f.error().c_str(), SALOME::BAD_PARAM);
1215 THROW_SALOME_CORBA_EXCEPTION
1216 (( SMESH_Comment("Can't open for reading the file ") << theFileName ).c_str(),
1217 SALOME::BAD_PARAM );
1222 //=============================================================================
1224 * SMESH_Gen_i::CreateMeshFromUNV
1226 * Create mesh and import data from UNV file
1228 //=============================================================================
1230 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromUNV( const char* theFileName )
1231 throw ( SALOME::SALOME_Exception )
1233 Unexpect aCatch(SALOME_SalomeException);
1235 checkFileReadable( theFileName );
1237 SMESH::SMESH_Mesh_var aMesh = createMesh();
1239 // publish mesh in the study
1240 if ( CanPublishInStudy( aMesh ) ) {
1241 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1242 aStudyBuilder->NewCommand(); // There is a transaction
1243 SALOMEDS::SObject_wrap aSO = PublishMesh( aMesh.in(), aFileName.c_str() );
1244 aStudyBuilder->CommitCommand();
1245 if ( !aSO->_is_nil() ) {
1246 // Update Python script
1247 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromUNV(r'" << theFileName << "')";
1251 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1253 aServant->ImportUNVFile( theFileName );
1255 // Dump creation of groups
1256 SMESH::ListOfGroups_var groups = aServant->GetGroups();
1258 aServant->GetImpl().GetMeshDS()->Modified();
1259 return aMesh._retn();
1262 //=============================================================================
1264 * SMESH_Gen_i::CreateMeshFromMED
1266 * Create mesh and import data from MED file
1268 //=============================================================================
1270 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMEDorSAUV( const char* theFileName,
1271 SMESH::DriverMED_ReadStatus& theStatus,
1272 const char* theCommandNameForPython,
1273 const char* theFileNameForPython)
1276 char bname[ _MAX_FNAME ];
1277 _splitpath( theFileNameForPython, NULL, NULL, bname, NULL );
1278 string aFileName = bname;
1280 string aFileName = basename( const_cast<char *>(theFileNameForPython) );
1282 // Retrieve mesh names from the file
1283 DriverMED_R_SMESHDS_Mesh myReader;
1284 myReader.SetFile( theFileName );
1285 myReader.SetMeshId( -1 );
1286 Driver_Mesh::Status aStatus;
1287 list<string> aNames = myReader.GetMeshNames(aStatus);
1288 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1289 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1291 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1294 TPythonDump aPythonDump;
1295 aPythonDump << "([";
1297 if (theStatus == SMESH::DRS_OK) {
1298 SALOMEDS::StudyBuilder_var aStudyBuilder;
1299 aStudyBuilder = getStudyServant()->NewBuilder();
1300 aStudyBuilder->NewCommand(); // There is a transaction
1302 aResult->length( aNames.size() );
1305 // Iterate through all meshes and create mesh objects
1306 for ( list<string>::iterator it = aNames.begin(); it != aNames.end(); it++ )
1309 if (i > 0) aPythonDump << ", ";
1312 SMESH::SMESH_Mesh_var mesh = createMesh();
1314 // publish mesh in the study
1315 SALOMEDS::SObject_wrap aSO;
1316 if ( CanPublishInStudy( mesh ) )
1317 // little trick: for MED file theFileName and theFileNameForPython are the same, but they are different for SAUV
1318 // - as names of meshes are stored in MED file, we use them for data publishing
1319 // - as mesh name is not stored in UNV file, we use file name as name of mesh when publishing data
1320 aSO = PublishMesh( mesh.in(), ( theFileName == theFileNameForPython ) ? (*it).c_str() : aFileName.c_str() );
1323 if ( !aSO->_is_nil() ) {
1326 aPythonDump << "mesh_" << i;
1329 // Read mesh data (groups are published automatically by ImportMEDFile())
1330 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1331 ASSERT( meshServant );
1332 SMESH::DriverMED_ReadStatus status1 =
1333 meshServant->ImportMEDFile( theFileName, (*it).c_str() );
1334 if (status1 > theStatus)
1335 theStatus = status1;
1337 aResult[i++] = SMESH::SMESH_Mesh::_duplicate( mesh );
1338 meshServant->GetImpl().GetMeshDS()->Modified();
1340 if ( !aStudyBuilder->_is_nil() )
1341 aStudyBuilder->CommitCommand();
1344 // Update Python script
1345 aPythonDump << "], status) = " << this << "." << theCommandNameForPython << "(r'" << theFileNameForPython << "')";
1347 // Dump creation of groups
1348 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1349 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1351 return aResult._retn();
1354 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromMED( const char* theFileName,
1355 SMESH::DriverMED_ReadStatus& theStatus)
1356 throw ( SALOME::SALOME_Exception )
1358 Unexpect aCatch(SALOME_SalomeException);
1359 checkFileReadable( theFileName );
1361 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(theFileName, theStatus, "CreateMeshesFromMED", theFileName);
1365 //=============================================================================
1367 * SMESH_Gen_i::CreateMeshFromSAUV
1369 * Create mesh and import data from SAUV file
1371 //=============================================================================
1373 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromSAUV( const char* theFileName,
1374 SMESH::DriverMED_ReadStatus& theStatus)
1375 throw ( SALOME::SALOME_Exception )
1377 Unexpect aCatch(SALOME_SalomeException);
1378 checkFileReadable( theFileName );
1380 std::string sauvfilename(theFileName);
1381 std::string medfilename(theFileName);
1382 medfilename += ".med";
1385 cmd = "%PYTHONBIN% ";
1390 cmd += "from medutilities import convert ; convert(r'" + sauvfilename + "', 'GIBI', 'MED', 1, r'" + medfilename + "')";
1392 system(cmd.c_str());
1393 SMESH::mesh_array* result = CreateMeshesFromMEDorSAUV(medfilename.c_str(), theStatus, "CreateMeshesFromSAUV", sauvfilename.c_str());
1395 cmd = "%PYTHONBIN% ";
1400 cmd += "from medutilities import my_remove ; my_remove(r'" + medfilename + "')";
1402 system(cmd.c_str());
1406 //=============================================================================
1408 * SMESH_Gen_i::CreateMeshFromSTL
1410 * Create mesh and import data from STL file
1412 //=============================================================================
1414 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CreateMeshesFromSTL( const char* theFileName )
1415 throw ( SALOME::SALOME_Exception )
1417 Unexpect aCatch(SALOME_SalomeException);
1418 checkFileReadable( theFileName );
1420 SMESH::SMESH_Mesh_var aMesh = createMesh();
1423 char bname[ _MAX_FNAME ];
1424 _splitpath( theFileName, NULL, NULL, bname, NULL );
1425 string aFileName = bname;
1427 string aFileName = basename( const_cast<char *>(theFileName) );
1429 // publish mesh in the study
1430 if ( CanPublishInStudy( aMesh ) ) {
1431 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1432 aStudyBuilder->NewCommand(); // There is a transaction
1433 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1434 aStudyBuilder->CommitCommand();
1435 if ( !aSO->_is_nil() ) {
1436 // Update Python script
1437 TPythonDump() << aSO << " = " << this << ".CreateMeshesFromSTL(r'" << theFileName << "')";
1441 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1443 aServant->ImportSTLFile( theFileName );
1444 aServant->GetImpl().GetMeshDS()->Modified();
1445 return aMesh._retn();
1448 //================================================================================
1450 * \brief Create meshes and import data from the CGSN file
1452 //================================================================================
1454 SMESH::mesh_array* SMESH_Gen_i::CreateMeshesFromCGNS( const char* theFileName,
1455 SMESH::DriverMED_ReadStatus& theStatus)
1456 throw ( SALOME::SALOME_Exception )
1458 Unexpect aCatch(SALOME_SalomeException);
1459 checkFileReadable( theFileName );
1461 SMESH::mesh_array_var aResult = new SMESH::mesh_array();
1464 // Retrieve nb meshes from the file
1465 DriverCGNS_Read myReader;
1466 myReader.SetFile( theFileName );
1467 Driver_Mesh::Status aStatus;
1468 int nbMeshes = myReader.GetNbMeshes(aStatus);
1469 theStatus = (SMESH::DriverMED_ReadStatus)aStatus;
1471 aResult->length( nbMeshes );
1473 { // open a new scope to make aPythonDump die before PythonDump in SMESH_Mesh::GetGroups()
1476 TPythonDump aPythonDump;
1477 aPythonDump << "([";
1479 if (theStatus == SMESH::DRS_OK)
1481 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1482 aStudyBuilder->NewCommand(); // There is a transaction
1486 // Iterate through all meshes and create mesh objects
1487 for ( ; i < nbMeshes; ++i )
1490 if (i > 0) aPythonDump << ", ";
1493 SMESH::SMESH_Mesh_var mesh = createMesh();
1494 aResult[i] = SMESH::SMESH_Mesh::_duplicate( mesh );
1496 // Read mesh data (groups are published automatically by ImportMEDFile())
1497 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
1498 ASSERT( meshServant );
1500 SMESH::DriverMED_ReadStatus status1 =
1501 meshServant->ImportCGNSFile( theFileName, i, meshName );
1502 if (status1 > theStatus)
1503 theStatus = status1;
1505 meshServant->GetImpl().GetMeshDS()->Modified();
1506 // publish mesh in the study
1507 SALOMEDS::SObject_wrap aSO;
1508 if ( CanPublishInStudy( mesh ) )
1509 aSO = PublishMesh( mesh.in(), meshName.c_str() );
1512 if ( !aSO->_is_nil() ) {
1516 aPythonDump << "mesh_" << i;
1519 aStudyBuilder->CommitCommand();
1522 aPythonDump << "], status) = " << this << ".CreateMeshesFromCGNS(r'" << theFileName << "')";
1524 // Dump creation of groups
1525 for ( CORBA::ULong i = 0; i < aResult->length(); ++i )
1526 SMESH::ListOfGroups_var groups = aResult[ i ]->GetGroups();
1528 THROW_SALOME_CORBA_EXCEPTION("CGNS library is unavailable", SALOME::INTERNAL_ERROR);
1531 return aResult._retn();
1534 //================================================================================
1536 * \brief Create a mesh and import data from a GMF file
1538 //================================================================================
1540 SMESH::SMESH_Mesh_ptr
1541 SMESH_Gen_i::CreateMeshesFromGMF( const char* theFileName,
1542 CORBA::Boolean theMakeRequiredGroups,
1543 SMESH::ComputeError_out theError)
1544 throw ( SALOME::SALOME_Exception )
1546 Unexpect aCatch(SALOME_SalomeException);
1547 checkFileReadable( theFileName );
1549 SMESH::SMESH_Mesh_var aMesh = createMesh();
1551 char bname[ _MAX_FNAME ];
1552 _splitpath( theFileName, NULL, NULL, bname, NULL );
1553 string aFileName = bname;
1555 string aFileName = basename( const_cast<char *>(theFileName) );
1557 // publish mesh in the study
1558 if ( CanPublishInStudy( aMesh ) ) {
1559 SALOMEDS::StudyBuilder_var aStudyBuilder = getStudyServant()->NewBuilder();
1560 aStudyBuilder->NewCommand(); // There is a transaction
1561 SALOMEDS::SObject_wrap aSO = PublishInStudy( SALOMEDS::SObject::_nil(), aMesh.in(), aFileName.c_str() );
1562 aStudyBuilder->CommitCommand();
1563 if ( !aSO->_is_nil() ) {
1564 // Update Python script
1565 TPythonDump() << "("<< aSO << ", error) = " << this << ".CreateMeshesFromGMF(r'"
1566 << theFileName << "', "
1567 << theMakeRequiredGroups << " )";
1570 SMESH_Mesh_i* aServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( aMesh ).in() );
1572 theError = aServant->ImportGMFFile( theFileName, theMakeRequiredGroups );
1573 aServant->GetImpl().GetMeshDS()->Modified();
1574 return aMesh._retn();
1578 //=============================================================================
1580 * SMESH_Gen_i::IsReadyToCompute
1582 * Returns true if mesh contains enough data to be computed
1584 //=============================================================================
1586 CORBA::Boolean SMESH_Gen_i::IsReadyToCompute( SMESH::SMESH_Mesh_ptr theMesh,
1587 GEOM::GEOM_Object_ptr theShapeObject )
1588 throw ( SALOME::SALOME_Exception )
1590 Unexpect aCatch(SALOME_SalomeException);
1591 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IsReadyToCompute" );
1593 if ( CORBA::is_nil( theShapeObject ) )
1594 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
1595 SALOME::BAD_PARAM );
1597 if ( CORBA::is_nil( theMesh ) )
1598 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
1599 SALOME::BAD_PARAM );
1603 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
1604 ASSERT( meshServant );
1605 if ( meshServant ) {
1606 // get local TopoDS_Shape
1607 TopoDS_Shape myLocShape = GeomObjectToShape( theShapeObject );
1608 // call implementation
1609 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1610 return myGen.CheckAlgoState( myLocMesh, myLocShape );
1613 catch ( SALOME_Exception& S_ex ) {
1614 INFOS( "catch exception "<< S_ex.what() );
1619 //================================================================================
1621 * \brief Find SObject for an algo
1623 //================================================================================
1625 SALOMEDS::SObject_ptr SMESH_Gen_i::GetAlgoSO(const ::SMESH_Algo* algo)
1628 SALOMEDS::Study_var aStudy = getStudyServant();
1629 if ( !aStudy->_is_nil() ) {
1630 // find algo in the study
1631 CORBA::String_var compDataType = ComponentDataType();
1632 SALOMEDS::SComponent_wrap father = aStudy->FindComponent( compDataType.in() );
1633 if ( !father->_is_nil() ) {
1634 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( father );
1635 for ( ; itBig->More(); itBig->Next() ) {
1636 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
1637 if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
1638 SALOMEDS::ChildIterator_wrap algoIt = aStudy->NewChildIterator( gotBranch );
1639 for ( ; algoIt->More(); algoIt->Next() ) {
1640 SALOMEDS::SObject_wrap algoSO = algoIt->Value();
1641 CORBA::Object_var algoIOR = SObjectToObject( algoSO );
1642 if ( !CORBA::is_nil( algoIOR )) {
1643 SMESH_Hypothesis_i* impl = SMESH::DownCast<SMESH_Hypothesis_i*>( algoIOR );
1644 if ( impl && impl->GetImpl() == algo )
1645 return algoSO._retn();
1647 } // loop on algo SO's
1650 } // SMESH component iterator
1654 return SALOMEDS::SObject::_nil();
1657 //================================================================================
1659 * \brief Return errors of mesh computation
1661 //================================================================================
1663 SMESH::compute_error_array* SMESH_Gen_i::GetComputeErrors( SMESH::SMESH_Mesh_ptr theMesh,
1664 GEOM::GEOM_Object_ptr theSubObject )
1665 throw ( SALOME::SALOME_Exception )
1667 Unexpect aCatch(SALOME_SalomeException);
1668 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetComputeErrors()" );
1670 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1671 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1673 if ( CORBA::is_nil( theMesh ) )
1674 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1676 SMESH::compute_error_array_var error_array = new SMESH::compute_error_array;
1678 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1681 if(theMesh->HasShapeToMesh())
1682 shape = GeomObjectToShape( theSubObject );
1684 shape = SMESH_Mesh::PseudoShape();
1686 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1688 error_array->length( mesh.GetMeshDS()->MaxShapeIndex() );
1691 SMESH_subMesh *sm = mesh.GetSubMesh(shape);
1692 const bool includeSelf = true, complexShapeFirst = true;
1693 SMESH_subMeshIteratorPtr smIt = sm->getDependsOnIterator(includeSelf,
1695 while ( smIt->more() )
1698 // if ( sm->GetSubShape().ShapeType() == TopAbs_VERTEX )
1700 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1701 if ( error && !error->IsOK() )
1703 if ( !( error->myAlgo ) &&
1704 !( error->myAlgo = sm->GetAlgo() ))
1706 SMESH::ComputeError & errStruct = error_array[ nbErr++ ];
1707 errStruct.code = -( error->myName < 0 ? error->myName + 1: error->myName ); // -1 -> 0
1708 errStruct.comment = error->myComment.c_str();
1709 errStruct.subShapeID = sm->GetId();
1710 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->myAlgo );
1711 if ( !algoSO->_is_nil() ) {
1712 CORBA::String_var algoName = algoSO->GetName();
1713 errStruct.algoName = algoName;
1716 errStruct.algoName = error->myAlgo->GetName();
1718 errStruct.hasBadMesh = error->HasBadElems();
1721 error_array->length( nbErr );
1724 catch ( SALOME_Exception& S_ex ) {
1725 INFOS( "catch exception "<< S_ex.what() );
1728 return error_array._retn();
1731 //================================================================================
1733 * \brief Return mesh elements preventing computation of a subshape
1735 //================================================================================
1737 SMESH::MeshPreviewStruct*
1738 SMESH_Gen_i::GetBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1739 CORBA::Short theSubShapeID )
1740 throw ( SALOME::SALOME_Exception )
1742 Unexpect aCatch(SALOME_SalomeException);
1743 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetBadInputElements()" );
1745 if ( CORBA::is_nil( theMesh ) )
1746 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1748 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
1751 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1753 // mesh implementation
1754 ::SMESH_Mesh& mesh = meshServant->GetImpl();
1755 // submesh by subshape id
1756 if ( SMESH_subMesh * sm = mesh.GetSubMeshContaining( theSubShapeID ))
1759 SMESH_ComputeErrorPtr error = sm->GetComputeError();
1760 if ( error && error->HasBadElems() )
1762 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
1763 typedef TNode2LocalIDMap::iterator TNodeLocalID;
1765 // get nodes of elements and count elements
1766 TNode2LocalIDMap mapNode2LocalID;
1767 list< TNodeLocalID > connectivity;
1768 int i, nbElements = 0, nbConnNodes = 0;
1770 const list<const SMDS_MeshElement*>& badElems =
1771 static_cast<SMESH_BadInputElements*>( error.get() )->myBadElements;
1772 list<const SMDS_MeshElement*>::const_iterator elemIt = badElems.begin();
1773 list<const SMDS_MeshElement*>::const_iterator elemEnd = badElems.end();
1774 for ( ; elemIt != elemEnd; ++elemIt, ++nbElements )
1776 SMDS_ElemIteratorPtr nIt = (*elemIt)->nodesIterator();
1777 while ( nIt->more() )
1778 connectivity.push_back
1779 ( mapNode2LocalID.insert( make_pair( nIt->next(), ++nbConnNodes)).first );
1781 // fill node coords and assign local ids to the nodes
1782 int nbNodes = mapNode2LocalID.size();
1783 result->nodesXYZ.length( nbNodes );
1784 TNodeLocalID node2ID = mapNode2LocalID.begin();
1785 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
1786 node2ID->second = i;
1787 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
1788 result->nodesXYZ[i].x = node->X();
1789 result->nodesXYZ[i].y = node->Y();
1790 result->nodesXYZ[i].z = node->Z();
1792 // fill connectivity
1793 result->elementConnectivities.length( nbConnNodes );
1794 list< TNodeLocalID >::iterator connIt = connectivity.begin();
1795 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
1796 result->elementConnectivities[i] = (*connIt)->second;
1798 // fill element types
1799 result->elementTypes.length( nbElements );
1800 for ( i = 0, elemIt = badElems.begin(); i <nbElements; ++i, ++elemIt )
1802 const SMDS_MeshElement* elem = *elemIt;
1803 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType) elem->GetType();
1804 result->elementTypes[i].isPoly = elem->IsPoly();
1805 result->elementTypes[i].nbNodesInElement = elem->NbNodes();
1811 catch ( SALOME_Exception& S_ex ) {
1812 INFOS( "catch exception "<< S_ex.what() );
1815 return result._retn();
1818 //================================================================================
1820 * \brief Create a group of elements preventing computation of a sub-shape
1822 //================================================================================
1824 SMESH::ListOfGroups*
1825 SMESH_Gen_i::MakeGroupsOfBadInputElements( SMESH::SMESH_Mesh_ptr theMesh,
1826 CORBA::Short theSubShapeID,
1827 const char* theGroupName )
1828 throw ( SALOME::SALOME_Exception )
1830 Unexpect aCatch(SALOME_SalomeException);
1832 SMESH::ListOfGroups_var groups;
1834 if ( CORBA::is_nil( theMesh ) )
1835 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1838 if ( SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh ))
1840 groups = meshServant->MakeGroupsOfBadInputElements( theSubShapeID, theGroupName );
1841 TPythonDump() << groups << " = " << this
1842 << ".MakeGroupsOfBadInputElements( "
1843 << theMesh << ", " << theSubShapeID << ", '" << theGroupName << "' )";
1846 catch ( SALOME_Exception& S_ex ) {
1847 INFOS( "catch exception "<< S_ex.what() );
1849 return groups._retn();
1852 //================================================================================
1854 * \brief Returns errors of hypotheses definition
1855 * \param theMesh - the mesh
1856 * \param theSubObject - the main or sub- shape
1857 * \retval SMESH::algo_error_array* - sequence of errors
1859 //================================================================================
1861 SMESH::algo_error_array* SMESH_Gen_i::GetAlgoState( SMESH::SMESH_Mesh_ptr theMesh,
1862 GEOM::GEOM_Object_ptr theSubObject )
1863 throw ( SALOME::SALOME_Exception )
1865 Unexpect aCatch(SALOME_SalomeException);
1866 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetAlgoState()" );
1868 if ( CORBA::is_nil( theSubObject ) && theMesh->HasShapeToMesh())
1869 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1871 if ( CORBA::is_nil( theMesh ) )
1872 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",SALOME::BAD_PARAM );
1874 SMESH::algo_error_array_var error_array = new SMESH::algo_error_array;
1876 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
1877 ASSERT( meshServant );
1878 if ( meshServant ) {
1879 TopoDS_Shape myLocShape;
1880 if(theMesh->HasShapeToMesh())
1881 myLocShape = GeomObjectToShape( theSubObject );
1883 myLocShape = SMESH_Mesh::PseudoShape();
1885 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
1886 list< ::SMESH_Gen::TAlgoStateError > error_list;
1887 list< ::SMESH_Gen::TAlgoStateError >::iterator error;
1888 // call ::SMESH_Gen::GetAlgoState()
1889 myGen.GetAlgoState( myLocMesh, myLocShape, error_list );
1890 error_array->length( error_list.size() );
1892 for ( error = error_list.begin(); error != error_list.end(); ++error )
1894 // fill AlgoStateError structure
1895 SMESH::AlgoStateError & errStruct = error_array[ i++ ];
1896 errStruct.state = SMESH_Mesh_i::ConvertHypothesisStatus( error->_name );
1897 errStruct.algoDim = error->_algoDim;
1898 errStruct.isGlobalAlgo = error->_isGlobalAlgo;
1899 errStruct.algoName = "";
1900 SALOMEDS::SObject_wrap algoSO = GetAlgoSO( error->_algo );
1901 if ( !algoSO->_is_nil() ) {
1902 CORBA::String_var algoName = algoSO->GetName();
1903 errStruct.algoName = algoName.in();
1908 catch ( SALOME_Exception& S_ex ) {
1909 INFOS( "catch exception "<< S_ex.what() );
1911 return error_array._retn();
1914 //=============================================================================
1916 * SMESH_Gen_i::GetSubShapesId
1918 * Get sub-shapes unique ID's list
1920 //=============================================================================
1923 SMESH_Gen_i::GetSubShapesId( GEOM::GEOM_Object_ptr theMainShapeObject,
1924 const SMESH::object_array& theListOfSubShapeObject )
1925 throw ( SALOME::SALOME_Exception )
1927 Unexpect aCatch(SALOME_SalomeException);
1928 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::GetSubShapesId" );
1930 SMESH::long_array_var shapesId = new SMESH::long_array;
1933 if ( CORBA::is_nil( theMainShapeObject ) )
1934 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference", SALOME::BAD_PARAM );
1938 TopoDS_Shape myMainShape = GeomObjectToShape(theMainShapeObject);
1939 TopTools_IndexedMapOfShape myIndexToShape;
1940 TopExp::MapShapes(myMainShape,myIndexToShape);
1942 for ( CORBA::ULong i = 0; i < theListOfSubShapeObject.length(); i++ )
1944 GEOM::GEOM_Object_var aShapeObject
1945 = GEOM::GEOM_Object::_narrow(theListOfSubShapeObject[i]);
1946 if ( CORBA::is_nil( aShapeObject ) )
1947 THROW_SALOME_CORBA_EXCEPTION ("bad shape object reference", \
1948 SALOME::BAD_PARAM );
1950 TopoDS_Shape locShape = GeomObjectToShape(aShapeObject);
1951 for (TopExp_Explorer exp(locShape,TopAbs_FACE); exp.More(); exp.Next())
1953 const TopoDS_Face& F = TopoDS::Face(exp.Current());
1954 setId.insert(myIndexToShape.FindIndex(F));
1955 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(F));
1957 for (TopExp_Explorer exp(locShape,TopAbs_EDGE); exp.More(); exp.Next())
1959 const TopoDS_Edge& E = TopoDS::Edge(exp.Current());
1960 setId.insert(myIndexToShape.FindIndex(E));
1961 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(E));
1963 for (TopExp_Explorer exp(locShape,TopAbs_VERTEX); exp.More(); exp.Next())
1965 const TopoDS_Vertex& V = TopoDS::Vertex(exp.Current());
1966 setId.insert(myIndexToShape.FindIndex(V));
1967 if(MYDEBUG) SCRUTE(myIndexToShape.FindIndex(V));
1970 shapesId->length(setId.size());
1971 set<int>::iterator iind;
1973 for (iind = setId.begin(); iind != setId.end(); iind++)
1975 if(MYDEBUG) SCRUTE((*iind));
1976 shapesId[i] = (*iind);
1977 if(MYDEBUG) SCRUTE(shapesId[i]);
1981 catch (SALOME_Exception& S_ex)
1983 THROW_SALOME_CORBA_EXCEPTION(S_ex.what(), SALOME::BAD_PARAM);
1986 return shapesId._retn();
1989 //=============================================================================
1991 * SMESH_Gen_i::Compute
1993 * Compute mesh on a shape
1995 //=============================================================================
1997 CORBA::Boolean SMESH_Gen_i::Compute( SMESH::SMESH_Mesh_ptr theMesh,
1998 GEOM::GEOM_Object_ptr theShapeObject )
1999 throw ( SALOME::SALOME_Exception )
2002 Unexpect aCatch(SALOME_SalomeException);
2003 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Compute" );
2005 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2006 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2007 SALOME::BAD_PARAM );
2009 if ( CORBA::is_nil( theMesh ) )
2010 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2011 SALOME::BAD_PARAM );
2013 // Update Python script
2014 TPythonDump() << "isDone = " << this << ".Compute( "
2015 << theMesh << ", " << theShapeObject << ")";
2019 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2020 ASSERT( meshServant );
2021 if ( meshServant ) {
2022 meshServant->Load();
2023 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2024 // Clear meshy because it was not cleared in CheckGeomModif of previous call
2025 meshServant->Clear();
2026 meshServant->CheckGeomModif();
2027 // get local TopoDS_Shape
2028 TopoDS_Shape myLocShape;
2029 if(theMesh->HasShapeToMesh())
2030 myLocShape = GeomObjectToShape( theShapeObject );
2032 myLocShape = SMESH_Mesh::PseudoShape();
2033 // call implementation compute
2034 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2035 myGen.PrepareCompute( myLocMesh, myLocShape );
2036 int how = ::SMESH_Gen::COMPACT_MESH;
2037 if ( myLocShape != myLocMesh.GetShapeToMesh() ) // compute a sub-mesh
2038 how |= ::SMESH_Gen::SHAPE_ONLY;
2039 bool ok = myGen.Compute( myLocMesh, myLocShape, how );
2040 meshServant->CreateGroupServants(); // algos can create groups (issue 0020918)
2041 myLocMesh.GetMeshDS()->Modified();
2042 UpdateIcons( theMesh );
2044 HighLightInvalid( theMesh, /*isInvalid=*/false );
2048 catch ( std::bad_alloc ) {
2049 INFOS( "Compute(): lack of memory" );
2051 catch ( SALOME_Exception& S_ex ) {
2052 INFOS( "Compute(): catch exception "<< S_ex.what() );
2055 INFOS( "Compute(): unknown exception " );
2060 //=============================================================================
2062 * SMESH_Gen_i::CancelCompute
2064 * Cancel Compute mesh on a shape
2066 //=============================================================================
2068 void SMESH_Gen_i::CancelCompute( SMESH::SMESH_Mesh_ptr theMesh,
2069 GEOM::GEOM_Object_ptr theShapeObject )
2071 if ( SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() ))
2073 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2074 TopoDS_Shape myLocShape;
2075 if(theMesh->HasShapeToMesh())
2076 myLocShape = GeomObjectToShape( theShapeObject );
2078 myLocShape = SMESH_Mesh::PseudoShape();
2079 myGen.CancelCompute( myLocMesh, myLocShape);
2083 //=============================================================================
2085 * SMESH_Gen_i::Precompute
2087 * Compute mesh as preview till indicated dimension on shape
2089 //=============================================================================
2091 SMESH::MeshPreviewStruct* SMESH_Gen_i::Precompute( SMESH::SMESH_Mesh_ptr theMesh,
2092 GEOM::GEOM_Object_ptr theShapeObject,
2093 SMESH::Dimension theDimension,
2094 SMESH::long_array& theShapesId)
2095 throw ( SALOME::SALOME_Exception )
2097 Unexpect aCatch(SALOME_SalomeException);
2098 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Precompute" );
2100 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2101 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2102 SALOME::BAD_PARAM );
2104 if ( CORBA::is_nil( theMesh ) )
2105 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2106 SALOME::BAD_PARAM );
2108 SMESH::MeshPreviewStruct_var result = new SMESH::MeshPreviewStruct;
2111 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2112 meshServant->Load();
2113 ASSERT( meshServant );
2114 if ( meshServant ) {
2115 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2116 meshServant->CheckGeomModif();
2117 // get local TopoDS_Shape
2118 TopoDS_Shape myLocShape;
2119 if(theMesh->HasShapeToMesh())
2120 myLocShape = GeomObjectToShape( theShapeObject );
2122 return result._retn();;
2124 // call implementation compute
2125 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2127 ::MeshDimension aDim = (MeshDimension)theDimension;
2128 if ( myGen.Compute( myLocMesh, myLocShape, ::SMESH_Gen::COMPACT_MESH, aDim, &shapeIds ) )
2130 int nbShapeId = shapeIds.size();
2131 theShapesId.length( nbShapeId );
2132 // iterates on shapes and collect mesh entities into mesh preview
2133 TSetOfInt::const_iterator idIt = shapeIds.begin();
2134 TSetOfInt::const_iterator idEnd = shapeIds.end();
2135 std::map< int, int > mapOfShIdNb;
2136 std::set< SMESH_TLink > setOfEdge;
2137 std::list< SMDSAbs_ElementType > listOfElemType;
2138 typedef map<const SMDS_MeshElement*, int > TNode2LocalIDMap;
2139 typedef TNode2LocalIDMap::iterator TNodeLocalID;
2140 TNode2LocalIDMap mapNode2LocalID;
2141 list< TNodeLocalID > connectivity;
2142 int i, nbConnNodes = 0;
2143 std::set< const SMESH_subMesh* > setOfVSubMesh;
2144 // iterates on shapes
2145 for ( ; idIt != idEnd; idIt++ )
2147 if ( mapOfShIdNb.find( *idIt ) != mapOfShIdNb.end() )
2149 SMESH_subMesh* sm = myLocMesh.GetSubMeshContaining(*idIt);
2150 if ( !sm || !sm->IsMeshComputed() )
2153 const TopoDS_Shape& aSh = sm->GetSubShape();
2154 const int shDim = myGen.GetShapeDim( aSh );
2155 if ( shDim < 1 || shDim > theDimension )
2158 mapOfShIdNb[ *idIt ] = 0;
2159 theShapesId[ mapOfShIdNb.size() - 1 ] = *idIt;
2161 SMESHDS_SubMesh* smDS = sm->GetSubMeshDS();
2162 if ( !smDS ) continue;
2164 if ( theDimension == SMESH::DIM_2D )
2166 SMDS_ElemIteratorPtr faceIt = smDS->GetElements();
2167 while ( faceIt->more() )
2169 const SMDS_MeshElement* face = faceIt->next();
2170 int aNbNode = face->NbNodes();
2172 aNbNode /= 2; // do not take into account additional middle nodes
2174 SMDS_MeshNode* node1 = (SMDS_MeshNode*)face->GetNode( 0 );
2175 for ( int nIndx = 0; nIndx < aNbNode; nIndx++ )
2177 SMDS_MeshNode* node2 = (SMDS_MeshNode*)face->GetNode( nIndx+1 < aNbNode ? nIndx+1 : 0 );
2178 if ( setOfEdge.insert( SMESH_TLink ( node1, node2 ) ).second )
2180 listOfElemType.push_back( SMDSAbs_Edge );
2181 connectivity.push_back
2182 ( mapNode2LocalID.insert( make_pair( node1, ++nbConnNodes)).first );
2183 connectivity.push_back
2184 ( mapNode2LocalID.insert( make_pair( node2, ++nbConnNodes)).first );
2190 else if ( theDimension == SMESH::DIM_1D )
2192 SMDS_NodeIteratorPtr nodeIt = smDS->GetNodes();
2193 while ( nodeIt->more() )
2195 listOfElemType.push_back( SMDSAbs_Node );
2196 connectivity.push_back
2197 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2199 // add corner nodes by first vertex from edge
2200 SMESH_subMeshIteratorPtr edgeSmIt =
2201 sm->getDependsOnIterator(/*includeSelf*/false,
2202 /*complexShapeFirst*/false);
2203 while ( edgeSmIt->more() )
2205 SMESH_subMesh* vertexSM = edgeSmIt->next();
2206 // check that vertex is not already treated
2207 if ( !setOfVSubMesh.insert( vertexSM ).second )
2209 if ( vertexSM->GetSubShape().ShapeType() != TopAbs_VERTEX )
2212 const SMESHDS_SubMesh* vertexSmDS = vertexSM->GetSubMeshDS();
2213 SMDS_NodeIteratorPtr nodeIt = vertexSmDS->GetNodes();
2214 while ( nodeIt->more() )
2216 listOfElemType.push_back( SMDSAbs_Node );
2217 connectivity.push_back
2218 ( mapNode2LocalID.insert( make_pair( nodeIt->next(), ++nbConnNodes)).first );
2224 // fill node coords and assign local ids to the nodes
2225 int nbNodes = mapNode2LocalID.size();
2226 result->nodesXYZ.length( nbNodes );
2227 TNodeLocalID node2ID = mapNode2LocalID.begin();
2228 for ( i = 0; i < nbNodes; ++i, ++node2ID ) {
2229 node2ID->second = i;
2230 const SMDS_MeshNode* node = (const SMDS_MeshNode*) node2ID->first;
2231 result->nodesXYZ[i].x = node->X();
2232 result->nodesXYZ[i].y = node->Y();
2233 result->nodesXYZ[i].z = node->Z();
2235 // fill connectivity
2236 result->elementConnectivities.length( nbConnNodes );
2237 list< TNodeLocalID >::iterator connIt = connectivity.begin();
2238 for ( i = 0; i < nbConnNodes; ++i, ++connIt ) {
2239 result->elementConnectivities[i] = (*connIt)->second;
2242 // fill element types
2243 result->elementTypes.length( listOfElemType.size() );
2244 std::list< SMDSAbs_ElementType >::const_iterator typeIt = listOfElemType.begin();
2245 std::list< SMDSAbs_ElementType >::const_iterator typeEnd = listOfElemType.end();
2246 for ( i = 0; typeIt != typeEnd; ++i, ++typeIt )
2248 SMDSAbs_ElementType elemType = *typeIt;
2249 result->elementTypes[i].SMDS_ElementType = (SMESH::ElementType)elemType;
2250 result->elementTypes[i].isPoly = false;
2251 result->elementTypes[i].nbNodesInElement = elemType == SMDSAbs_Edge ? 2 : 1;
2254 // correct number of shapes
2255 theShapesId.length( mapOfShIdNb.size() );
2259 catch ( std::bad_alloc ) {
2260 INFOS( "Precompute(): lack of memory" );
2262 catch ( SALOME_Exception& S_ex ) {
2263 INFOS( "Precompute(): catch exception "<< S_ex.what() );
2266 INFOS( "Precompute(): unknown exception " );
2268 return result._retn();
2272 //=============================================================================
2274 * SMESH_Gen_i::Evaluate
2276 * Evaluate mesh on a shape
2278 //=============================================================================
2280 SMESH::long_array* SMESH_Gen_i::Evaluate(SMESH::SMESH_Mesh_ptr theMesh,
2281 GEOM::GEOM_Object_ptr theShapeObject)
2282 // SMESH::long_array& theNbElems)
2283 throw ( SALOME::SALOME_Exception )
2285 Unexpect aCatch(SALOME_SalomeException);
2286 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Evaluate" );
2288 if ( CORBA::is_nil( theShapeObject ) && theMesh->HasShapeToMesh())
2289 THROW_SALOME_CORBA_EXCEPTION( "bad shape object reference",
2290 SALOME::BAD_PARAM );
2292 if ( CORBA::is_nil( theMesh ) )
2293 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference",
2294 SALOME::BAD_PARAM );
2296 SMESH::long_array_var nbels = new SMESH::long_array;
2297 nbels->length(SMESH::Entity_Last);
2298 int i = SMESH::Entity_Node;
2299 for (; i < SMESH::Entity_Last; i++)
2302 // Update Python script
2303 TPythonDump() << "theNbElems = " << this << ".Evaluate( "
2304 << theMesh << ", " << theShapeObject << ")";
2308 SMESH_Mesh_i* meshServant = dynamic_cast<SMESH_Mesh_i*>( GetServant( theMesh ).in() );
2309 ASSERT( meshServant );
2310 if ( meshServant ) {
2311 meshServant->Load();
2312 // NPAL16168: "geometrical group edition from a submesh don't modify mesh computation"
2313 meshServant->CheckGeomModif();
2314 // get local TopoDS_Shape
2315 TopoDS_Shape myLocShape;
2316 if(theMesh->HasShapeToMesh())
2317 myLocShape = GeomObjectToShape( theShapeObject );
2319 myLocShape = SMESH_Mesh::PseudoShape();
2320 // call implementation compute
2321 ::SMESH_Mesh& myLocMesh = meshServant->GetImpl();
2322 MapShapeNbElems aResMap;
2323 /*CORBA::Boolean ret =*/ myGen.Evaluate( myLocMesh, myLocShape, aResMap);
2324 MapShapeNbElemsItr anIt = aResMap.begin();
2325 for(; anIt!=aResMap.end(); anIt++) {
2326 const vector<int>& aVec = (*anIt).second;
2327 for ( i = SMESH::Entity_Node; i < (int)aVec.size(); i++ ) {
2328 int nbElem = aVec[i];
2329 if ( nbElem < 0 ) // algo failed, check that it has reported a message
2331 SMESH_subMesh* sm = anIt->first;
2332 SMESH_ComputeErrorPtr& error = sm->GetComputeError();
2333 const SMESH_Algo* algo = sm->GetAlgo();
2334 if ( (algo && !error.get()) || error->IsOK() )
2335 error.reset( new SMESH_ComputeError( COMPERR_ALGO_FAILED,"Failed to evaluate",algo));
2339 nbels[i] += aVec[i];
2343 return nbels._retn();
2346 catch ( std::bad_alloc ) {
2347 INFOS( "Evaluate(): lack of memory" );
2349 catch ( SALOME_Exception& S_ex ) {
2350 INFOS( "Evaluate(): catch exception "<< S_ex.what() );
2353 INFOS( "Evaluate(): unknown exception " );
2356 return nbels._retn();
2359 //================================================================================
2361 * \brief Return geometrical object the given element is built on
2362 * \param theMesh - the mesh the element is in
2363 * \param theElementID - the element ID
2364 * \param theGeomName - the name of the result geom object if it is not yet published
2365 * \retval GEOM::GEOM_Object_ptr - the found or just published geom object (no need to UnRegister())
2367 //================================================================================
2369 GEOM::GEOM_Object_ptr
2370 SMESH_Gen_i::GetGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2371 CORBA::Long theElementID,
2372 const char* theGeomName)
2373 throw ( SALOME::SALOME_Exception )
2375 Unexpect aCatch(SALOME_SalomeException);
2377 GEOM::GEOM_Object_wrap geom = FindGeometryByMeshElement(theMesh, theElementID);
2378 if ( !geom->_is_nil() ) {
2379 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2380 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( geom );
2382 // try to find the corresponding SObject
2383 SALOMEDS::SObject_wrap SObj = ObjectToSObject( geom.in() );
2384 if ( SObj->_is_nil() ) // submesh can be not found even if published
2386 // try to find published submesh
2387 GEOM::ListOfLong_var list = geom->GetSubShapeIndices();
2388 if ( !geom->IsMainShape() && list->length() == 1 ) {
2389 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2390 SALOMEDS::ChildIterator_wrap it;
2391 if ( !mainSO->_is_nil() ) {
2392 it = getStudyServant()->NewChildIterator( mainSO );
2394 if ( !it->_is_nil() ) {
2395 for ( it->InitEx(true); it->More(); it->Next() ) {
2396 SALOMEDS::SObject_wrap so = it->Value();
2397 CORBA::Object_var obj = SObjectToObject( so );
2398 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2399 if ( !subGeom->_is_nil() ) {
2400 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2401 if ( subList->length() == 1 && list[0] == subList[0] ) {
2411 if ( SObj->_is_nil() && !geomGen->_is_nil() ) // publish a new subshape
2412 SObj = geomGen->AddInStudy( geom, theGeomName, mainShape );
2414 // return only published geometry
2415 if ( !SObj->_is_nil() ) {
2416 //return geom._retn(); -- servant of geom must be UnRegister()ed;
2417 CORBA::Object_var obj = SObjectToObject( SObj );
2418 GEOM::GEOM_Object_var go = GEOM::GEOM_Object::_narrow( obj );
2422 return GEOM::GEOM_Object::_nil();
2425 //================================================================================
2427 * \brief Return geometrical object the given element is built on.
2428 * \param theMesh - the mesh the element is in
2429 * \param theElementID - the element ID
2430 * \retval GEOM::GEOM_Object_ptr - the found or created (UnRegister()!) geom object
2432 //================================================================================
2434 GEOM::GEOM_Object_ptr
2435 SMESH_Gen_i::FindGeometryByMeshElement( SMESH::SMESH_Mesh_ptr theMesh,
2436 CORBA::Long theElementID)
2437 throw ( SALOME::SALOME_Exception )
2439 Unexpect aCatch(SALOME_SalomeException);
2440 if ( CORBA::is_nil( theMesh ) )
2441 THROW_SALOME_CORBA_EXCEPTION( "bad Mesh reference", SALOME::BAD_PARAM );
2443 GEOM::GEOM_Object_var mainShape = theMesh->GetShapeToMesh();
2444 GEOM::GEOM_Gen_var geomGen = GetGeomEngine( mainShape );
2446 // get a core mesh DS
2447 SMESH_Mesh_i* meshServant = SMESH::DownCast<SMESH_Mesh_i*>( theMesh );
2448 if ( meshServant && !geomGen->_is_nil() && !mainShape->_is_nil() )
2450 ::SMESH_Mesh & mesh = meshServant->GetImpl();
2451 SMESHDS_Mesh* meshDS = mesh.GetMeshDS();
2452 // find the element in mesh
2453 if ( const SMDS_MeshElement * elem = meshDS->FindElement( theElementID ) ) {
2454 // find a shape id by the element
2455 if ( int shapeID = ::SMESH_MeshEditor( &mesh ).FindShape( elem )) {
2456 // get a geom object by the shape id
2457 GEOM::GEOM_Object_var geom = ShapeToGeomObject( meshDS->IndexToShape( shapeID ));
2458 if ( geom->_is_nil() ) {
2459 // try to find a published sub-shape
2460 SALOMEDS::SObject_wrap mainSO = ObjectToSObject( mainShape );
2461 SALOMEDS::ChildIterator_wrap it;
2462 if ( !mainSO->_is_nil() ) {
2463 it = getStudyServant()->NewChildIterator( mainSO );
2465 if ( !it->_is_nil() ) {
2466 for ( it->InitEx(true); it->More(); it->Next() ) {
2467 SALOMEDS::SObject_wrap so = it->Value();
2468 CORBA::Object_var obj = SObjectToObject( so );
2469 GEOM::GEOM_Object_var subGeom = GEOM::GEOM_Object::_narrow( obj );
2470 if ( !subGeom->_is_nil() ) {
2471 GEOM::ListOfLong_var subList = subGeom->GetSubShapeIndices();
2472 if ( subList->length() == 1 && shapeID == subList[0] ) {
2480 if ( geom->_is_nil() ) {
2482 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
2483 if ( !op->_is_nil() )
2484 geom = op->GetSubShape( mainShape, shapeID );
2489 if ( !geom->_is_nil() ) {
2490 GeomObjectToShape( geom ); // let geom client remember the found shape
2491 return geom._retn();
2496 return GEOM::GEOM_Object::_nil();
2499 //================================================================================
2501 * SMESH_Gen_i::Concatenate
2503 * Concatenate the given meshes into one mesh
2505 //================================================================================
2507 SMESH::SMESH_Mesh_ptr
2508 SMESH_Gen_i::Concatenate(const SMESH::ListOfIDSources& theMeshesArray,
2509 CORBA::Boolean theUniteIdenticalGroups,
2510 CORBA::Boolean theMergeNodesAndElements,
2511 CORBA::Double theMergeTolerance,
2512 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2513 throw ( SALOME::SALOME_Exception )
2515 return ConcatenateCommon(theMeshesArray,
2516 theUniteIdenticalGroups,
2517 theMergeNodesAndElements,
2523 //================================================================================
2525 * SMESH_Gen_i::ConcatenateWithGroups
2527 * Concatenate the given meshes into one mesh
2528 * Create the groups of all elements from initial meshes
2530 //================================================================================
2532 SMESH::SMESH_Mesh_ptr
2533 SMESH_Gen_i::ConcatenateWithGroups(const SMESH::ListOfIDSources& theMeshesArray,
2534 CORBA::Boolean theUniteIdenticalGroups,
2535 CORBA::Boolean theMergeNodesAndElements,
2536 CORBA::Double theMergeTolerance,
2537 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2538 throw ( SALOME::SALOME_Exception )
2540 return ConcatenateCommon(theMeshesArray,
2541 theUniteIdenticalGroups,
2542 theMergeNodesAndElements,
2548 //================================================================================
2550 * SMESH_Gen_i::ConcatenateCommon
2552 * Concatenate the given meshes into one mesh
2554 //================================================================================
2556 SMESH::SMESH_Mesh_ptr
2557 SMESH_Gen_i::ConcatenateCommon(const SMESH::ListOfIDSources& theMeshesArray,
2558 CORBA::Boolean theUniteIdenticalGroups,
2559 CORBA::Boolean theMergeNodesAndElements,
2560 CORBA::Double theMergeTolerance,
2561 CORBA::Boolean theCommonGroups,
2562 SMESH::SMESH_Mesh_ptr theMeshToAppendTo)
2563 throw ( SALOME::SALOME_Exception )
2565 std::unique_ptr< TPythonDump > pPythonDump( new TPythonDump );
2566 TPythonDump& pythonDump = *pPythonDump; // prevent dump of called methods
2568 // create mesh if theMeshToAppendTo not provided
2569 SMESH::SMESH_Mesh_var newMesh;
2570 if ( CORBA::is_nil( theMeshToAppendTo ))
2571 newMesh = CreateEmptyMesh();
2573 newMesh = SMESH::SMESH_Mesh::_duplicate( theMeshToAppendTo );
2574 SMESH_Mesh_i* newImpl = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2575 if ( !newImpl ) return newMesh._retn();
2578 ::SMESH_Mesh& locMesh = newImpl->GetImpl();
2579 SMESHDS_Mesh* newMeshDS = locMesh.GetMeshDS();
2581 typedef std::list<SMESH::SMESH_Group_var> TListOfNewGroups;
2582 typedef std::pair<string, SMESH::ElementType > TNameAndType;
2583 typedef std::map< TNameAndType, TListOfNewGroups > TGroupsMap;
2584 TGroupsMap groupsMap;
2585 TListOfNewGroups listOfNewGroups;
2587 if ( !CORBA::is_nil( theMeshToAppendTo ))
2589 // fill groupsMap with existing groups
2590 SMESH::ListOfGroups_var groups = theMeshToAppendTo->GetGroups();
2591 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
2593 SMESH::SMESH_Group_var group = SMESH::SMESH_Group::_narrow( groups[ i ]);
2594 if ( !group->_is_nil() )
2596 CORBA::String_var name = group->GetName();
2597 SMESH::ElementType type = group->GetType();
2598 groupsMap[ TNameAndType( name.in(), type ) ].push_back( group );
2603 ::SMESH_MeshEditor newEditor( &locMesh );
2604 ::SMESH_MeshEditor::ElemFeatures elemType;
2606 // loop on sub-meshes
2607 for ( CORBA::ULong i = 0; i < theMeshesArray.length(); i++ )
2609 if ( CORBA::is_nil( theMeshesArray[i] )) continue;
2610 SMESH::SMESH_Mesh_var initMesh = theMeshesArray[i]->GetMesh();
2611 SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( initMesh );
2612 if ( !initImpl ) continue;
2613 if ( initMesh->_is_equivalent( theMeshToAppendTo ))
2617 // assure that IDs increment by one during iteration
2618 ::SMESH_Mesh& initLocMesh = initImpl->GetImpl();
2619 SMESHDS_Mesh* initMeshDS = initLocMesh.GetMeshDS();
2620 if ( initMeshDS->MaxNodeID() > initMeshDS->NbNodes() ||
2621 initMeshDS->MaxElementID() > initMeshDS->NbElements() )
2623 initMeshDS->Modified();
2624 initMeshDS->CompactMesh();
2627 // remember nb of elements before filling in
2628 SMESH::long_array_var prevState = newMesh->GetNbElementsByType();
2632 std::vector< const SMDS_MeshElement* > newNodes( initMeshDS->NbNodes() + 1, 0 );
2633 SMDS_ElemIteratorPtr elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::NODE );
2634 while ( elemIt->more() )
2636 SMESH_NodeXYZ node = elemIt->next();
2637 newNodes[ node->GetID() ] = newMeshDS->AddNode( node.X(), node.Y(), node.Z() );
2642 SMESH::array_of_ElementType_var srcElemTypes = theMeshesArray[i]->GetTypes();
2643 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2645 std::vector< const SMDS_MeshElement* > newElems( initMeshDS->NbElements() + 1, 0 );
2646 elemIt = initImpl->GetElements( theMeshesArray[i], SMESH::ALL );
2647 while ( elemIt->more() )
2649 const SMDS_MeshElement* elem = elemIt->next();
2650 elemType.myNodes.resize( elem->NbNodes() );
2652 SMDS_NodeIteratorPtr itNodes = elem->nodeIterator();
2653 for ( int k = 0; itNodes->more(); k++)
2655 const SMDS_MeshNode* node = itNodes->next();
2656 elemType.myNodes[ k ] = static_cast< const SMDS_MeshNode*> ( newNodes[ node->GetID() ]);
2659 // creates a corresponding element on existent nodes in new mesh
2660 newElems[ elem->GetID() ] =
2661 newEditor.AddElement( elemType.myNodes, elemType.Init( elem, /*basicOnly=*/false ));
2663 newEditor.ClearLastCreated(); // forget the history
2666 // create groups of just added elements
2667 SMESH::SMESH_Group_var newGroup;
2668 SMESH::ElementType groupType;
2669 if ( theCommonGroups )
2672 const char* typeNames[] = { "All","Nodes","Edges","Faces","Volumes","0DElems","Balls" };
2673 { // check of typeNames: compilation failure mains that NB_ELEMENT_TYPES changed:
2674 const int nbNames = sizeof(typeNames) / sizeof(const char*);
2675 int _assert[( nbNames == SMESH::NB_ELEMENT_TYPES ) ? 2 : -1 ]; _assert[0]=_assert[1]=0;
2678 SMESH::long_array_var curState = newMesh->GetNbElementsByType();
2680 for( groupType = SMESH::NODE;
2681 groupType < SMESH::NB_ELEMENT_TYPES;
2682 groupType = (SMESH::ElementType)( groupType + 1 ))
2684 if ( curState[ groupType ] <= prevState[ groupType ])
2685 continue; // no elements of groupType added from the i-th mesh
2687 // make a group name
2688 std::string groupName = "Gr";
2689 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( theMeshesArray[i] );
2691 CORBA::String_var name = meshSO->GetName();
2695 groupName += typeNames[ groupType ];
2697 // make and fill a group
2698 newGroup = newImpl->CreateGroup( groupType, groupName.c_str() );
2699 std::vector< const SMDS_MeshElement* > & elemVec =
2700 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2701 if ( SMESH_Group_i* grp_i = SMESH::DownCast<SMESH_Group_i*>( newGroup ))
2703 if ( SMESHDS_Group* grpDS = dynamic_cast<SMESHDS_Group*>( grp_i->GetGroupDS() ))
2705 for ( size_t j = 0; j < elemVec.size(); ++j )
2707 if ( elemVec[j] && elemVec[j]->GetType() == grpDS->GetType() )
2708 grpDS->Add( elemVec[j] );
2712 listOfNewGroups.clear();
2713 listOfNewGroups.push_back( newGroup );
2714 groupsMap.insert( std::make_pair( TNameAndType( groupName, groupType ),
2719 if ( SMESH_Mesh_i* initImpl = SMESH::DownCast<SMESH_Mesh_i*>( theMeshesArray[i] ))
2723 SMESH::SMESH_GroupBase_ptr group;
2724 CORBA::String_var groupName;
2725 SMESH::long_array_var newIDs = new SMESH::long_array();
2727 // loop on groups of a source mesh
2728 SMESH::ListOfGroups_var listOfGroups = initImpl->GetGroups();
2729 for ( CORBA::ULong iG = 0; iG < listOfGroups->length(); iG++ )
2731 group = listOfGroups[iG];
2732 groupType = group->GetType();
2733 groupName = group->GetName();
2734 std::string name = groupName.in();
2736 // convert a list of IDs
2737 newIDs->length( group->Size() );
2738 std::vector< const SMDS_MeshElement* > & elemVec =
2739 ( groupType == SMESH::NODE ) ? newNodes : newElems;
2740 SMDS_ElemIteratorPtr itGrElems = initImpl->GetElements( group, SMESH::ALL );
2742 while ( itGrElems->more() )
2744 const SMDS_MeshElement* elem = itGrElems->next();
2745 const SMDS_MeshElement* newElem = elemVec[ elem->GetID() ];
2747 newIDs[ nbElems++ ] = newElem->GetID();
2749 newIDs->length( nbElems );
2751 // check that a current group name and type don't have identical ones in final mesh
2752 listOfNewGroups.clear();
2753 TNameAndType nameAndType( name, groupType );
2754 TGroupsMap::iterator anIter = groupsMap.find( nameAndType );
2755 if ( anIter == groupsMap.end() )
2757 // add a new group in the mesh
2758 newGroup = newImpl->CreateGroup( groupType, groupName.in() );
2759 newGroup->Add( newIDs );
2761 listOfNewGroups.push_back( newGroup );
2762 groupsMap.insert( std::make_pair( nameAndType, listOfNewGroups ));
2764 else if ( theUniteIdenticalGroups )
2766 // unite identical groups
2767 TListOfNewGroups& aNewGroups = anIter->second;
2768 aNewGroups.front()->Add( newIDs );
2772 // rename identical groups
2773 newGroup = newImpl->CreateGroup( groupType, groupName );
2774 newGroup->Add( newIDs );
2776 TListOfNewGroups& newGroups = anIter->second;
2777 std::string newGroupName;
2778 if ( newGroups.size() == 1 )
2780 newGroupName = name + "_1";
2781 newGroups.front()->SetName( newGroupName.c_str() );
2783 newGroupName = name + "_" + SMESH_Comment( newGroups.size() + 1 );
2784 newGroup->SetName( newGroupName.c_str() );
2785 newGroups.push_back( newGroup );
2788 } // if an IDSource is a mesh
2791 if ( theMergeNodesAndElements ) // merge nodes
2793 TIDSortedNodeSet meshNodes; // no input nodes == treat all
2794 SMESH_MeshEditor::TListOfListOfNodes groupsOfNodes;
2795 newEditor.FindCoincidentNodes( meshNodes, theMergeTolerance, groupsOfNodes,
2796 /*SeparateCornersAndMedium=*/ false );
2797 newEditor.MergeNodes( groupsOfNodes );
2799 newEditor.MergeEqualElements();
2802 // Update Python script
2803 pythonDump << newMesh << " = " << this
2804 << "." << ( theCommonGroups ? "ConcatenateWithGroups" : "Concatenate" ) << "( "
2805 << theMeshesArray << ", "
2806 << theUniteIdenticalGroups << ", "
2807 << theMergeNodesAndElements << ", "
2808 << TVar( theMergeTolerance ) << ", "
2809 << theMeshToAppendTo << " )";
2811 pPythonDump.reset(); // enable python dump from GetGroups()
2813 // 0020577: EDF 1164 SMESH: Bad dump of concatenate with create common groups
2814 if ( !newMesh->_is_nil() )
2816 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
2819 // IPAL21468 Change icon of compound because it need not be computed.
2820 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2821 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH" );
2823 newMeshDS->Modified();
2825 return newMesh._retn();
2828 //================================================================================
2830 * \brief Create a mesh by copying a part of another mesh
2831 * \param meshPart - a part of mesh to copy
2832 * \param toCopyGroups - to create in the new mesh groups
2833 * the copied elements belongs to
2834 * \param toKeepIDs - to preserve IDs of the copied elements or not
2835 * \retval SMESH::SMESH_Mesh_ptr - the new mesh
2837 //================================================================================
2839 SMESH::SMESH_Mesh_ptr SMESH_Gen_i::CopyMesh(SMESH::SMESH_IDSource_ptr meshPart,
2840 const char* meshName,
2841 CORBA::Boolean toCopyGroups,
2842 CORBA::Boolean toKeepIDs)
2843 throw ( SALOME::SALOME_Exception )
2845 Unexpect aCatch(SALOME_SalomeException);
2847 TPythonDump* pyDump = new TPythonDump; // prevent dump from CreateMesh()
2848 std::unique_ptr<TPythonDump> pyDumpDeleter( pyDump );
2850 // 1. Get source mesh
2852 if ( CORBA::is_nil( meshPart ))
2853 THROW_SALOME_CORBA_EXCEPTION( "bad IDSource", SALOME::BAD_PARAM );
2855 SMESH::SMESH_Mesh_var srcMesh = meshPart->GetMesh();
2856 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( srcMesh );
2858 THROW_SALOME_CORBA_EXCEPTION( "bad mesh of IDSource", SALOME::BAD_PARAM );
2860 SMESHDS_Mesh* srcMeshDS = srcMesh_i->GetImpl().GetMeshDS();
2862 // 2. Make a new mesh
2864 SMESH::SMESH_Mesh_var newMesh = CreateMesh(GEOM::GEOM_Object::_nil());
2865 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( newMesh );
2867 THROW_SALOME_CORBA_EXCEPTION( "can't create a mesh", SALOME::INTERNAL_ERROR );
2868 SALOMEDS::SObject_wrap meshSO = ObjectToSObject( newMesh );
2869 if ( !meshSO->_is_nil() )
2871 SetName( meshSO, meshName, "Mesh" );
2872 SetPixMap( meshSO, "ICON_SMESH_TREE_MESH_IMPORTED");
2874 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
2875 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
2876 ::SMESH_MeshEditor::ElemFeatures elemType;
2878 // 3. Get elements to copy
2880 SMDS_ElemIteratorPtr srcElemIt; SMDS_NodeIteratorPtr srcNodeIt;
2881 TIDSortedElemSet srcElems;
2882 SMESH::array_of_ElementType_var srcElemTypes = meshPart->GetTypes();
2883 if ( SMESH::DownCast<SMESH_Mesh_i*>( meshPart ))
2886 srcElemIt = srcMeshDS->elementsIterator();
2887 srcNodeIt = srcMeshDS->nodesIterator();
2891 SMESH::long_array_var ids = meshPart->GetIDs();
2892 if ( srcElemTypes->length() == 1 && srcElemTypes[0] == SMESH::NODE ) // group of nodes
2894 for ( CORBA::ULong i=0; i < ids->length(); i++ )
2895 if ( const SMDS_MeshElement * elem = srcMeshDS->FindNode( ids[i] ))
2896 srcElems.insert( elem );
2900 for ( CORBA::ULong i = 0; i < ids->length(); i++ )
2901 if ( const SMDS_MeshElement * elem = srcMeshDS->FindElement( ids[i] ))
2902 srcElems.insert( elem );
2904 if ( srcElems.empty() )
2905 return newMesh._retn();
2907 typedef SMDS_SetIterator< SMDS_pElement, TIDSortedElemSet::const_iterator > ElIter;
2908 srcElemIt = SMDS_ElemIteratorPtr( new ElIter( srcElems.begin(), srcElems.end() ));
2913 typedef map<SMDS_pElement, SMDS_pElement, TIDCompare> TE2EMap;
2914 TE2EMap e2eMapByType[ SMDSAbs_NbElementTypes ];
2915 TE2EMap& n2nMap = e2eMapByType[ SMDSAbs_Node ];
2917 const SMDS_MeshNode *nSrc, *nTgt;
2918 vector< const SMDS_MeshNode* > nodes;
2919 while ( srcElemIt->more() )
2921 const SMDS_MeshElement * elem = srcElemIt->next();
2923 nodes.resize( elem->NbNodes());
2924 SMDS_ElemIteratorPtr nIt = elem->nodesIterator();
2926 for ( iN = 0; nIt->more(); ++iN )
2928 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2929 nTgt = newMeshDS->FindNode( nSrc->GetID());
2931 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2936 for ( iN = 0; nIt->more(); ++iN )
2938 nSrc = static_cast<const SMDS_MeshNode*>( nIt->next() );
2939 TE2EMap::iterator n2n = n2nMap.insert( make_pair( nSrc, SMDS_pNode(0) )).first;
2941 n2n->second = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2942 nodes[ iN ] = (const SMDS_MeshNode*) n2n->second;
2946 if ( elem->GetType() != SMDSAbs_Node )
2948 elemType.Init( elem, /*basicOnly=*/false );
2949 if ( toKeepIDs ) elemType.SetID( elem->GetID() );
2951 const SMDS_MeshElement * newElem = editor.AddElement( nodes, elemType );
2952 if ( toCopyGroups && !toKeepIDs )
2953 e2eMapByType[ elem->GetType() ].insert( make_pair( elem, newElem ));
2955 } // while ( srcElemIt->more() )
2957 // 4(b). Copy free nodes
2959 if ( srcNodeIt && srcMeshDS->NbNodes() != newMeshDS->NbNodes() )
2961 while ( srcNodeIt->more() )
2963 nSrc = srcNodeIt->next();
2964 if ( nSrc->NbInverseElements() == 0 )
2967 nTgt = newMeshDS->AddNodeWithID( nSrc->X(), nSrc->Y(), nSrc->Z(), nSrc->GetID());
2969 n2nMap[ nSrc ] = newMeshDS->AddNode( nSrc->X(), nSrc->Y(), nSrc->Z() );
2976 int nbNewGroups = 0;
2979 SMESH_Mesh::GroupIteratorPtr gIt = srcMesh_i->GetImpl().GetGroups();
2980 while ( gIt->more() )
2982 SMESH_Group* group = gIt->next();
2983 const SMESHDS_GroupBase* groupDS = group->GetGroupDS();
2985 // Check group type. We copy nodal groups containing nodes of copied element
2986 SMDSAbs_ElementType groupType = groupDS->GetType();
2987 if ( groupType != SMDSAbs_Node &&
2988 newMeshDS->GetMeshInfo().NbElements( groupType ) == 0 )
2989 continue; // group type differs from types of meshPart
2991 // Find copied elements in the group
2992 vector< const SMDS_MeshElement* > groupElems;
2993 SMDS_ElemIteratorPtr eIt = groupDS->GetElements();
2996 const SMDS_MeshElement* foundElem;
2997 if ( groupType == SMDSAbs_Node )
2999 while ( eIt->more() )
3000 if (( foundElem = newMeshDS->FindNode( eIt->next()->GetID() )))
3001 groupElems.push_back( foundElem );
3005 while ( eIt->more() )
3006 if (( foundElem = newMeshDS->FindElement( eIt->next()->GetID() )))
3007 groupElems.push_back( foundElem );
3012 TE2EMap & e2eMap = e2eMapByType[ groupDS->GetType() ];
3013 if ( e2eMap.empty() ) continue;
3014 int minID = e2eMap.begin()->first->GetID();
3015 int maxID = e2eMap.rbegin()->first->GetID();
3016 TE2EMap::iterator e2e;
3017 while ( eIt->more() && groupElems.size() < e2eMap.size())
3019 const SMDS_MeshElement* e = eIt->next();
3020 if ( e->GetID() < minID || e->GetID() > maxID ) continue;
3021 if ((e2e = e2eMap.find( e )) != e2eMap.end())
3022 groupElems.push_back( e2e->second );
3026 if ( !groupElems.empty() )
3028 SMESH::SMESH_Group_var newGroupObj =
3029 newMesh->CreateGroup( SMESH::ElementType(groupType), group->GetName() );
3030 if ( SMESH_GroupBase_i* newGroup_i = SMESH::DownCast<SMESH_GroupBase_i*>( newGroupObj))
3032 SMESHDS_GroupBase * newGroupDS = newGroup_i->GetGroupDS();
3033 SMDS_MeshGroup& smdsGroup = ((SMESHDS_Group*)newGroupDS)->SMDSGroup();
3034 for ( unsigned i = 0; i < groupElems.size(); ++i )
3035 smdsGroup.Add( groupElems[i] );
3043 newMeshDS->Modified();
3045 *pyDump << newMesh << " = " << this
3046 << ".CopyMesh( " << meshPart << ", "
3047 << "'" << meshName << "', "
3048 << toCopyGroups << ", "
3049 << toKeepIDs << ")";
3051 pyDumpDeleter.reset(); // allow dump in GetGroups()
3053 if ( nbNewGroups > 0 ) // dump created groups
3054 SMESH::ListOfGroups_var groups = newMesh->GetGroups();
3056 return newMesh._retn();
3060 namespace // utils for CopyMeshWithGeom()
3062 typedef std::map< std::string, std::string > TStr2StrMap;
3063 typedef std::map< std::string, std::set< std::string > > TStr2StrSetMap;
3064 typedef std::map< std::set<int>, int > TIdSet2IndexMap;
3065 typedef std::map< std::string, int > TName2IndexMap;
3067 //================================================================================
3069 * \brief Return a new sub-shape corresponding to an old one
3071 //================================================================================
3075 SMESH_Mesh_i* mySrcMesh_i;
3076 SMESH_Mesh_i* myNewMesh_i;
3077 SMESH_Gen_i* myGen_i;
3081 TStr2StrMap myOld2NewEntryMap; // map of study entries
3083 GEOM::ListOfGO_var mySubshapes; // sub-shapes existing in the new geometry
3084 TIdSet2IndexMap myIds2SubshapeIndex; // to find an existing sub-shape
3085 TName2IndexMap myName2SubshapeIndex; // to find an existing sub-shape by name
3088 GEOM::ListOfListOfLong_var myGIPMap; // filled by GetInPlaceMap()
3090 // not directly relating to shape search
3091 TStr2StrSetMap myInvalidMap; // blame shape -> invalid objects
3093 //================================================================================
3095 * \brief Constructor
3097 ShapeMapper( SMESH_Mesh_i* srcMesh_i,
3098 SMESH_Mesh_i* newMesh_i,
3099 SMESH_Gen_i* smeshGen_i )
3100 : mySrcMesh_i( srcMesh_i ),
3101 myNewMesh_i( newMesh_i ),
3102 myGen_i ( smeshGen_i ),
3103 myToPublish( smeshGen_i->IsEnablePublish() ),
3104 myGIPMapDone( false )
3106 // retrieve from the study shape mapping made thanks to
3107 // "Set presentation parameters and sub-shapes from arguments" option
3109 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3110 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3111 SALOMEDS::SObject_wrap oldSO = myGen_i->ObjectToSObject( mainShapeOld );
3112 SALOMEDS::SObject_wrap newSO = myGen_i->ObjectToSObject( mainShapeNew );
3113 if ( newSO->_is_nil() )
3115 myToPublish = false;
3118 if (( myIsSameGeom = mainShapeNew->_is_equivalent( mainShapeOld )))
3120 CORBA::String_var oldEntry = oldSO->GetID();
3121 CORBA::String_var newEntry = newSO->GetID();
3122 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3123 std::string( newEntry.in() )));
3124 std::string newMainEntry = newEntry.in();
3126 SALOMEDS::Study_var study = myGen_i->getStudyServant();
3127 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3128 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3129 mySubshapes = op->GetExistingSubObjects( mainShapeNew,
3130 /*groupsOnly=*/false );
3131 for ( CORBA::ULong i = 0; i < mySubshapes->length(); ++i )
3133 newSO = myGen_i->ObjectToSObject( mySubshapes[ i ]);
3134 SALOMEDS::ChildIterator_wrap anIter = study->NewChildIterator( newSO );
3135 bool refFound = false;
3136 for ( ; anIter->More(); anIter->Next() )
3138 SALOMEDS::SObject_wrap so = anIter->Value();
3139 if ( so->ReferencedObject( oldSO.inout() ))
3141 oldEntry = oldSO->GetID();
3142 newEntry = newSO->GetID();
3143 if (( refFound = ( newMainEntry != oldEntry.in() )))
3144 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3145 std::string( newEntry.in() )));
3150 GEOM::GEOM_Object_var father = mySubshapes[ i ]->GetMainShape();
3151 if ( father->_is_equivalent( mainShapeNew ))
3153 GEOM::ListOfLong_var ids = mySubshapes[ i ]->GetSubShapeIndices();
3154 std::set< int > idSet( &ids[0] , &ids[0] + ids->length() );
3155 myIds2SubshapeIndex.insert( std::make_pair( idSet, i ));
3156 CORBA::String_var name = newSO->GetName();
3158 myName2SubshapeIndex.insert( std::make_pair( name.in(), i ));
3164 //================================================================================
3166 * \brief Find a new sub-shape corresponding to an old one
3168 GEOM::GEOM_Object_ptr FindNew( GEOM::GEOM_Object_ptr oldShape )
3171 return GEOM::GEOM_Object::_duplicate( oldShape );
3173 GEOM::GEOM_Object_var newShape;
3175 if ( CORBA::is_nil( oldShape ))
3176 return newShape._retn();
3178 if ( !isChildOfOld( oldShape ))
3179 return GEOM::GEOM_Object::_duplicate( oldShape ); // shape independent of the old shape
3181 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3182 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3184 // try to find by entry or name
3187 CORBA::String_var oldEntry = oldShape->GetStudyEntry();
3188 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry.in() );
3189 if ( o2nID != myOld2NewEntryMap.end() )
3191 newShape = getShapeByEntry( o2nID->second );
3193 if ( newShape->_is_nil() )
3195 CORBA::String_var name = oldShape->GetName();
3196 TName2IndexMap::iterator n2ind = myName2SubshapeIndex.find( name.in() );
3197 if ( n2ind != myName2SubshapeIndex.end() )
3199 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ n2ind->second ]);
3200 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3201 GEOM::ListOfLong_var newIndices = newShape->GetSubShapeIndices();
3202 if ( oldIndices->length() == 0 ||
3203 newIndices->length() == 0 ||
3204 getShapeType( myNewMesh_i, newIndices[0] ) !=
3205 getShapeType( mySrcMesh_i, oldIndices[0] ))
3206 newShape = GEOM::GEOM_Object::_nil();
3211 if ( newShape->_is_nil() )
3213 // try to construct a new sub-shape using myGIPMap
3215 std::vector< int > newIndices;
3216 GEOM::ListOfLong_var oldIndices = oldShape->GetSubShapeIndices();
3217 for ( CORBA::ULong i = 0; i < oldIndices->length(); ++i )
3219 findNewIDs( oldIndices[i], newIndices );
3221 if ( newIndices.size() < oldIndices->length() ) // issue #17096
3224 newShape = getInPlace( oldShape );
3226 if ( !newIndices.empty() && newShape->_is_nil() )
3228 // search for a sub-shape with same ids
3229 std::set< int > idSet( newIndices.begin(), newIndices.end() );
3230 TIdSet2IndexMap::iterator ids2ind = myIds2SubshapeIndex.find( idSet );
3231 if ( ids2ind != myIds2SubshapeIndex.end() ) {
3232 newShape = GEOM::GEOM_Object::_duplicate( mySubshapes[ ids2ind->second ]);
3234 if ( newShape->_is_nil() )
3237 // create a new shape
3238 if ( newIndices.size() > 1 || oldShape->GetType() == GEOM_GROUP )
3240 int groupType = getShapeType( myNewMesh_i, newIndices[0] );
3242 GEOM::GEOM_IGroupOperations_ptr grOp = geomGen->GetIGroupOperations();
3243 newShape = grOp->CreateGroup( mainShapeNew, groupType );
3245 GEOM::ListOfLong_var newIndicesList = new GEOM::ListOfLong();
3246 newIndicesList->length( newIndices.size() );
3247 for ( size_t i = 0; i < newIndices.size(); ++i )
3248 newIndicesList[ i ] = newIndices[ i ];
3249 grOp->UnionIDs( newShape, newIndicesList );
3253 GEOM::GEOM_IShapesOperations_wrap shOp = geomGen->GetIShapesOperations();
3254 newShape = shOp->GetSubShape( mainShapeNew, newIndices[0] );
3263 if ( !newShape->_is_nil() && myToPublish )
3265 CORBA::String_var oldEntry, newEntry = newShape->GetStudyEntry();
3266 if ( !newEntry.in() || !newEntry.in()[0] )
3268 CORBA::String_var name = oldShape->GetName();
3269 SALOMEDS::SObject_wrap so = geomGen->AddInStudy( newShape, name, mainShapeNew );
3270 newEntry = newShape->GetStudyEntry();
3271 oldEntry = oldShape->GetStudyEntry();
3272 myOld2NewEntryMap.insert( std::make_pair( std::string( oldEntry.in() ),
3273 std::string( newEntry.in() )));
3277 return newShape._retn();
3280 //================================================================================
3282 * \brief Return a study entry of a new shape by study entry of the old one
3284 std::string FindNew( const std::string & oldEntry )
3289 TStr2StrMap::iterator o2nID = myOld2NewEntryMap.find( oldEntry );
3290 if ( o2nID != myOld2NewEntryMap.end() )
3291 return o2nID->second;
3293 GEOM::GEOM_Object_var oldShape = getShapeByEntry( oldEntry );
3294 if ( oldShape->_is_nil() || !isChildOfOld( oldShape ))
3297 GEOM::GEOM_Object_ptr newShape = FindNew( oldShape );
3298 if ( newShape->_is_nil() )
3299 return std::string();
3301 CORBA::String_var newEntry = newShape->GetStudyEntry();
3302 return newEntry.in();
3305 //================================================================================
3307 * \brief Return a sub-shape ID of a new shape by a sub-shape ID of the old one.
3308 * Return zero if not found or there are more than one new ID
3310 int FindNew( int oldID )
3319 if ( 0 < oldID && oldID < (int)myGIPMap->length() )
3321 if ( myGIPMap[ oldID ].length() == 1 )
3323 newID = myGIPMap[ oldID ][ 0 ];
3325 else if ( myGIPMap[ oldID ].length() > 1 &&
3326 getShapeType( mySrcMesh_i, oldID ) == TopAbs_VERTEX )
3328 // select a meshed VERTEX
3329 SMESH_subMesh* newSM;
3330 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length() && !newID; ++i )
3331 if (( newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( myGIPMap[ oldID ][ i ] )) &&
3332 ( !newSM->IsEmpty() ))
3333 newID = myGIPMap[ oldID ][ i ];
3339 //================================================================================
3341 * \brief Return a sub-shape ID of a new shape by an old sub-mesh.
3342 * Return zero if the old shape is not kept as is in the new shape.
3344 int FindNewNotChanged( SMESH_subMesh* oldSM )
3347 return oldSM->GetId();
3349 int newID = FindNew( oldSM->GetId() );
3353 SMESH_subMesh* newSM = myNewMesh_i->GetImpl().GetSubMeshContaining( newID );
3357 // consider a sub-shape as not changed if all its sub-shapes are mapped into
3358 // one new sub-shape of the same type.
3360 if ( oldSM->DependsOn().size() !=
3361 newSM->DependsOn().size() )
3364 SMESH_subMeshIteratorPtr srcSMIt = oldSM->getDependsOnIterator( /*includeSelf=*/true );
3365 while ( srcSMIt->more() )
3367 oldSM = srcSMIt->next();
3368 int newSubID = FindNew( oldSM->GetId() );
3369 if ( getShapeType( myNewMesh_i, newSubID ) !=
3370 getShapeType( mySrcMesh_i, oldSM->GetId() ))
3376 //================================================================================
3378 * \brief Return shape by study entry
3380 GEOM::GEOM_Object_ptr getShapeByEntry( const std::string & entry )
3382 GEOM::GEOM_Object_var shape;
3383 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry.c_str() );
3384 if ( !so->_is_nil() )
3386 CORBA::Object_var obj = so->GetObject();
3387 shape = GEOM::GEOM_Object::_narrow( obj );
3389 return shape._retn();
3392 //================================================================================
3394 * \brief Fill myGIPMap by calling GetInPlaceMap()
3398 if ( !myGIPMapDone )
3400 myGIPMapDone = true;
3402 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3403 GEOM::GEOM_Object_var mainShapeOld = mySrcMesh_i->GetShapeToMesh();
3404 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3405 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3408 myGIPMap = op->GetInPlaceMap( mainShapeNew, mainShapeOld );
3412 myGIPMap = new GEOM::ListOfListOfLong();
3417 //================================================================================
3419 * \brief Get new sub-shape by calling GetInPlace()
3421 GEOM::GEOM_Object_ptr getInPlace( GEOM::GEOM_Object_ptr oldShape )
3423 GEOM::GEOM_Object_var newShape;
3425 GEOM::GEOM_Object_var mainShapeNew = myNewMesh_i->GetShapeToMesh();
3426 GEOM::GEOM_Gen_var geomGen = myGen_i->GetGeomEngine( mainShapeNew );
3427 GEOM::GEOM_IShapesOperations_wrap op = geomGen->GetIShapesOperations();
3430 newShape = op->GetInPlace( mainShapeNew, oldShape );
3435 return newShape._retn();
3438 //================================================================================
3440 * \brief Find a new sub-shape indices by an old one in myGIPMap. Return
3441 * number of found IDs
3443 int findNewIDs( int oldID, std::vector< int >& newIDs )
3445 size_t prevNbIDs = newIDs.size();
3447 if ( 0 < oldID && oldID < (int) myGIPMap->length() )
3449 for ( CORBA::ULong i = 0; i < myGIPMap[ oldID ].length(); ++i )
3450 newIDs.push_back( myGIPMap[ oldID ][ i ]);
3452 return newIDs.size() - prevNbIDs;
3455 //================================================================================
3457 * \brief Check if an object relates to the old shape
3459 bool isChildOfOld( GEOM::GEOM_Object_ptr oldShape )
3461 if ( CORBA::is_nil( oldShape ))
3463 GEOM::GEOM_Object_var mainShapeOld1 = mySrcMesh_i->GetShapeToMesh();
3464 GEOM::GEOM_Object_var mainShapeOld2 = oldShape->GetMainShape();
3465 return ( mainShapeOld1->_is_equivalent( mainShapeOld2 ) ||
3466 mainShapeOld1->_is_equivalent( oldShape ));
3469 //================================================================================
3471 * \brief Return shape type by shape ID
3473 TopAbs_ShapeEnum getShapeType( SMESH_Mesh_i* mesh_i, int shapeID )
3475 SMESHDS_Mesh* meshDS = mesh_i->GetImpl().GetMeshDS();
3476 const TopoDS_Shape& shape = meshDS->IndexToShape( shapeID );
3477 return shape.IsNull() ? TopAbs_SHAPE : shape.ShapeType();
3480 //================================================================================
3482 * \brief Store a source sub-shape for which a counterpart not found and
3483 * a smesh object invalid due to that
3485 void AddInvalid( GEOM::GEOM_Object_var srcShape,
3486 SALOMEDS::SObject_wrap smeshSO )
3488 CORBA::String_var geomEntry = srcShape->GetStudyEntry();
3489 if ( geomEntry.in()[0] && !smeshSO->_is_nil() )
3491 CORBA::String_var smeshEntry = smeshSO->GetID();
3492 myInvalidMap[ geomEntry.in() ].insert( smeshEntry.in() );
3496 //================================================================================
3498 * \brief Store a source sub-shape for which a counterpart not found and
3499 * a smesh object invalid due to that
3501 void AddInvalid( std::string geomEntry,
3502 SALOMEDS::SObject_wrap smeshSO )
3504 if ( !geomEntry.empty() )
3506 CORBA::String_var smeshEntry = smeshSO->GetID();
3507 myInvalidMap[ geomEntry ].insert( smeshEntry.in() );
3511 //================================================================================
3513 * \brief Store a source sub-shape for which a counterpart not found and
3514 * a smesh object invalid due to that
3516 void AddInvalid( int oldGeomID,
3517 SALOMEDS::SObject_wrap smeshSO )
3519 int shapeType = getShapeType( mySrcMesh_i, oldGeomID );
3520 if ( shapeType < 0 || shapeType > TopAbs_SHAPE )
3523 const char* typeName[] = { "COMPOUND","COMPSOLID","SOLID","SHELL",
3524 "FACE","WIRE","EDGE","VERTEX","SHAPE" };
3526 SMESH_Comment geomName( typeName[ shapeType ]);
3527 geomName << " #" << oldGeomID;
3529 CORBA::String_var smeshEntry = smeshSO->GetID();
3530 myInvalidMap[ geomName ].insert( smeshEntry.in() );
3533 //================================================================================
3535 * \brief Return entries of a source sub-shape for which a counterpart not found and
3536 * of smesh objects invalid due to that
3538 void GetInvalid( SMESH::string_array_out & theInvalidEntries,
3539 std::vector< SALOMEDS::SObject_wrap > & theInvalidMeshSObjects)
3542 TStr2StrSetMap::iterator entry2entrySet = myInvalidMap.begin();
3543 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3545 nbSO += 1 + entry2entrySet->second.size();
3547 int iSO = theInvalidMeshSObjects.size(), iEntry = 0;
3548 theInvalidEntries->length ( nbSO );
3549 theInvalidMeshSObjects.resize( theInvalidMeshSObjects.size() + nbSO - myInvalidMap.size() );
3551 entry2entrySet = myInvalidMap.begin();
3552 for ( ; entry2entrySet != myInvalidMap.end(); ++entry2entrySet )
3554 theInvalidEntries[ iEntry++ ] = entry2entrySet->first.c_str();
3556 std::set< std::string > & entrySet = entry2entrySet->second;
3557 std::set< std::string >::iterator entry = entrySet.begin();
3558 for ( ; entry != entrySet.end(); ++entry )
3560 theInvalidEntries[ iEntry++ ] = entry->c_str();
3562 SALOMEDS::SObject_wrap so = myGen_i->getStudyServant()->FindObjectID( entry->c_str() );
3563 if ( !so->_is_nil() )
3564 theInvalidMeshSObjects[ iSO++ ] = so;
3569 }; // struct ShapeMapper
3571 //================================================================================
3573 * \brief Append an item to a CORBA sequence
3575 template < class CORBA_seq, class ITEM >
3576 void append( CORBA_seq& seq, ITEM item )
3578 if ( !CORBA::is_nil( item ))
3580 seq->length( 1 + seq->length() );
3581 seq[ seq->length() - 1 ] = item;
3584 } // namespace // utils for CopyMeshWithGeom()
3586 //================================================================================
3588 * \brief Create a mesh by copying definitions of another mesh to a given geometry
3589 * \param [in] sourceMesh - a mesh to copy
3590 * \param [in] newGeometry - a new geometry
3591 * \param [in] toCopyGroups - to create groups in the new mesh
3592 * \param [in] toReuseHypotheses - if True, existing hypothesis will be used by the new mesh,
3593 * otherwise new hypotheses with the same parameters will be created for the new mesh.
3594 * \param [in] toCopyElements - to copy mesh elements of same sub-shapes of the two geometries
3595 * \param [out] newMesh - return a new mesh
3596 * \param [out] newGroups - return new groups
3597 * \param [out] newSubmeshes - return new sub-meshes
3598 * \param [out] newHypotheses - return new algorithms and hypotheses
3599 * \param [out] invalidEntries - return study entries of objects whose
3600 * counterparts are not found in the newGeometry, followed by entries
3601 * of mesh sub-objects that are invalid because they depend on a not found
3602 * preceding sub-shape
3603 * \return CORBA::Boolean - is a success
3605 //================================================================================
3607 CORBA::Boolean SMESH_Gen_i::CopyMeshWithGeom( SMESH::SMESH_Mesh_ptr theSourceMesh,
3608 GEOM::GEOM_Object_ptr theNewGeometry,
3609 const char* theMeshName,
3610 CORBA::Boolean theToCopyGroups,
3611 CORBA::Boolean theToReuseHypotheses,
3612 CORBA::Boolean theToCopyElements,
3613 SMESH::SMESH_Mesh_out theNewMesh,
3614 SMESH::ListOfGroups_out theNewGroups,
3615 SMESH::submesh_array_out theNewSubmeshes,
3616 SMESH::ListOfHypothesis_out theNewHypotheses,
3617 SMESH::string_array_out theInvalidEntries)
3618 throw ( SALOME::SALOME_Exception )
3620 if ( CORBA::is_nil( theSourceMesh ) ||
3621 CORBA::is_nil( theNewGeometry ))
3622 THROW_SALOME_CORBA_EXCEPTION( "NULL arguments", SALOME::BAD_PARAM );
3624 if ( !theSourceMesh->HasShapeToMesh() )
3625 THROW_SALOME_CORBA_EXCEPTION( "Source mesh not on geometry", SALOME::BAD_PARAM );
3630 TPythonDump pyDump; // prevent dump from CreateMesh()
3632 theNewMesh = CreateMesh( theNewGeometry );
3633 theNewGroups = new SMESH::ListOfGroups();
3634 theNewSubmeshes = new SMESH::submesh_array();
3635 theNewHypotheses = new SMESH::ListOfHypothesis();
3636 theInvalidEntries = new SMESH::string_array();
3638 std::vector< SALOMEDS::SObject_wrap > invalidSObjects;
3640 GEOM::GEOM_Object_var srcGeom = theSourceMesh->GetShapeToMesh();
3641 GEOM::GEOM_Object_var geom, newGeom;
3642 SALOMEDS::SObject_wrap so;
3644 SMESH_Mesh_i* srcMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theSourceMesh );
3645 SMESH_Mesh_i* newMesh_i = SMESH::DownCast<SMESH_Mesh_i*>( theNewMesh );
3648 ShapeMapper shapeMapper( srcMesh_i, newMesh_i, this );
3650 // treat hypotheses of mesh and sub-meshes
3651 SMESH::submesh_array_var smList = theSourceMesh->GetSubMeshes();
3652 for ( CORBA::ULong iSM = 0; iSM <= smList->length(); ++iSM )
3654 bool isSubMesh = ( iSM < smList->length() );
3657 // create a new sub-mesh
3658 SMESH::SMESH_subMesh_var newSM;
3659 geom = smList[iSM]->GetSubShape();
3660 so = ObjectToSObject( smList[iSM] );
3661 CORBA::String_var name;
3662 if ( !so->_is_nil() )
3663 name = so->GetName();
3664 newGeom = shapeMapper.FindNew( geom );
3665 if ( newGeom->_is_nil() )
3667 newSM = createInvalidSubMesh( theNewMesh, geom, name.in() );
3668 shapeMapper.AddInvalid( geom, ObjectToSObject( newSM ));
3673 newSM = theNewMesh->GetSubMesh( newGeom, name.in() );
3675 append( theNewSubmeshes, newSM );
3677 if ( newGeom->_is_nil() )
3678 continue; // don't assign hypotheses
3682 newGeom = GEOM::GEOM_Object::_duplicate( theNewGeometry );
3684 so = ObjectToSObject( theNewMesh );
3685 SetName( so, theMeshName, "Mesh" );
3688 // assign hypotheses
3689 SMESH::ListOfHypothesis_var hypList = theSourceMesh->GetHypothesisList( geom );
3690 for ( CORBA::ULong iHyp = 0; iHyp < hypList->length(); ++iHyp )
3692 SMESH::SMESH_Hypothesis_var hyp = hypList[ iHyp ];
3693 SMESH_Hypothesis_i* hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3695 // get geometry hyp depends on
3696 std::vector< std::string > entryArray;
3697 std::vector< int > subIDArray;
3698 bool dependsOnGeom = hyp_i->getObjectsDependOn( entryArray, subIDArray );
3700 if ( !theToReuseHypotheses || dependsOnGeom )
3702 // create a new hypothesis
3703 CORBA::String_var type = hyp->GetName();
3704 CORBA::String_var lib = hyp->GetLibName();
3705 CORBA::String_var data = hyp_i->SaveTo();
3708 hyp = CreateHypothesis( type, lib );
3709 hyp_i = SMESH::DownCast< SMESH_Hypothesis_i* >( hyp );
3710 hyp_i->LoadFrom( data.in() );
3711 append( theNewHypotheses, hyp );
3715 // update geometry hyp depends on
3716 if ( dependsOnGeom )
3718 for ( size_t iGeo = 0; iGeo < entryArray.size(); ++iGeo )
3720 if ( !entryArray[ iGeo ].empty() )
3722 std::string newEntry = shapeMapper.FindNew( entryArray[ iGeo ]);
3723 if ( newEntry.empty() )
3726 shapeMapper.AddInvalid( entryArray[ iGeo ], ObjectToSObject( hyp ));
3727 shapeMapper.AddInvalid( entryArray[ iGeo ], so ); // sub-mesh
3729 entryArray[ iGeo ] = newEntry;
3732 for ( size_t iGeo = 0; iGeo < subIDArray.size(); ++iGeo )
3734 if ( subIDArray[ iGeo ] > 0 )
3736 int newID = shapeMapper.FindNew( subIDArray[ iGeo ]);
3740 shapeMapper.AddInvalid( subIDArray[ iGeo ], ObjectToSObject( hyp ));
3741 shapeMapper.AddInvalid( subIDArray[ iGeo ], so ); // sub-mesh
3743 subIDArray[ iGeo ] = newID;
3746 if ( !hyp_i->setObjectsDependOn( entryArray, subIDArray ))
3750 CORBA::String_var errorText;
3751 theNewMesh->AddHypothesis( newGeom, hyp, errorText.out() );
3752 if ( errorText.in()[0] )
3755 } // loop on hypotheses
3756 } // loop on sub-meshes and mesh
3759 // copy mesh elements, keeping IDs
3760 SMESHDS_Mesh* newMeshDS = newMesh_i->GetImpl().GetMeshDS();
3761 if ( theToCopyElements && theSourceMesh->NbNodes() > 0 )
3763 ::SMESH_MeshEditor editor( &newMesh_i->GetImpl() );
3764 ::SMESH_MeshEditor::ElemFeatures elemData;
3766 SMESH_subMesh* srcMainSM = srcMesh_i->GetImpl().GetSubMeshContaining( 1 );
3767 SMESH_subMeshIteratorPtr srcSMIt = srcMainSM->getDependsOnIterator( /*includeSelf=*/true,
3768 /*vertexLast=*/false);
3769 while ( srcSMIt->more() )
3771 SMESH_subMesh* srcSM = srcSMIt->next();
3772 if ( srcSM->IsEmpty() )
3773 continue; // not yet computed
3774 int newID = shapeMapper.FindNewNotChanged( srcSM );
3778 SMESHDS_SubMesh* srcSMDS = srcSM->GetSubMeshDS();
3779 SMDS_NodeIteratorPtr nIt = srcSMDS->GetNodes();
3780 while ( nIt->more() )
3782 SMESH_NodeXYZ node( nIt->next() );
3783 const SMDS_MeshNode* newNode = newMeshDS->AddNodeWithID( node.X(), node.Y(), node.Z(),
3785 const SMDS_PositionPtr pos = node->GetPosition();
3786 const double* uv = pos->GetParameters();
3787 switch ( pos->GetTypeOfPosition() )
3789 case SMDS_TOP_3DSPACE: newMeshDS->SetNodeInVolume( newNode, newID ); break;
3790 case SMDS_TOP_FACE: newMeshDS->SetNodeOnFace ( newNode, newID, uv[0], uv[1] ); break;
3791 case SMDS_TOP_EDGE: newMeshDS->SetNodeOnEdge ( newNode, newID, uv[0] ); break;
3792 case SMDS_TOP_VERTEX: newMeshDS->SetNodeOnVertex( newNode, newID ); break;
3796 SMDS_ElemIteratorPtr eIt = srcSMDS->GetElements();
3797 while( eIt->more() )
3799 const SMDS_MeshElement* e = eIt->next();
3800 elemData.Init( e, /*basicOnly=*/false );
3801 elemData.SetID( e->GetID() );
3802 elemData.myNodes.resize( e->NbNodes() );
3803 SMDS_NodeIteratorPtr nnIt = e->nodeIterator();
3805 for ( iN = 0; nnIt->more(); ++iN )
3807 const SMDS_MeshNode* srcNode = nnIt->next();
3808 elemData.myNodes[ iN ] = newMeshDS->FindNode( srcNode->GetID() );
3809 if ( !elemData.myNodes[ iN ])
3812 if ( iN == elemData.myNodes.size() )
3813 if ( const SMDS_MeshElement * newElem = editor.AddElement( elemData.myNodes, elemData ))
3814 newMeshDS->SetMeshElementOnShape( newElem, newID );
3816 if ( SMESH_subMesh* newSM = newMesh_i->GetImpl().GetSubMeshContaining( newID ))
3817 newSM->ComputeStateEngine( SMESH_subMesh::CHECK_COMPUTE_STATE );
3820 newMeshDS->Modified();
3826 TStr2StrMap old2newGroupMap;
3828 SALOME::GenericObj_wrap< SMESH::FilterManager > filterMgr = CreateFilterManager();
3830 SMESH::ListOfGroups_var groups = theSourceMesh->GetGroups();
3831 CORBA::ULong nbGroups = theToCopyGroups ? groups->length() : 0, nbAddedGroups = 0;
3832 for ( CORBA::ULong i = 0; i < nbGroups + nbAddedGroups; ++i )
3834 SMESH::SMESH_Group_var stdlGroup = SMESH::SMESH_Group::_narrow ( groups[ i ]);
3835 SMESH::SMESH_GroupOnGeom_var geomGroup = SMESH::SMESH_GroupOnGeom::_narrow ( groups[ i ]);
3836 SMESH::SMESH_GroupOnFilter_var fltrGroup = SMESH::SMESH_GroupOnFilter::_narrow( groups[ i ]);
3838 CORBA::String_var name = groups[ i ]->GetName();
3839 SMESH::ElementType elemType = groups[ i ]->GetType();
3841 SMESH::SMESH_GroupBase_var newGroup;
3843 if ( !stdlGroup->_is_nil() )
3845 if ( newMeshDS->GetMeshInfo().NbElements( SMDSAbs_ElementType( elemType )) > 0 )
3847 SMESH::long_array_var elemIDs = stdlGroup->GetIDs();
3848 const bool isElem = ( elemType != SMESH::NODE );
3849 CORBA::ULong iE = 0;
3850 for ( ; iE < elemIDs->length(); ++iE ) // check if any element has been copied
3851 if ( newMeshDS->GetElementType( elemIDs[ iE ], isElem ) != SMDSAbs_All )
3853 if ( iE < elemIDs->length() )
3855 stdlGroup = theNewMesh->CreateGroup( elemType, name );
3856 stdlGroup->Add( elemIDs );
3857 newGroup = SMESH::SMESH_GroupBase::_narrow( stdlGroup );
3861 else if ( !geomGroup->_is_nil() )
3863 GEOM::GEOM_Object_var geom = geomGroup->GetShape();
3864 GEOM::GEOM_Object_var newGeom = shapeMapper.FindNew( geom );
3865 if ( newGeom->_is_nil() )
3867 newGroup = theNewMesh->CreateGroup( elemType, name ); // just to notify the user
3868 shapeMapper.AddInvalid( geom, ObjectToSObject( newGroup ));
3873 newGroup = theNewMesh->CreateGroupFromGEOM( elemType, name, newGeom );
3876 else if ( !fltrGroup->_is_nil() )
3878 // replace geometry in a filter
3879 SMESH::Filter_var filter = fltrGroup->GetFilter();
3880 SMESH::Filter::Criteria_var criteria;
3881 filter->GetCriteria( criteria.out() );
3883 bool isMissingGroup = false;
3884 std::vector< std::string > badEntries;
3886 for ( CORBA::ULong iCr = 0; iCr < criteria->length(); ++iCr )
3888 const char* thresholdID = criteria[ iCr ].ThresholdID.in();
3889 switch ( criteria[ iCr ].Type )
3891 case SMESH::FT_BelongToMeshGroup:
3893 SALOME::GenericObj_wrap< SMESH::BelongToMeshGroup > btgg = filterMgr->CreateBelongToMeshGroup();
3894 btgg->SetGroupID( thresholdID );
3895 SMESH::SMESH_GroupBase_ptr refGroup = btgg->GetGroup();
3896 SALOMEDS::SObject_wrap refGroupSO = ObjectToSObject( refGroup );
3897 if ( refGroupSO->_is_nil() )
3899 CORBA::String_var refID = refGroupSO->GetID();
3900 TStr2StrMap::iterator o2nID = old2newGroupMap.find( refID.in() );
3901 if ( o2nID == old2newGroupMap.end() )
3903 isMissingGroup = true; // corresponding new group not yet created
3906 criteria[ iCr ].ThresholdID = o2nID->second.c_str();
3908 if ( o2nID->second.empty() ) // new referred group is invalid
3909 badEntries.push_back( refID.in() );
3912 case SMESH::FT_BelongToGeom:
3913 case SMESH::FT_BelongToPlane:
3914 case SMESH::FT_BelongToCylinder:
3915 case SMESH::FT_BelongToGenSurface:
3916 case SMESH::FT_LyingOnGeom:
3918 std::string newID = shapeMapper.FindNew( thresholdID );
3919 criteria[ iCr ].ThresholdID = newID.c_str();
3920 if ( newID.empty() )
3921 badEntries.push_back( thresholdID );
3924 case SMESH::FT_ConnectedElements:
3926 if ( thresholdID && thresholdID[0] )
3928 std::string newID = shapeMapper.FindNew( thresholdID );
3929 criteria[ iCr ].ThresholdID = newID.c_str();
3930 if ( newID.empty() )
3931 badEntries.push_back( thresholdID );
3937 } // loop on criteria
3939 if ( isMissingGroup && i < nbGroups )
3941 // to treat the group again
3942 append( groups, SMESH::SMESH_GroupBase::_duplicate( groups[ i ]));
3946 SMESH::Filter_var newFilter = filterMgr->CreateFilter();
3947 newFilter->SetCriteria( criteria );
3949 newGroup = theNewMesh->CreateGroupFromFilter( elemType, name, newFilter );
3950 newFilter->UnRegister();
3952 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3953 for ( size_t iEnt = 0; iEnt < badEntries.size(); ++iEnt )
3954 shapeMapper.AddInvalid( badEntries[ iEnt ], newSO );
3956 if ( isMissingGroup ) // all groups treated but a referred groups still not found
3958 invalidSObjects.push_back( ObjectToSObject( newGroup ));
3961 if ( !badEntries.empty() )
3964 } // treat a group on filter
3966 append( theNewGroups, newGroup );
3968 // fill old2newGroupMap
3969 SALOMEDS::SObject_wrap srcSO = ObjectToSObject( groups[i] );
3970 SALOMEDS::SObject_wrap newSO = ObjectToSObject( newGroup );
3971 if ( !srcSO->_is_nil() )
3973 CORBA::String_var srcID, newID("");
3974 srcID = srcSO->GetID();
3975 if ( !newSO->_is_nil() )
3976 newID = newSO->GetID();
3977 old2newGroupMap.insert( std::make_pair( std::string( srcID.in() ),
3978 std::string( newID.in() )));
3981 if ( newGroup->_is_nil() )
3986 newMeshDS->CompactMesh();
3989 if ( !theMeshName || !theMeshName[0] )
3991 SALOMEDS::SObject_wrap soNew = ObjectToSObject( theNewMesh );
3992 SALOMEDS::SObject_wrap soOld = ObjectToSObject( theSourceMesh );
3993 CORBA::String_var oldName = soOld->GetName();
3994 SetName( soNew, oldName.in(), "Mesh" );
3996 // mark invalid objects
3997 shapeMapper.GetInvalid( theInvalidEntries, invalidSObjects );
3999 for ( size_t i = 0; i < invalidSObjects.size(); ++i )
4000 highLightInvalid( invalidSObjects[i].in(), true );
4003 << theNewMesh << ", "
4004 << theNewGroups << ", "
4005 << *theNewSubmeshes.ptr() << ", "
4006 << *theNewHypotheses.ptr() << ", "
4007 << "invalidEntries = " << this << ".CopyMeshWithGeom( "
4008 << theSourceMesh << ", "
4009 << theNewGeometry << ", "
4010 << "'" << theMeshName << "', "
4011 << theToCopyGroups << ", "
4012 << theToReuseHypotheses << ", "
4013 << theToCopyElements << " )";
4015 SMESH_CATCH( SMESH::throwCorbaException );
4020 //================================================================================
4022 * \brief Get version of MED format being used.
4024 //================================================================================
4026 char* SMESH_Gen_i::GetMEDFileVersion()
4028 MED::TInt majeur, mineur, release;
4029 majeur = mineur = release = 0;
4030 MED::GetVersionRelease(majeur, mineur, release);
4031 std::ostringstream version;
4032 version << majeur << "." << mineur << "." << release;
4033 return CORBA::string_dup( version.str().c_str() );
4036 //================================================================================
4038 * SMESH_Gen_i::GetMEDVersion
4040 * Get MED version of the file by its name
4042 //================================================================================
4043 char* SMESH_Gen_i::GetMEDVersion(const char* theFileName)
4045 std::string version = MED::GetMEDVersion( theFileName );
4046 return CORBA::string_dup( version.c_str() );
4049 //================================================================================
4051 * SMESH_Gen_i::CheckCompatibility
4053 * Check compatibility of file with MED format being used, read only.
4055 //================================================================================
4056 CORBA::Boolean SMESH_Gen_i::CheckCompatibility(const char* theFileName)
4058 return MED::CheckCompatibility( theFileName );
4061 //================================================================================
4063 * SMESH_Gen_i::CheckWriteCompatibility
4065 * Check compatibility of file with MED format being used, for append on write.
4067 //================================================================================
4068 CORBA::Boolean SMESH_Gen_i::CheckWriteCompatibility(const char* theFileName)
4070 return MED::CheckCompatibility( theFileName, true );
4073 //================================================================================
4075 * SMESH_Gen_i::GetMeshNames
4077 * Get names of meshes defined in file with the specified name
4079 //================================================================================
4080 SMESH::string_array* SMESH_Gen_i::GetMeshNames(const char* theFileName)
4082 //MESSAGE("GetMeshNames " << theFileName);
4083 SMESH::string_array_var aResult = new SMESH::string_array();
4084 MED::PWrapper aMed = MED::CrWrapperR( theFileName );
4086 MED::TInt aNbMeshes = aMed->GetNbMeshes( &anErr );
4087 //MESSAGE("---" << aNbMeshes);
4089 aResult->length( aNbMeshes );
4090 for( MED::TInt i = 0; i < aNbMeshes; i++ ) {
4091 MED::PMeshInfo aMeshInfo = aMed->GetPMeshInfo( i+1 );
4092 aResult[i] = CORBA::string_dup( aMeshInfo->GetName().c_str() );
4095 return aResult._retn();
4098 //=============================================================================
4102 * Save SMESH module's data
4104 //=============================================================================
4105 SALOMEDS::TMPFile* SMESH_Gen_i::Save( SALOMEDS::SComponent_ptr theComponent,
4110 Kernel_Utils::Localizer loc;
4112 if (!myStudyContext)
4115 // Store study contents as a set of python commands
4118 SALOMEDS::Study_var aStudy = getStudyServant();
4120 // Declare a byte stream
4121 SALOMEDS::TMPFile_var aStreamFile;
4123 // Obtain a temporary dir
4124 TCollection_AsciiString tmpDir =
4125 ( isMultiFile ) ? TCollection_AsciiString( ( char* )theURL ) : ( char* )SALOMEDS_Tool::GetTmpDir().c_str();
4127 // Create a sequence of files processed
4128 SALOMEDS_Tool::ListOfFiles aFileSeq;
4129 aFileSeq.reserve( NUM_TMP_FILES );
4131 TCollection_AsciiString aStudyName( "" );
4133 aStudyName = ( (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(aStudy->URL()) ).c_str() );
4135 // Set names of temporary files
4136 TCollection_AsciiString filename =
4137 aStudyName + TCollection_AsciiString( "_SMESH.hdf" ); // for SMESH data itself
4138 TCollection_AsciiString meshfile =
4139 aStudyName + TCollection_AsciiString( "_SMESH_Mesh.med" ); // for mesh data to be stored in MED file
4140 aFileSeq.push_back(CORBA::string_dup( filename.ToCString() ));
4141 aFileSeq.push_back(CORBA::string_dup( meshfile.ToCString() ));
4142 filename = tmpDir + filename;
4143 meshfile = tmpDir + meshfile;
4146 HDFdataset* aDataset;
4147 HDFgroup* aTopGroup;
4149 HDFgroup* aSubGroup;
4150 HDFgroup* aSubSubGroup;
4151 hdf_size aSize[ 1 ];
4154 //Remove the files if they exist: BugID: 11225
4155 #ifndef WIN32 /* unix functionality */
4156 TCollection_AsciiString cmd("rm -f \"");
4158 TCollection_AsciiString cmd("del /F \"");
4168 system(cmd.ToCString());
4170 // MED writer to be used by storage process
4171 DriverMED_W_SMESHDS_Mesh myWriter;
4172 myWriter.SetFile( meshfile.ToCString() );
4175 // SetStoreName() to groups before storing hypotheses to let them refer to
4176 // groups using "store name", which is "Group <group_persistent_id>"
4178 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4179 for ( ; itBig->More(); itBig->Next() ) {
4180 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4181 if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4182 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4183 if ( !CORBA::is_nil( anObject ) ) {
4184 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4185 if ( !myMesh->_is_nil() ) {
4186 myMesh->Load(); // load from study file if not yet done
4187 TPythonDump pd; // not to dump GetGroups()
4188 SMESH::ListOfGroups_var groups = myMesh->GetGroups();
4189 for ( CORBA::ULong i = 0; i < groups->length(); ++i )
4191 SMESH_GroupBase_i* grImpl = SMESH::DownCast<SMESH_GroupBase_i*>( groups[i]);
4194 CORBA::String_var objStr = GetORB()->object_to_string( grImpl->_this() );
4195 int anId = myStudyContext->findId( string( objStr.in() ) );
4197 sprintf( grpName, "Group %d %d", anId, grImpl->GetLocalID() );
4198 SMESHDS_GroupBase* aGrpBaseDS = grImpl->GetGroupDS();
4199 aGrpBaseDS->SetStoreName( grpName );
4209 // ---> create HDF file
4210 aFile = new HDFfile( (char*) filename.ToCString() );
4211 aFile->CreateOnDisk();
4213 // --> iterator for top-level objects
4214 SALOMEDS::ChildIterator_wrap itBig = aStudy->NewChildIterator( theComponent );
4215 for ( ; itBig->More(); itBig->Next() ) {
4216 SALOMEDS::SObject_wrap gotBranch = itBig->Value();
4218 // --> hypotheses root branch (only one for the study)
4219 if ( gotBranch->Tag() == GetHypothesisRootTag() ) {
4220 // create hypotheses root HDF group
4221 aTopGroup = new HDFgroup( "Hypotheses", aFile );
4222 aTopGroup->CreateOnDisk();
4224 // iterator for all hypotheses
4225 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4226 for ( ; it->More(); it->Next() ) {
4227 SALOMEDS::SObject_wrap mySObject = it->Value();
4228 CORBA::Object_var anObject = SObjectToObject( mySObject );
4229 if ( !CORBA::is_nil( anObject ) ) {
4230 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4231 if ( !myHyp->_is_nil() ) {
4232 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4234 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4235 std::string hypname = hn.in();
4236 std::string libname = ln.in();
4238 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4239 // WIN32 and ".so" for X-system) must be deleted
4240 int libname_len = libname.length();
4242 if( libname_len > 4 )
4243 libname.resize( libname_len - 4 );
4245 // PAL17753 (Regression: missing hypothesis in restored study)
4246 // "lib" also should be removed from the beginning
4247 //if( libname_len > 3 )
4248 //libname.resize( libname_len - 3 );
4249 if( libname_len > 6 )
4250 libname = libname.substr( 3, libname_len - 3 - 3 );
4252 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4253 CORBA::String_var hypdata = myImpl->SaveTo();
4254 int id = myStudyContext->findId( string( objStr.in() ));
4256 // for each hypothesis create HDF group basing on its id
4257 char hypGrpName[30];
4258 sprintf( hypGrpName, "Hypothesis %d", id );
4259 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4260 aGroup->CreateOnDisk();
4261 // --> type name of hypothesis
4262 aSize[ 0 ] = hypname.length() + 1;
4263 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4264 aDataset->CreateOnDisk();
4265 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4266 aDataset->CloseOnDisk();
4267 // --> server plugin library name of hypothesis
4268 aSize[ 0 ] = libname.length() + 1;
4269 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4270 aDataset->CreateOnDisk();
4271 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4272 aDataset->CloseOnDisk();
4273 // --> persistent data of hypothesis
4274 aSize[ 0 ] = strlen( hypdata.in() ) + 1;
4275 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4276 aDataset->CreateOnDisk();
4277 aDataset->WriteOnDisk( ( char* )( hypdata.in() ) );
4278 aDataset->CloseOnDisk();
4279 // close hypothesis HDF group
4280 aGroup->CloseOnDisk();
4285 // close hypotheses root HDF group
4286 aTopGroup->CloseOnDisk();
4288 // --> algorithms root branch (only one for the study)
4289 else if ( gotBranch->Tag() == GetAlgorithmsRootTag() ) {
4290 // create algorithms root HDF group
4291 aTopGroup = new HDFgroup( "Algorithms", aFile );
4292 aTopGroup->CreateOnDisk();
4294 // iterator for all algorithms
4295 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( gotBranch );
4296 for ( ; it->More(); it->Next() ) {
4297 SALOMEDS::SObject_wrap mySObject = it->Value();
4298 CORBA::Object_var anObject = SObjectToObject( mySObject );
4299 if ( !CORBA::is_nil( anObject ) ) {
4300 SMESH::SMESH_Hypothesis_var myHyp = SMESH::SMESH_Hypothesis::_narrow( anObject );
4301 if ( !myHyp->_is_nil() ) {
4302 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
4304 CORBA::String_var hn = myHyp->GetName(), ln = myHyp->GetLibName();
4305 std::string hypname = hn.in();
4306 std::string libname = ln.in();
4308 // Needs for save crossplatform libname, i.e. parth of name ( ".dll" for
4309 // WIN32 and ".so" for X-system) must be deleted
4310 int libname_len = libname.length();
4312 if( libname_len > 4 )
4313 libname.resize( libname_len - 4 );
4315 // PAL17753 (Regression: missing hypothesis in restored study)
4316 // "lib" also should be removed from the beginning
4317 //if( libname_len > 3 )
4318 //libname.resize( libname_len - 3 );
4319 if( libname_len > 6 )
4320 libname = libname.substr( 3, libname_len - 3 - 3 );
4322 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4323 CORBA::String_var hypdata = myImpl->SaveTo();
4324 int id = myStudyContext->findId( string( objStr.in() ) );
4326 // for each algorithm create HDF group basing on its id
4327 char hypGrpName[30];
4328 sprintf( hypGrpName, "Algorithm %d", id );
4329 aGroup = new HDFgroup( hypGrpName, aTopGroup );
4330 aGroup->CreateOnDisk();
4331 // --> type name of algorithm
4332 aSize[0] = hypname.length() + 1;
4333 aDataset = new HDFdataset( "Name", aGroup, HDF_STRING, aSize, 1 );
4334 aDataset->CreateOnDisk();
4335 aDataset->WriteOnDisk( ( char* )( hypname.c_str() ) );
4336 aDataset->CloseOnDisk();
4337 // --> server plugin library name of hypothesis
4338 aSize[0] = libname.length() + 1;
4339 aDataset = new HDFdataset( "LibName", aGroup, HDF_STRING, aSize, 1 );
4340 aDataset->CreateOnDisk();
4341 aDataset->WriteOnDisk( ( char* )( libname.c_str() ) );
4342 aDataset->CloseOnDisk();
4343 // --> persistent data of algorithm
4344 aSize[0] = strlen( hypdata.in() ) + 1;
4345 aDataset = new HDFdataset( "Data", aGroup, HDF_STRING, aSize, 1 );
4346 aDataset->CreateOnDisk();
4347 aDataset->WriteOnDisk( ( char* )( hypdata.in() ));
4348 aDataset->CloseOnDisk();
4349 // close algorithm HDF group
4350 aGroup->CloseOnDisk();
4355 // close algorithms root HDF group
4356 aTopGroup->CloseOnDisk();
4358 // --> mesh objects roots branches
4359 else if ( gotBranch->Tag() > GetAlgorithmsRootTag() ) {
4360 CORBA::Object_var anObject = SObjectToObject( gotBranch );
4361 if ( !CORBA::is_nil( anObject ) ) {
4362 SMESH::SMESH_Mesh_var myMesh = SMESH::SMESH_Mesh::_narrow( anObject ) ;
4363 if ( !myMesh->_is_nil() ) {
4364 SMESH_Mesh_i* myImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myMesh ).in() );
4366 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4367 int id = myStudyContext->findId( string( objStr.in() ) );
4368 ::SMESH_Mesh& myLocMesh = myImpl->GetImpl();
4369 SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
4370 bool hasShape = myLocMesh.HasShapeToMesh();
4372 // for each mesh open the HDF group basing on its id
4373 char meshGrpName[ 30 ];
4374 sprintf( meshGrpName, "Mesh %d", id );
4375 aTopGroup = new HDFgroup( meshGrpName, aFile );
4376 aTopGroup->CreateOnDisk();
4378 // --> put dataset to hdf file which is a flag that mesh has data
4379 string strHasData = "0";
4380 // check if the mesh is not empty
4381 if ( mySMESHDSMesh->NbNodes() > 0 ) {
4382 // write mesh data to med file
4383 myWriter.SetMesh( mySMESHDSMesh );
4384 myWriter.SetMeshId( id );
4387 aSize[ 0 ] = strHasData.length() + 1;
4388 aDataset = new HDFdataset( "Has data", aTopGroup, HDF_STRING, aSize, 1 );
4389 aDataset->CreateOnDisk();
4390 aDataset->WriteOnDisk( ( char* )( strHasData.c_str() ) );
4391 aDataset->CloseOnDisk();
4394 // for each mesh open the HDF group basing on its auto color parameter
4395 char meshAutoColorName[ 30 ];
4396 sprintf( meshAutoColorName, "AutoColorMesh %d", id );
4398 anAutoColor[0] = myImpl->GetAutoColor();
4400 aDataset = new HDFdataset( meshAutoColorName, aTopGroup, HDF_INT32, aSize, 1 );
4401 aDataset->CreateOnDisk();
4402 aDataset->WriteOnDisk( anAutoColor );
4403 aDataset->CloseOnDisk();
4405 // issue 0020693. Store _isModified flag
4406 int isModified = myLocMesh.GetIsModified();
4408 aDataset = new HDFdataset( "_isModified", aTopGroup, HDF_INT32, aSize, 1 );
4409 aDataset->CreateOnDisk();
4410 aDataset->WriteOnDisk( &isModified );
4411 aDataset->CloseOnDisk();
4413 // issue 20918. Store Persistent Id of SMESHDS_Mesh
4414 int meshPersistentId = mySMESHDSMesh->GetPersistentId();
4416 aDataset = new HDFdataset( "meshPersistentId", aTopGroup, HDF_INT32, aSize, 1 );
4417 aDataset->CreateOnDisk();
4418 aDataset->WriteOnDisk( &meshPersistentId );
4419 aDataset->CloseOnDisk();
4421 // Store SMESH_Mesh_i::_mainShapeTick
4422 int shapeTick = myImpl->MainShapeTick();
4424 aDataset = new HDFdataset( "shapeTick", aTopGroup, HDF_INT32, aSize, 1 );
4425 aDataset->CreateOnDisk();
4426 aDataset->WriteOnDisk( &shapeTick );
4427 aDataset->CloseOnDisk();
4429 // write reference on a shape if exists
4430 SALOMEDS::SObject_wrap myRef;
4431 bool shapeRefFound = false;
4432 bool found = gotBranch->FindSubObject( GetRefOnShapeTag(), myRef.inout() );
4434 SALOMEDS::SObject_wrap myShape;
4435 bool ok = myRef->ReferencedObject( myShape.inout() );
4437 CORBA::Object_var shapeObj = myShape->GetObject();
4438 shapeRefFound = (! CORBA::is_nil( shapeObj ));
4439 CORBA::String_var myRefOnObject = myShape->GetID();
4440 if ( shapeRefFound && myRefOnObject.in()[0] ) {
4441 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4442 aDataset = new HDFdataset( "Ref on shape", aTopGroup, HDF_STRING, aSize, 1 );
4443 aDataset->CreateOnDisk();
4444 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ) );
4445 aDataset->CloseOnDisk();
4451 std::string info = myImpl->FileInfoToString();
4452 if ( !info.empty() )
4454 aSize[ 0 ] = info.size();
4455 aDataset = new HDFdataset( "file info", aTopGroup, HDF_STRING, aSize, 1 );
4456 aDataset->CreateOnDisk();
4457 aDataset->WriteOnDisk( (char*) info.data() );
4458 aDataset->CloseOnDisk();
4461 // write applied hypotheses if exist
4462 SALOMEDS::SObject_wrap myHypBranch;
4463 found = gotBranch->FindSubObject( GetRefOnAppliedHypothesisTag(), myHypBranch.inout() );
4464 if ( found && !shapeRefFound && hasShape ) { // remove applied hyps
4465 aStudy->NewBuilder()->RemoveObjectWithChildren( myHypBranch );
4467 if ( found && (shapeRefFound || !hasShape) ) {
4468 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
4469 aGroup->CreateOnDisk();
4471 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myHypBranch );
4473 for ( ; it->More(); it->Next() ) {
4474 SALOMEDS::SObject_wrap mySObject = it->Value();
4475 SALOMEDS::SObject_wrap myRefOnHyp;
4476 bool ok = mySObject->ReferencedObject( myRefOnHyp.inout() );
4478 // san - it is impossible to recover applied hypotheses
4479 // using their entries within Load() method,
4480 // for there are no AttributeIORs in the study when Load() is working.
4481 // Hence, it is better to store persistent IDs of hypotheses as references to them
4483 //string myRefOnObject = myRefOnHyp->GetID();
4484 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4485 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4486 int id = myStudyContext->findId( string( objStr.in() ) );
4487 //if ( myRefOnObject.length() > 0 ) {
4488 //aSize[ 0 ] = myRefOnObject.length() + 1;
4489 char hypName[ 30 ], hypId[ 30 ];
4490 sprintf( hypName, "Hyp %d", ++hypNb );
4491 sprintf( hypId, "%d", id );
4492 aSize[ 0 ] = strlen( hypId ) + 1;
4493 aDataset = new HDFdataset( hypName, aGroup, HDF_STRING, aSize, 1 );
4494 aDataset->CreateOnDisk();
4495 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4496 aDataset->WriteOnDisk( hypId );
4497 aDataset->CloseOnDisk();
4501 aGroup->CloseOnDisk();
4504 // write applied algorithms if exist
4505 SALOMEDS::SObject_wrap myAlgoBranch;
4506 found = gotBranch->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4507 myAlgoBranch.inout() );
4508 if ( found && !shapeRefFound && hasShape) { // remove applied algos
4509 aStudy->NewBuilder()->RemoveObjectWithChildren( myAlgoBranch );
4511 if ( found && (shapeRefFound || !hasShape)) {
4512 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
4513 aGroup->CreateOnDisk();
4515 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myAlgoBranch );
4517 for ( ; it->More(); it->Next() ) {
4518 SALOMEDS::SObject_wrap mySObject = it->Value();
4519 SALOMEDS::SObject_wrap myRefOnAlgo;
4520 bool ok = mySObject->ReferencedObject( myRefOnAlgo.inout() );
4522 // san - it is impossible to recover applied algorithms
4523 // using their entries within Load() method,
4524 // for there are no AttributeIORs in the study when Load() is working.
4525 // Hence, it is better to store persistent IDs of algorithms as references to them
4527 //string myRefOnObject = myRefOnAlgo->GetID();
4528 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4529 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4530 int id = myStudyContext->findId( string( objStr.in() ) );
4531 //if ( myRefOnObject.length() > 0 ) {
4532 //aSize[ 0 ] = myRefOnObject.length() + 1;
4533 char algoName[ 30 ], algoId[ 30 ];
4534 sprintf( algoName, "Algo %d", ++algoNb );
4535 sprintf( algoId, "%d", id );
4536 aSize[ 0 ] = strlen( algoId ) + 1;
4537 aDataset = new HDFdataset( algoName, aGroup, HDF_STRING, aSize, 1 );
4538 aDataset->CreateOnDisk();
4539 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4540 aDataset->WriteOnDisk( algoId );
4541 aDataset->CloseOnDisk();
4545 aGroup->CloseOnDisk();
4548 // --> submesh objects sub-branches
4550 for ( int i = GetSubMeshOnVertexTag(); i <= GetSubMeshOnCompoundTag(); i++ ) {
4551 SALOMEDS::SObject_wrap mySubmeshBranch;
4552 found = gotBranch->FindSubObject( i, mySubmeshBranch.inout() );
4554 if ( found ) // check if there is shape reference in submeshes
4556 bool hasShapeRef = false;
4557 SALOMEDS::ChildIterator_wrap itSM =
4558 aStudy->NewChildIterator( mySubmeshBranch );
4559 for ( ; itSM->More(); itSM->Next() ) {
4560 SALOMEDS::SObject_wrap mySubRef, myShape, mySObject = itSM->Value();
4561 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4562 mySubRef->ReferencedObject( myShape.inout() );
4563 if ( !CORBA::is_nil( myShape ) && !CORBA::is_nil( myShape->GetObject() ))
4566 { // remove one submesh
4567 if ( shapeRefFound )
4568 { // unassign hypothesis
4569 SMESH::SMESH_subMesh_var mySubMesh =
4570 SMESH::SMESH_subMesh::_narrow( SObjectToObject( mySObject ));
4571 if ( !mySubMesh->_is_nil() ) {
4572 int shapeID = mySubMesh->GetId();
4573 TopoDS_Shape S = mySMESHDSMesh->IndexToShape( shapeID );
4574 const list<const SMESHDS_Hypothesis*>& hypList =
4575 mySMESHDSMesh->GetHypothesis( S );
4576 list<const SMESHDS_Hypothesis*>::const_iterator hyp = hypList.begin();
4577 while ( hyp != hypList.end() ) {
4578 int hypID = (*hyp++)->GetID(); // goto next hyp here because
4579 myLocMesh.RemoveHypothesis( S, hypID ); // hypList changes here
4583 aStudy->NewBuilder()->RemoveObjectWithChildren( mySObject );
4585 } // loop on submeshes of a type
4586 if ( !shapeRefFound || !hasShapeRef ) { // remove the whole submeshes branch
4587 aStudy->NewBuilder()->RemoveObjectWithChildren( mySubmeshBranch );
4590 } // end check if there is shape reference in submeshes
4592 char name_meshgroup[ 30 ];
4593 if ( i == GetSubMeshOnVertexTag() )
4594 strcpy( name_meshgroup, "SubMeshes On Vertex" );
4595 else if ( i == GetSubMeshOnEdgeTag() )
4596 strcpy( name_meshgroup, "SubMeshes On Edge" );
4597 else if ( i == GetSubMeshOnWireTag() )
4598 strcpy( name_meshgroup, "SubMeshes On Wire" );
4599 else if ( i == GetSubMeshOnFaceTag() )
4600 strcpy( name_meshgroup, "SubMeshes On Face" );
4601 else if ( i == GetSubMeshOnShellTag() )
4602 strcpy( name_meshgroup, "SubMeshes On Shell" );
4603 else if ( i == GetSubMeshOnSolidTag() )
4604 strcpy( name_meshgroup, "SubMeshes On Solid" );
4605 else if ( i == GetSubMeshOnCompoundTag() )
4606 strcpy( name_meshgroup, "SubMeshes On Compound" );
4608 // for each type of submeshes create container HDF group
4609 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
4610 aGroup->CreateOnDisk();
4612 // iterator for all submeshes of given type
4613 SALOMEDS::ChildIterator_wrap itSM = aStudy->NewChildIterator( mySubmeshBranch );
4614 for ( ; itSM->More(); itSM->Next() ) {
4615 SALOMEDS::SObject_wrap mySObject = itSM->Value();
4616 CORBA::Object_var anSubObject = SObjectToObject( mySObject );
4617 if ( !CORBA::is_nil( anSubObject ))
4619 SMESH::SMESH_subMesh_var mySubMesh = SMESH::SMESH_subMesh::_narrow( anSubObject ) ;
4620 CORBA::String_var objStr = GetORB()->object_to_string( anSubObject );
4621 int subid = myStudyContext->findId( string( objStr.in() ) );
4623 // for each mesh open the HDF group basing on its id
4624 char submeshGrpName[ 30 ];
4625 sprintf( submeshGrpName, "SubMesh %d", subid );
4626 aSubGroup = new HDFgroup( submeshGrpName, aGroup );
4627 aSubGroup->CreateOnDisk();
4629 // write reference on a shape, already checked if it exists
4630 SALOMEDS::SObject_wrap mySubRef, myShape;
4631 if ( mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ))
4632 mySubRef->ReferencedObject( myShape.inout() );
4633 string myRefOnObject = myShape->GetID();
4634 if ( myRefOnObject.length() > 0 ) {
4635 aSize[ 0 ] = myRefOnObject.length() + 1;
4636 aDataset = new HDFdataset( "Ref on shape", aSubGroup, HDF_STRING, aSize, 1 );
4637 aDataset->CreateOnDisk();
4638 aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4639 aDataset->CloseOnDisk();
4642 // write applied hypotheses if exist
4643 SALOMEDS::SObject_wrap mySubHypBranch;
4644 found = mySObject->FindSubObject( GetRefOnAppliedHypothesisTag(),
4645 mySubHypBranch.inout() );
4647 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
4648 aSubSubGroup->CreateOnDisk();
4650 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( mySubHypBranch );
4652 for ( ; it->More(); it->Next() ) {
4653 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4654 SALOMEDS::SObject_wrap myRefOnHyp;
4655 bool ok = mySubSObject->ReferencedObject( myRefOnHyp.inout() );
4657 //string myRefOnObject = myRefOnHyp->GetID();
4658 CORBA::Object_var anObject = SObjectToObject( myRefOnHyp );
4659 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4660 int id = myStudyContext->findId( string( objStr.in() ) );
4661 //if ( myRefOnObject.length() > 0 ) {
4662 //aSize[ 0 ] = myRefOnObject.length() + 1;
4663 char hypName[ 30 ], hypId[ 30 ];
4664 sprintf( hypName, "Hyp %d", ++hypNb );
4665 sprintf( hypId, "%d", id );
4666 aSize[ 0 ] = strlen( hypId ) + 1;
4667 aDataset = new HDFdataset( hypName, aSubSubGroup, HDF_STRING, aSize, 1 );
4668 aDataset->CreateOnDisk();
4669 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4670 aDataset->WriteOnDisk( hypId );
4671 aDataset->CloseOnDisk();
4675 aSubSubGroup->CloseOnDisk();
4678 // write applied algorithms if exist
4679 SALOMEDS::SObject_wrap mySubAlgoBranch;
4680 found = mySObject->FindSubObject( GetRefOnAppliedAlgorithmsTag(),
4681 mySubAlgoBranch.inout() );
4683 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
4684 aSubSubGroup->CreateOnDisk();
4686 SALOMEDS::ChildIterator_wrap it =
4687 aStudy->NewChildIterator( mySubAlgoBranch );
4689 for ( ; it->More(); it->Next() ) {
4690 SALOMEDS::SObject_wrap mySubSObject = it->Value();
4691 SALOMEDS::SObject_wrap myRefOnAlgo;
4692 bool ok = mySubSObject->ReferencedObject( myRefOnAlgo.inout() );
4694 //string myRefOnObject = myRefOnAlgo->GetID();
4695 CORBA::Object_var anObject = SObjectToObject( myRefOnAlgo );
4696 CORBA::String_var objStr = GetORB()->object_to_string( anObject );
4697 int id = myStudyContext->findId( string( objStr.in() ) );
4698 //if ( myRefOnObject.length() > 0 ) {
4699 //aSize[ 0 ] = myRefOnObject.length() + 1;
4700 char algoName[ 30 ], algoId[ 30 ];
4701 sprintf( algoName, "Algo %d", ++algoNb );
4702 sprintf( algoId, "%d", id );
4703 aSize[ 0 ] = strlen( algoId ) + 1;
4704 aDataset = new HDFdataset( algoName, aSubSubGroup, HDF_STRING, aSize, 1 );
4705 aDataset->CreateOnDisk();
4706 //aDataset->WriteOnDisk( ( char* )( myRefOnObject.c_str() ) );
4707 aDataset->WriteOnDisk( algoId );
4708 aDataset->CloseOnDisk();
4712 aSubSubGroup->CloseOnDisk();
4714 // close submesh HDF group
4715 aSubGroup->CloseOnDisk();
4718 // close container of submeshes by type HDF group
4719 aGroup->CloseOnDisk();
4722 // All sub-meshes will be stored in MED file
4723 // .. will NOT (PAL 12992)
4724 //if ( shapeRefFound )
4725 //myWriter.AddAllSubMeshes();
4727 // store submesh order if any
4728 const TListOfListOfInt& theOrderIds = myLocMesh.GetMeshOrder();
4729 if ( theOrderIds.size() ) {
4730 char order_list[ 30 ];
4731 strcpy( order_list, "Mesh Order" );
4732 // count number of submesh ids
4734 TListOfListOfInt::const_iterator idIt = theOrderIds.begin();
4735 for ( ; idIt != theOrderIds.end(); idIt++ )
4736 nbIDs += (*idIt).size();
4737 // number of values = number of IDs +
4738 // number of lists (for separators) - 1
4739 int* smIDs = new int [ nbIDs + theOrderIds.size() - 1 ];
4740 idIt = theOrderIds.begin();
4741 for ( int i = 0; idIt != theOrderIds.end(); idIt++ ) {
4742 const TListOfInt& idList = *idIt;
4743 if (idIt != theOrderIds.begin()) // not first list
4744 smIDs[ i++ ] = -1/* *idList.size()*/; // separator between lists
4745 // dump submesh ids from current list
4746 TListOfInt::const_iterator id_smId = idList.begin();
4747 for( ; id_smId != idList.end(); id_smId++ )
4748 smIDs[ i++ ] = *id_smId;
4751 aSize[ 0 ] = nbIDs + theOrderIds.size() - 1;
4753 aDataset = new HDFdataset( order_list, aTopGroup, HDF_INT32, aSize, 1 );
4754 aDataset->CreateOnDisk();
4755 aDataset->WriteOnDisk( smIDs );
4756 aDataset->CloseOnDisk();
4761 // groups root sub-branch
4762 SALOMEDS::SObject_wrap myGroupsBranch;
4763 for ( int i = GetNodeGroupsTag(); i <= GetBallElementsGroupsTag(); i++ ) {
4764 found = gotBranch->FindSubObject( i, myGroupsBranch.inout() );
4766 char name_group[ 30 ];
4767 if ( i == GetNodeGroupsTag() )
4768 strcpy( name_group, "Groups of Nodes" );
4769 else if ( i == GetEdgeGroupsTag() )
4770 strcpy( name_group, "Groups of Edges" );
4771 else if ( i == GetFaceGroupsTag() )
4772 strcpy( name_group, "Groups of Faces" );
4773 else if ( i == GetVolumeGroupsTag() )
4774 strcpy( name_group, "Groups of Volumes" );
4775 else if ( i == Get0DElementsGroupsTag() )
4776 strcpy( name_group, "Groups of 0D Elements" );
4777 else if ( i == GetBallElementsGroupsTag() )
4778 strcpy( name_group, "Groups of Balls" );
4780 aGroup = new HDFgroup( name_group, aTopGroup );
4781 aGroup->CreateOnDisk();
4783 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( myGroupsBranch );
4784 for ( ; it->More(); it->Next() ) {
4785 SALOMEDS::SObject_wrap mySObject = it->Value();
4786 CORBA::Object_var aSubObject = SObjectToObject( mySObject );
4787 if ( !CORBA::is_nil( aSubObject ) ) {
4788 SMESH_GroupBase_i* myGroupImpl =
4789 dynamic_cast<SMESH_GroupBase_i*>( GetServant( aSubObject ).in() );
4792 SMESHDS_GroupBase* aGrpBaseDS = myGroupImpl->GetGroupDS();
4796 CORBA::String_var objStr = GetORB()->object_to_string( aSubObject );
4797 int anId = myStudyContext->findId( string( objStr.in() ) );
4799 // For each group, create a dataset named "Group <group_persistent_id>"
4800 // and store the group's user name into it
4801 const char* grpName = aGrpBaseDS->GetStoreName();
4802 CORBA::String_var aUserName = myGroupImpl->GetName();
4803 aSize[ 0 ] = strlen( aUserName ) + 1;
4805 aDataset = new HDFdataset( grpName, aGroup, HDF_STRING, aSize, 1 );
4806 aDataset->CreateOnDisk();
4807 aDataset->WriteOnDisk( aUserName );
4808 aDataset->CloseOnDisk();
4811 // For each group, create a dataset named "Group <group_persistent_id> Color"
4812 // and store the group's color into it
4813 char grpColorName[ 30 ];
4814 sprintf( grpColorName, "ColorGroup %d", anId );
4815 SALOMEDS::Color aColor = myGroupImpl->GetColor();
4817 anRGB[ 0 ] = aColor.R;
4818 anRGB[ 1 ] = aColor.G;
4819 anRGB[ 2 ] = aColor.B;
4821 aDataset = new HDFdataset( grpColorName, aGroup, HDF_FLOAT64, aSize, 1 );
4822 aDataset->CreateOnDisk();
4823 aDataset->WriteOnDisk( anRGB );
4824 aDataset->CloseOnDisk();
4826 // Pass SMESHDS_Group to MED writer
4827 SMESHDS_Group* aGrpDS = dynamic_cast<SMESHDS_Group*>( aGrpBaseDS );
4829 myWriter.AddGroup( aGrpDS );
4831 // write reference on a shape if exists
4832 SMESHDS_GroupOnGeom* aGeomGrp =
4833 dynamic_cast<SMESHDS_GroupOnGeom*>( aGrpBaseDS );
4835 SALOMEDS::SObject_wrap mySubRef, myShape;
4836 if (mySObject->FindSubObject( GetRefOnShapeTag(), mySubRef.inout() ) &&
4837 mySubRef->ReferencedObject( myShape.inout() ) &&
4838 !CORBA::is_nil( myShape->GetObject() ))
4840 CORBA::String_var myRefOnObject = myShape->GetID();
4841 if ( myRefOnObject.in()[0] ) {
4842 char aRefName[ 30 ];
4843 sprintf( aRefName, "Ref on shape %d", anId);
4844 aSize[ 0 ] = strlen( myRefOnObject.in() ) + 1;
4845 aDataset = new HDFdataset(aRefName, aGroup, HDF_STRING, aSize, 1);
4846 aDataset->CreateOnDisk();
4847 aDataset->WriteOnDisk( ( char* )( myRefOnObject.in() ));
4848 aDataset->CloseOnDisk();
4851 else // shape ref is invalid:
4853 // save a group on geometry as ordinary group
4854 myWriter.AddGroup( aGeomGrp );
4857 else if ( SMESH_GroupOnFilter_i* aFilterGrp_i =
4858 dynamic_cast<SMESH_GroupOnFilter_i*>( myGroupImpl ))
4860 std::string str = aFilterGrp_i->FilterToString();
4861 std::string hdfGrpName = "Filter " + SMESH_Comment(anId);
4862 aSize[ 0 ] = str.length() + 1;
4863 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup, HDF_STRING, aSize, 1);
4864 aDataset->CreateOnDisk();
4865 aDataset->WriteOnDisk( ( char* )( str.c_str() ) );
4866 aDataset->CloseOnDisk();
4870 aGroup->CloseOnDisk();
4874 if ( strcmp( strHasData.c_str(), "1" ) == 0 )
4876 // Flush current mesh information into MED file
4879 // save info on nb of elements
4880 SMESH_PreMeshInfo::SaveToFile( myImpl, id, aFile );
4882 // maybe a shape was deleted in the study
4883 if ( !shapeRefFound && !mySMESHDSMesh->ShapeToMesh().IsNull() && hasShape) {
4884 TopoDS_Shape nullShape;
4885 myLocMesh.ShapeToMesh( nullShape ); // remove shape referring data
4888 SMESHDS_SubMeshIteratorPtr smIt = mySMESHDSMesh->SubMeshes();
4893 aGroup = new HDFgroup( "Submeshes", aTopGroup );
4894 aGroup->CreateOnDisk();
4896 // each element belongs to one or none submesh,
4897 // so for each node/element, we store a submesh ID
4899 // Store submesh IDs
4900 for ( int isNode = 0; isNode < 2; ++isNode )
4902 SMDS_ElemIteratorPtr eIt =
4903 mySMESHDSMesh->elementsIterator( isNode ? SMDSAbs_Node : SMDSAbs_All );
4904 int nbElems = isNode ? mySMESHDSMesh->NbNodes() : mySMESHDSMesh->GetMeshInfo().NbElements();
4907 std::vector<int> smIDs; smIDs.reserve( nbElems );
4908 while ( eIt->more() )
4909 if ( const SMDS_MeshElement* e = eIt->next())
4910 smIDs.push_back( e->getshapeId() );
4912 aSize[ 0 ] = nbElems;
4913 string aDSName( isNode ? "Node Submeshes" : "Element Submeshes");
4914 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
4915 aDataset->CreateOnDisk();
4916 aDataset->WriteOnDisk( & smIDs[0] );
4917 aDataset->CloseOnDisk();
4920 aGroup->CloseOnDisk();
4922 // Store node positions on sub-shapes (SMDS_Position):
4923 // ----------------------------------------------------
4925 aGroup = new HDFgroup( "Node Positions", aTopGroup );
4926 aGroup->CreateOnDisk();
4928 // in aGroup, create 5 datasets to contain:
4929 // "Nodes on Edges" - ID of node on edge
4930 // "Edge positions" - U parameter on node on edge
4931 // "Nodes on Faces" - ID of node on face
4932 // "Face U positions" - U parameter of node on face
4933 // "Face V positions" - V parameter of node on face
4935 // Find out nb of nodes on edges and faces
4936 // Collect corresponding sub-meshes
4937 int nbEdgeNodes = 0, nbFaceNodes = 0;
4938 list<SMESHDS_SubMesh*> aEdgeSM, aFaceSM;
4939 // loop on SMESHDS_SubMesh'es
4940 while ( smIt->more() )
4942 SMESHDS_SubMesh* aSubMesh = const_cast< SMESHDS_SubMesh* >( smIt->next() );
4943 if ( aSubMesh->IsComplexSubmesh() )
4944 continue; // submesh containing other submeshs
4945 int nbNodes = aSubMesh->NbNodes();
4946 if ( nbNodes == 0 ) continue;
4948 int aShapeID = aSubMesh->GetID();
4949 if ( aShapeID < 1 || aShapeID > mySMESHDSMesh->MaxShapeIndex() )
4951 int aShapeType = mySMESHDSMesh->IndexToShape( aShapeID ).ShapeType();
4952 // write only SMDS_FacePosition and SMDS_EdgePosition
4953 switch ( aShapeType ) {
4955 nbFaceNodes += nbNodes;
4956 aFaceSM.push_back( aSubMesh );
4959 nbEdgeNodes += nbNodes;
4960 aEdgeSM.push_back( aSubMesh );
4966 // Treat positions on edges or faces
4967 for ( int onFace = 0; onFace < 2; onFace++ )
4969 // Create arrays to store in datasets
4970 int iNode = 0, nbNodes = ( onFace ? nbFaceNodes : nbEdgeNodes );
4971 if (!nbNodes) continue;
4972 int* aNodeIDs = new int [ nbNodes ];
4973 double* aUPos = new double [ nbNodes ];
4974 double* aVPos = ( onFace ? new double[ nbNodes ] : 0 );
4977 // loop on sub-meshes
4978 list<SMESHDS_SubMesh*> * pListSM = ( onFace ? &aFaceSM : &aEdgeSM );
4979 list<SMESHDS_SubMesh*>::iterator itSM = pListSM->begin();
4980 for ( ; itSM != pListSM->end(); itSM++ )
4982 SMESHDS_SubMesh* aSubMesh = (*itSM);
4984 SMDS_NodeIteratorPtr itNode = aSubMesh->GetNodes();
4985 // loop on nodes in aSubMesh
4986 while ( itNode->more() )
4989 const SMDS_MeshNode* node = itNode->next();
4990 aNodeIDs [ iNode ] = node->GetID();
4993 const SMDS_PositionPtr pos = node->GetPosition();
4994 if ( onFace ) { // on FACE
4995 SMDS_FacePositionPtr fPos = pos;
4997 aUPos[ iNode ] = fPos->GetUParameter();
4998 aVPos[ iNode ] = fPos->GetVParameter();
5005 SMDS_EdgePositionPtr ePos = pos;
5007 aUPos[ iNode ] = ePos->GetUParameter();
5013 } // loop on nodes in aSubMesh
5014 } // loop on sub-meshes
5019 aSize[ 0 ] = nbNodes;
5021 string aDSName( onFace ? "Nodes on Faces" : "Nodes on Edges");
5022 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_INT32, aSize, 1 );
5023 aDataset->CreateOnDisk();
5024 aDataset->WriteOnDisk( aNodeIDs );
5025 aDataset->CloseOnDisk();
5028 aDSName = ( onFace ? "Face U positions" : "Edge positions");
5029 aDataset = new HDFdataset( (char*)aDSName.c_str(), aGroup, HDF_FLOAT64, aSize, 1);
5030 aDataset->CreateOnDisk();
5031 aDataset->WriteOnDisk( aUPos );
5032 aDataset->CloseOnDisk();
5035 aDataset = new HDFdataset( "Face V positions", aGroup, HDF_FLOAT64, aSize, 1);
5036 aDataset->CreateOnDisk();
5037 aDataset->WriteOnDisk( aVPos );
5038 aDataset->CloseOnDisk();
5043 if ( aVPos ) delete [] aVPos;
5045 } // treat positions on edges or faces
5047 // close "Node Positions" group
5048 aGroup->CloseOnDisk();
5050 } // if ( there are submeshes in SMESHDS_Mesh )
5053 // close mesh HDF group
5054 aTopGroup->CloseOnDisk();
5062 aFile->CloseOnDisk();
5065 // Convert temporary files to stream
5066 aStreamFile = SALOMEDS_Tool::PutFilesToStream( tmpDir.ToCString(), aFileSeq, isMultiFile );
5068 // Remove temporary files and directory
5070 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5072 return aStreamFile._retn();
5075 //=============================================================================
5077 * SMESH_Gen_i::SaveASCII
5079 * Save SMESH module's data in ASCII format
5081 //=============================================================================
5083 SALOMEDS::TMPFile* SMESH_Gen_i::SaveASCII( SALOMEDS::SComponent_ptr theComponent,
5085 bool isMultiFile ) {
5086 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::SaveASCII" );
5087 SALOMEDS::TMPFile_var aStreamFile = Save( theComponent, theURL, isMultiFile );
5088 return aStreamFile._retn();
5090 //after usual saving needs to encipher binary to text string
5091 //Any binary symbol will be represent as "|xx" () hexadecimal format number
5092 int size = aStreamFile.in().length();
5093 _CORBA_Octet* buffer = new _CORBA_Octet[size*3+1];
5094 for ( int i = 0; i < size; i++ )
5095 sprintf( (char*)&(buffer[i*3]), "|%02x", aStreamFile[i] );
5097 buffer[size * 3] = '\0';
5099 SALOMEDS::TMPFile_var anAsciiStreamFile = new SALOMEDS::TMPFile(size*3, size*3, buffer, 1);
5101 return anAsciiStreamFile._retn();
5104 //=============================================================================
5108 * Load SMESH module's data
5110 //=============================================================================
5112 bool SMESH_Gen_i::Load( SALOMEDS::SComponent_ptr theComponent,
5113 const SALOMEDS::TMPFile& theStream,
5117 UpdateStudy(); // load geom data
5118 Kernel_Utils::Localizer loc;
5120 SALOMEDS::Study_var aStudy = getStudyServant();
5122 // Get temporary files location
5123 TCollection_AsciiString tmpDir =
5124 ( char* )( isMultiFile ? theURL : SALOMEDS_Tool::GetTmpDir().c_str() );
5126 // Convert the stream into sequence of files to process
5127 SALOMEDS_Tool::ListOfFiles aFileSeq = SALOMEDS_Tool::PutStreamToFiles( theStream,
5130 TCollection_AsciiString aStudyName( "" );
5131 if ( isMultiFile ) {
5132 CORBA::WString_var url = aStudy->URL();
5133 aStudyName = (char*)SALOMEDS_Tool::GetNameFromPath( Kernel_Utils::encode(url.in()) ).c_str();
5135 // Set names of temporary files
5136 TCollection_AsciiString filename = tmpDir + aStudyName + "_SMESH.hdf";
5137 TCollection_AsciiString meshfile = tmpDir + aStudyName + "_SMESH_Mesh.med";
5141 HDFdataset* aDataset;
5142 HDFgroup* aTopGroup;
5144 HDFgroup* aSubGroup;
5145 HDFgroup* aSubSubGroup;
5148 // ---> open HDF file
5149 aFile = new HDFfile( (char*) filename.ToCString() );
5151 aFile->OpenOnDisk( HDF_RDONLY );
5153 catch ( HDFexception ) {
5154 INFOS( "Load(): " << filename << " not found!" );
5158 TPythonDump pd; // prevent dump during loading
5160 // DriverMED_R_SMESHDS_Mesh myReader;
5161 // myReader.SetFile( meshfile.ToCString() );
5163 // For PAL13473 ("Repetitive mesh") implementation.
5164 // New dependencies between SMESH objects are established:
5165 // now hypotheses can refer to meshes, shapes and other hypotheses.
5166 // To keep data consistent, the following order of data restoration
5168 // 1. Create hypotheses
5169 // 2. Create all meshes
5170 // 3. Load hypotheses' data
5173 list< pair< SMESH_Hypothesis_i*, string > > hypDataList;
5174 list< pair< SMESH_Mesh_i*, HDFgroup* > > meshGroupList;
5175 list< SMESH::Filter_var > filters;
5177 // get total number of top-level groups
5178 int aNbGroups = aFile->nInternalObjects();
5179 if ( aNbGroups > 0 ) {
5180 // --> in first turn we should read&create hypotheses
5181 if ( aFile->ExistInternalObject( "Hypotheses" ) ) {
5182 // open hypotheses root HDF group
5183 aTopGroup = new HDFgroup( "Hypotheses", aFile );
5184 aTopGroup->OpenOnDisk();
5186 // get number of hypotheses
5187 int aNbObjects = aTopGroup->nInternalObjects();
5188 for ( int j = 0; j < aNbObjects; j++ ) {
5189 // try to identify hypothesis
5190 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5191 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5193 if ( string( hypGrpName ).substr( 0, 10 ) == string( "Hypothesis" ) ) {
5194 // open hypothesis group
5195 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5196 aGroup->OpenOnDisk();
5198 // --> get hypothesis id
5199 int id = atoi( string( hypGrpName ).substr( 10 ).c_str() );
5204 // get number of datasets
5205 int aNbSubObjects = aGroup->nInternalObjects();
5206 for ( int k = 0; k < aNbSubObjects; k++ ) {
5208 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5209 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5210 // --> get hypothesis name
5211 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5212 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5213 aDataset->OpenOnDisk();
5214 size = aDataset->GetSize();
5215 char* hypname_str = new char[ size ];
5216 aDataset->ReadFromDisk( hypname_str );
5217 hypname = string( hypname_str );
5218 delete [] hypname_str;
5219 aDataset->CloseOnDisk();
5221 // --> get hypothesis plugin library name
5222 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5223 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5224 aDataset->OpenOnDisk();
5225 size = aDataset->GetSize();
5226 char* libname_str = new char[ size ];
5227 aDataset->ReadFromDisk( libname_str );
5228 if(MYDEBUG) SCRUTE( libname_str );
5229 libname = string( libname_str );
5230 delete [] libname_str;
5231 aDataset->CloseOnDisk();
5233 // --> get hypothesis data
5234 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5235 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5236 aDataset->OpenOnDisk();
5237 size = aDataset->GetSize();
5238 char* hypdata_str = new char[ size ];
5239 aDataset->ReadFromDisk( hypdata_str );
5240 hypdata = string( hypdata_str );
5241 delete [] hypdata_str;
5242 aDataset->CloseOnDisk();
5245 // close hypothesis HDF group
5246 aGroup->CloseOnDisk();
5248 // --> restore hypothesis from data
5249 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5250 if(MYDEBUG) MESSAGE("VSR - load hypothesis : id = " << id <<
5251 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5252 SMESH::SMESH_Hypothesis_var myHyp;
5254 try { // protect persistence mechanism against exceptions
5255 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5258 INFOS( "Exception during hypothesis creation" );
5261 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5263 // myImpl->LoadFrom( hypdata.c_str() );
5264 hypDataList.push_back( make_pair( myImpl, hypdata ));
5265 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5266 int newId = myStudyContext->findId( iorString.in() );
5267 myStudyContext->mapOldToNew( id, newId );
5270 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5274 // close hypotheses root HDF group
5275 aTopGroup->CloseOnDisk();
5279 // --> then we should read&create algorithms
5280 if ( aFile->ExistInternalObject( "Algorithms" ) ) {
5281 // open algorithms root HDF group
5282 aTopGroup = new HDFgroup( "Algorithms", aFile );
5283 aTopGroup->OpenOnDisk();
5285 // get number of algorithms
5286 int aNbObjects = aTopGroup->nInternalObjects();
5287 for ( int j = 0; j < aNbObjects; j++ ) {
5288 // try to identify algorithm
5289 char hypGrpName[ HDF_NAME_MAX_LEN+1 ];
5290 aTopGroup->InternalObjectIndentify( j, hypGrpName );
5292 if ( string( hypGrpName ).substr( 0, 9 ) == string( "Algorithm" ) ) {
5293 // open algorithm group
5294 aGroup = new HDFgroup( hypGrpName, aTopGroup );
5295 aGroup->OpenOnDisk();
5297 // --> get algorithm id
5298 int id = atoi( string( hypGrpName ).substr( 9 ).c_str() );
5303 // get number of datasets
5304 int aNbSubObjects = aGroup->nInternalObjects();
5305 for ( int k = 0; k < aNbSubObjects; k++ ) {
5307 char name_of_subgroup[ HDF_NAME_MAX_LEN+1 ];
5308 aGroup->InternalObjectIndentify( k, name_of_subgroup );
5309 // --> get algorithm name
5310 if ( strcmp( name_of_subgroup, "Name" ) == 0 ) {
5311 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5312 aDataset->OpenOnDisk();
5313 size = aDataset->GetSize();
5314 char* hypname_str = new char[ size ];
5315 aDataset->ReadFromDisk( hypname_str );
5316 hypname = string( hypname_str );
5317 delete [] hypname_str;
5318 aDataset->CloseOnDisk();
5320 // --> get algorithm plugin library name
5321 if ( strcmp( name_of_subgroup, "LibName" ) == 0 ) {
5322 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5323 aDataset->OpenOnDisk();
5324 size = aDataset->GetSize();
5325 char* libname_str = new char[ size ];
5326 aDataset->ReadFromDisk( libname_str );
5327 if(MYDEBUG) SCRUTE( libname_str );
5328 libname = string( libname_str );
5329 delete [] libname_str;
5330 aDataset->CloseOnDisk();
5332 // --> get algorithm data
5333 if ( strcmp( name_of_subgroup, "Data" ) == 0 ) {
5334 aDataset = new HDFdataset( name_of_subgroup, aGroup );
5335 aDataset->OpenOnDisk();
5336 size = aDataset->GetSize();
5337 char* hypdata_str = new char[ size ];
5338 aDataset->ReadFromDisk( hypdata_str );
5339 if(MYDEBUG) SCRUTE( hypdata_str );
5340 hypdata = string( hypdata_str );
5341 delete [] hypdata_str;
5342 aDataset->CloseOnDisk();
5345 // close algorithm HDF group
5346 aGroup->CloseOnDisk();
5348 // --> restore algorithm from data
5349 if ( id > 0 && !hypname.empty()/* && !hypdata.empty()*/ ) { // VSR : persistent data can be empty
5350 if(MYDEBUG) MESSAGE("VSR - load algo : id = " << id <<
5351 ", name = " << hypname.c_str() << ", persistent string = " << hypdata.c_str());
5352 SMESH::SMESH_Hypothesis_var myHyp;
5354 try { // protect persistence mechanism against exceptions
5355 myHyp = this->createHypothesis( hypname.c_str(), libname.c_str() );
5357 catch( SALOME::SALOME_Exception& ex )
5359 INFOS( "Exception during hypothesis creation: " << ex.details.text );
5362 INFOS( "Exception during hypothesis creation" );
5365 SMESH_Hypothesis_i* myImpl = dynamic_cast<SMESH_Hypothesis_i*>( GetServant( myHyp ).in() );
5367 //myImpl->LoadFrom( hypdata.c_str() );
5368 hypDataList.push_back( make_pair( myImpl, hypdata ));
5369 CORBA::String_var iorString = GetORB()->object_to_string( myHyp );
5370 int newId = myStudyContext->findId( iorString.in() );
5371 myStudyContext->mapOldToNew( id, newId );
5374 if(MYDEBUG) MESSAGE( "VSR - SMESH_Gen::Load - can't get servant" );
5378 // close algorithms root HDF group
5379 aTopGroup->CloseOnDisk();
5383 // --> the rest groups should be meshes
5384 for ( int i = 0; i < aNbGroups; i++ ) {
5385 // identify next group
5386 char meshName[ HDF_NAME_MAX_LEN+1 ];
5387 aFile->InternalObjectIndentify( i, meshName );
5389 if ( string( meshName ).substr( 0, 4 ) == string( "Mesh" ) ) {
5391 int id = atoi( string( meshName ).substr( 4 ).c_str() );
5395 // open mesh HDF group
5396 aTopGroup = new HDFgroup( meshName, aFile );
5397 aTopGroup->OpenOnDisk();
5399 // get number of child HDF objects
5400 int aNbObjects = aTopGroup->nInternalObjects();
5401 if ( aNbObjects > 0 ) {
5403 if(MYDEBUG) MESSAGE( "VSR - load mesh : id = " << id );
5404 SMESH::SMESH_Mesh_var myNewMesh = this->createMesh();
5405 SMESH_Mesh_i* myNewMeshImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( myNewMesh ).in() );
5406 if ( !myNewMeshImpl )
5408 meshGroupList.push_back( make_pair( myNewMeshImpl, aTopGroup ));
5410 CORBA::String_var iorString = GetORB()->object_to_string( myNewMesh );
5411 int newId = myStudyContext->findId( iorString.in() );
5412 myStudyContext->mapOldToNew( id, newId );
5415 // try to read and set auto color flag
5416 char aMeshAutoColorName[ 30 ];
5417 sprintf( aMeshAutoColorName, "AutoColorMesh %d", id);
5418 if( aTopGroup->ExistInternalObject( aMeshAutoColorName ) )
5420 aDataset = new HDFdataset( aMeshAutoColorName, aTopGroup );
5421 aDataset->OpenOnDisk();
5422 size = aDataset->GetSize();
5423 int* anAutoColor = new int[ size ];
5424 aDataset->ReadFromDisk( anAutoColor );
5425 aDataset->CloseOnDisk();
5426 myNewMeshImpl->GetImpl().SetAutoColor( (bool)anAutoColor[0] );
5427 delete [] anAutoColor;
5430 // try to read and set reference to shape
5431 GEOM::GEOM_Object_var aShapeObject;
5432 if ( aTopGroup->ExistInternalObject( "Ref on shape" ) ) {
5433 // load mesh "Ref on shape" - it's an entry to SObject
5434 aDataset = new HDFdataset( "Ref on shape", aTopGroup );
5435 aDataset->OpenOnDisk();
5436 size = aDataset->GetSize();
5437 char* refFromFile = new char[ size ];
5438 aDataset->ReadFromDisk( refFromFile );
5439 aDataset->CloseOnDisk();
5440 if ( strlen( refFromFile ) > 0 ) {
5441 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5442 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5443 if ( !CORBA::is_nil( shapeObject ) ) {
5444 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5445 if ( !aShapeObject->_is_nil() )
5446 myNewMeshImpl->SetShape( aShapeObject );
5449 delete [] refFromFile;
5452 // issue 20918. Restore Persistent Id of SMESHDS_Mesh
5453 if ( aTopGroup->ExistInternalObject( "meshPersistentId" ) )
5455 aDataset = new HDFdataset( "meshPersistentId", aTopGroup );
5456 aDataset->OpenOnDisk();
5457 size = aDataset->GetSize();
5458 int* meshPersistentId = new int[ size ];
5459 aDataset->ReadFromDisk( meshPersistentId );
5460 aDataset->CloseOnDisk();
5461 myNewMeshImpl->GetImpl().GetMeshDS()->SetPersistentId( *meshPersistentId );
5462 delete [] meshPersistentId;
5465 // Restore SMESH_Mesh_i::_mainShapeTick
5466 if ( aTopGroup->ExistInternalObject( "shapeTick" ))
5468 aDataset = new HDFdataset( "shapeTick", aTopGroup );
5469 aDataset->OpenOnDisk();
5470 int* shapeTick = & myNewMeshImpl->MainShapeTick();
5471 aDataset->ReadFromDisk( shapeTick );
5472 aDataset->CloseOnDisk();
5475 // Restore file info
5476 if ( aTopGroup->ExistInternalObject( "file info" ))
5478 aDataset = new HDFdataset( "file info", aTopGroup );
5479 aDataset->OpenOnDisk();
5480 size = aDataset->GetSize();
5481 std::string info( size, ' ');
5482 aDataset->ReadFromDisk( (char*) info.data() );
5483 aDataset->CloseOnDisk();
5484 myNewMeshImpl->FileInfoFromString( info );
5490 // As all object that can be referred by hypothesis are created,
5491 // we can restore hypothesis data
5493 list< pair< SMESH_Hypothesis_i*, string > >::iterator hyp_data;
5494 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5496 SMESH_Hypothesis_i* hyp = hyp_data->first;
5497 string & data = hyp_data->second;
5498 hyp->LoadFrom( data.c_str() );
5501 // Restore the rest mesh data
5503 list< pair< SMESH_Mesh_i*, HDFgroup* > >::iterator meshi_group;
5504 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5506 aTopGroup = meshi_group->second;
5507 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5508 //::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5509 //SMESHDS_Mesh* mySMESHDSMesh = myLocMesh.GetMeshDS();
5511 GEOM::GEOM_Object_var aShapeObject = myNewMeshImpl->GetShapeToMesh();
5512 bool hasData = false;
5515 CORBA::String_var iorString = GetORB()->object_to_string( myNewMeshImpl->_this() );
5516 int newId = myStudyContext->findId( iorString.in() );
5517 int meshOldId = myStudyContext->getOldId( newId );
5519 // try to find mesh data dataset
5520 if ( aTopGroup->ExistInternalObject( "Has data" ) ) {
5521 // load mesh "has data" flag
5522 aDataset = new HDFdataset( "Has data", aTopGroup );
5523 aDataset->OpenOnDisk();
5524 size = aDataset->GetSize();
5525 char* strHasData = new char[ size ];
5526 aDataset->ReadFromDisk( strHasData );
5527 aDataset->CloseOnDisk();
5528 if ( strcmp( strHasData, "1") == 0 ) {
5531 delete [] strHasData;
5534 // Try to get applied ALGORITHMS (mesh is not cleared by algo addition because
5535 // nodes and elements are not yet put into sub-meshes)
5536 if ( aTopGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5537 aGroup = new HDFgroup( "Applied Algorithms", aTopGroup );
5538 aGroup->OpenOnDisk();
5539 // get number of applied algorithms
5540 int aNbSubObjects = aGroup->nInternalObjects();
5541 if(MYDEBUG) MESSAGE( "VSR - number of applied algos " << aNbSubObjects );
5542 for ( int j = 0; j < aNbSubObjects; j++ ) {
5543 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5544 aGroup->InternalObjectIndentify( j, name_dataset );
5545 // check if it is an algorithm
5546 if ( string( name_dataset ).substr( 0, 4 ) == string( "Algo" ) ) {
5547 aDataset = new HDFdataset( name_dataset, aGroup );
5548 aDataset->OpenOnDisk();
5549 size = aDataset->GetSize();
5550 char* refFromFile = new char[ size ];
5551 aDataset->ReadFromDisk( refFromFile );
5552 aDataset->CloseOnDisk();
5553 // san - it is impossible to recover applied algorithms using their entries within Load() method
5554 //SALOMEDS::SObject_wrap hypSO = aStudy->FindObjectID( refFromFile );
5555 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5556 int id = atoi( refFromFile );
5557 delete [] refFromFile;
5558 string anIOR = myStudyContext->getIORbyOldId( id );
5559 if ( !anIOR.empty() ) {
5560 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5561 if ( !CORBA::is_nil( hypObject ) ) {
5562 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5563 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5564 || !myNewMeshImpl->HasShapeToMesh()) )
5565 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5570 aGroup->CloseOnDisk();
5573 // try to get applied hypotheses
5574 if ( aTopGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5575 aGroup = new HDFgroup( "Applied Hypotheses", aTopGroup );
5576 aGroup->OpenOnDisk();
5577 // get number of applied hypotheses
5578 int aNbSubObjects = aGroup->nInternalObjects();
5579 for ( int j = 0; j < aNbSubObjects; j++ ) {
5580 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5581 aGroup->InternalObjectIndentify( j, name_dataset );
5582 // check if it is a hypothesis
5583 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5584 aDataset = new HDFdataset( name_dataset, aGroup );
5585 aDataset->OpenOnDisk();
5586 size = aDataset->GetSize();
5587 char* refFromFile = new char[ size ];
5588 aDataset->ReadFromDisk( refFromFile );
5589 aDataset->CloseOnDisk();
5590 // san - it is impossible to recover applied hypotheses using their entries within Load() method
5591 //SALOMEDS::SObject_wrap hypSO = myStudy->FindObjectID( refFromFile );
5592 //CORBA::Object_var hypObject = SObjectToObject( hypSO );
5593 int id = atoi( refFromFile );
5594 delete [] refFromFile;
5595 string anIOR = myStudyContext->getIORbyOldId( id );
5596 if ( !anIOR.empty() ) {
5597 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5598 if ( !CORBA::is_nil( hypObject ) ) {
5599 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5600 if ( !anHyp->_is_nil() && (!aShapeObject->_is_nil()
5601 || !myNewMeshImpl->HasShapeToMesh()) )
5602 myNewMeshImpl->addHypothesis( aShapeObject, anHyp );
5607 aGroup->CloseOnDisk();
5610 // --> try to find SUB-MESHES containers for each type of submesh
5611 for ( int j = GetSubMeshOnVertexTag(); j <= GetSubMeshOnCompoundTag(); j++ ) {
5612 const char* name_meshgroup = 0;
5613 if ( j == GetSubMeshOnVertexTag() )
5614 name_meshgroup = "SubMeshes On Vertex";
5615 else if ( j == GetSubMeshOnEdgeTag() )
5616 name_meshgroup = "SubMeshes On Edge";
5617 else if ( j == GetSubMeshOnWireTag() )
5618 name_meshgroup = "SubMeshes On Wire";
5619 else if ( j == GetSubMeshOnFaceTag() )
5620 name_meshgroup = "SubMeshes On Face";
5621 else if ( j == GetSubMeshOnShellTag() )
5622 name_meshgroup = "SubMeshes On Shell";
5623 else if ( j == GetSubMeshOnSolidTag() )
5624 name_meshgroup = "SubMeshes On Solid";
5625 else if ( j == GetSubMeshOnCompoundTag() )
5626 name_meshgroup = "SubMeshes On Compound";
5628 // try to get submeshes container HDF group
5629 if ( aTopGroup->ExistInternalObject( name_meshgroup ) ) {
5630 // open submeshes containers HDF group
5631 aGroup = new HDFgroup( name_meshgroup, aTopGroup );
5632 aGroup->OpenOnDisk();
5634 // get number of submeshes
5635 int aNbSubMeshes = aGroup->nInternalObjects();
5636 for ( int k = 0; k < aNbSubMeshes; k++ ) {
5638 char name_submeshgroup[ HDF_NAME_MAX_LEN+1 ];
5639 aGroup->InternalObjectIndentify( k, name_submeshgroup );
5640 if ( strncmp( name_submeshgroup, "SubMesh", 7 ) == 0 ) {
5641 // --> get submesh id
5642 int subid = atoi( name_submeshgroup + 7 );
5645 // open submesh HDF group
5646 aSubGroup = new HDFgroup( name_submeshgroup, aGroup );
5647 aSubGroup->OpenOnDisk();
5649 // try to read and set reference to subshape
5650 GEOM::GEOM_Object_var aSubShapeObject;
5651 SMESH::SMESH_subMesh_var aSubMesh;
5653 if ( aSubGroup->ExistInternalObject( "Ref on shape" ) ) {
5654 // load submesh "Ref on shape" - it's an entry to SObject
5655 aDataset = new HDFdataset( "Ref on shape", aSubGroup );
5656 aDataset->OpenOnDisk();
5657 size = aDataset->GetSize();
5658 char* refFromFile = new char[ size ];
5659 aDataset->ReadFromDisk( refFromFile );
5660 aDataset->CloseOnDisk();
5661 if ( strlen( refFromFile ) > 0 ) {
5662 SALOMEDS::SObject_wrap subShapeSO = aStudy->FindObjectID( refFromFile );
5663 CORBA::Object_var subShapeObject = SObjectToObject( subShapeSO );
5664 if ( !CORBA::is_nil( subShapeObject ) ) {
5665 aSubShapeObject = GEOM::GEOM_Object::_narrow( subShapeObject );
5666 if ( !aSubShapeObject->_is_nil() )
5667 aSubMesh = SMESH::SMESH_subMesh::_duplicate
5668 ( myNewMeshImpl->createSubMesh( aSubShapeObject ) );
5669 if ( aSubMesh->_is_nil() )
5671 string iorSubString = GetORB()->object_to_string( aSubMesh );
5672 int newSubId = myStudyContext->findId( iorSubString );
5673 myStudyContext->mapOldToNew( subid, newSubId );
5676 delete [] refFromFile;
5679 if ( aSubMesh->_is_nil() )
5682 // try to get applied algorithms
5683 if ( aSubGroup->ExistInternalObject( "Applied Algorithms" ) ) {
5684 // open "applied algorithms" HDF group
5685 aSubSubGroup = new HDFgroup( "Applied Algorithms", aSubGroup );
5686 aSubSubGroup->OpenOnDisk();
5687 // get number of applied algorithms
5688 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5689 for ( int l = 0; l < aNbSubObjects; l++ ) {
5690 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5691 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5692 // check if it is an algorithm
5693 if ( strncmp( name_dataset, "Algo", 4 ) == 0 ) {
5694 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5695 aDataset->OpenOnDisk();
5696 size = aDataset->GetSize();
5697 char* refFromFile = new char[ size ];
5698 aDataset->ReadFromDisk( refFromFile );
5699 aDataset->CloseOnDisk();
5701 int id = atoi( refFromFile );
5702 string anIOR = myStudyContext->getIORbyOldId( id );
5703 if ( !anIOR.empty() ) {
5704 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5705 if ( !CORBA::is_nil( hypObject ) ) {
5706 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5707 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5708 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5711 delete [] refFromFile;
5714 // close "applied algorithms" HDF group
5715 aSubSubGroup->CloseOnDisk();
5718 // try to get applied hypotheses
5719 if ( aSubGroup->ExistInternalObject( "Applied Hypotheses" ) ) {
5720 // open "applied hypotheses" HDF group
5721 aSubSubGroup = new HDFgroup( "Applied Hypotheses", aSubGroup );
5722 aSubSubGroup->OpenOnDisk();
5723 // get number of applied hypotheses
5724 int aNbSubObjects = aSubSubGroup->nInternalObjects();
5725 for ( int l = 0; l < aNbSubObjects; l++ ) {
5726 char name_dataset[ HDF_NAME_MAX_LEN+1 ];
5727 aSubSubGroup->InternalObjectIndentify( l, name_dataset );
5728 // check if it is a hypothesis
5729 if ( string( name_dataset ).substr( 0, 3 ) == string( "Hyp" ) ) {
5730 aDataset = new HDFdataset( name_dataset, aSubSubGroup );
5731 aDataset->OpenOnDisk();
5732 size = aDataset->GetSize();
5733 char* refFromFile = new char[ size ];
5734 aDataset->ReadFromDisk( refFromFile );
5735 aDataset->CloseOnDisk();
5737 int id = atoi( refFromFile );
5738 string anIOR = myStudyContext->getIORbyOldId( id );
5739 if ( !anIOR.empty() ) {
5740 CORBA::Object_var hypObject = GetORB()->string_to_object( anIOR.c_str() );
5741 if ( !CORBA::is_nil( hypObject ) ) {
5742 SMESH::SMESH_Hypothesis_var anHyp = SMESH::SMESH_Hypothesis::_narrow( hypObject );
5743 if ( !anHyp->_is_nil() && !aShapeObject->_is_nil() )
5744 myNewMeshImpl->addHypothesis( aSubShapeObject, anHyp );
5747 delete [] refFromFile;
5750 // close "APPLIED HYPOTHESES" hdf group
5751 aSubSubGroup->CloseOnDisk();
5754 // close SUB-MESH hdf group
5755 aSubGroup->CloseOnDisk();
5758 // close SUB-MESHES containers hdf group
5759 aGroup->CloseOnDisk();
5763 // try to get GROUPS
5764 for ( int ii = GetNodeGroupsTag(); ii <= GetBallElementsGroupsTag(); ii++ ) {
5765 char name_group[ 30 ];
5766 if ( ii == GetNodeGroupsTag() )
5767 strcpy( name_group, "Groups of Nodes" );
5768 else if ( ii == GetEdgeGroupsTag() )
5769 strcpy( name_group, "Groups of Edges" );
5770 else if ( ii == GetFaceGroupsTag() )
5771 strcpy( name_group, "Groups of Faces" );
5772 else if ( ii == GetVolumeGroupsTag() )
5773 strcpy( name_group, "Groups of Volumes" );
5774 else if ( ii == Get0DElementsGroupsTag() )
5775 strcpy( name_group, "Groups of 0D Elements" );
5776 else if ( ii == GetBallElementsGroupsTag() )
5777 strcpy( name_group, "Groups of Balls" );
5779 if ( aTopGroup->ExistInternalObject( name_group ) ) {
5780 aGroup = new HDFgroup( name_group, aTopGroup );
5781 aGroup->OpenOnDisk();
5782 // PAL23514: get all names from the HDFgroup to avoid iteration on its contents
5783 // within aGroup->ExistInternalObject( name )
5784 std::vector< std::string > subNames;
5785 TColStd_MapOfAsciiString mapOfNames;
5786 aGroup->GetAllObjects( subNames );
5787 for ( size_t iN = 0; iN < subNames.size(); ++iN )
5788 mapOfNames.Add( subNames[ iN ].c_str() );
5790 for ( size_t j = 0; j < subNames.size(); j++ ) {
5791 const std::string& name_dataset = subNames[ j ];
5792 // check if it is a group
5793 if ( name_dataset.substr( 0, 5 ) == "Group" ) {
5796 int subid = strtol( name_dataset.data() + 5, &endptr, 10 );
5799 int groupID = -1; // group local ID (also persistent)
5801 groupID = atoi( endptr + 1 );
5802 aDataset = new HDFdataset( name_dataset.c_str(), aGroup );
5803 aDataset->OpenOnDisk();
5805 // Retrieve actual group name
5806 size = aDataset->GetSize();
5807 char* nameFromFile = new char[ size ];
5808 aDataset->ReadFromDisk( nameFromFile );
5809 aDataset->CloseOnDisk();
5811 // Try to find a shape reference
5812 TopoDS_Shape aShape;
5813 char aRefName[ 30 ];
5814 sprintf( aRefName, "Ref on shape %d", subid);
5815 if ( mapOfNames.Contains( aRefName ))
5817 // load mesh "Ref on shape" - it's an entry to SObject
5818 aDataset = new HDFdataset( aRefName, aGroup );
5819 aDataset->OpenOnDisk();
5820 size = aDataset->GetSize();
5821 char* refFromFile = new char[ size ];
5822 aDataset->ReadFromDisk( refFromFile );
5823 aDataset->CloseOnDisk();
5824 if ( strlen( refFromFile ) > 0 ) {
5825 SALOMEDS::SObject_wrap shapeSO = aStudy->FindObjectID( refFromFile );
5826 CORBA::Object_var shapeObject = SObjectToObject( shapeSO );
5827 if ( !CORBA::is_nil( shapeObject ) ) {
5828 aShapeObject = GEOM::GEOM_Object::_narrow( shapeObject );
5829 if ( !aShapeObject->_is_nil() )
5830 aShape = GeomObjectToShape( aShapeObject );
5833 delete [] refFromFile;
5835 // Try to read a filter of SMESH_GroupOnFilter
5836 SMESH::Filter_var filter;
5837 SMESH_PredicatePtr predicate;
5838 std::string hdfGrpName = ( SMESH_Comment( "Filter ") << subid );
5839 if ( mapOfNames.Contains( hdfGrpName.c_str() ))
5841 aDataset = new HDFdataset( hdfGrpName.c_str(), aGroup );
5842 aDataset->OpenOnDisk();
5843 size = aDataset->GetSize();
5844 char* persistStr = new char[ size ];
5845 aDataset->ReadFromDisk( persistStr );
5846 aDataset->CloseOnDisk();
5847 if ( strlen( persistStr ) > 0 ) {
5848 filter = SMESH_GroupOnFilter_i::StringToFilter( persistStr );
5849 predicate = SMESH_GroupOnFilter_i::GetPredicate( filter );
5850 filters.push_back( filter );
5852 delete [] persistStr;
5855 // Create group servant
5856 SMESH::ElementType type = (SMESH::ElementType)(ii - GetNodeGroupsTag() + 1);
5857 SMESH::SMESH_GroupBase_var aNewGroup = SMESH::SMESH_GroupBase::_duplicate
5858 ( myNewMeshImpl->createGroup( type, nameFromFile, groupID, aShape, predicate ) );
5859 delete [] nameFromFile;
5860 // Obtain a SMESHDS_Group object
5861 if ( aNewGroup->_is_nil() )
5864 string iorSubString = GetORB()->object_to_string( aNewGroup );
5865 int newSubId = myStudyContext->findId( iorSubString );
5866 myStudyContext->mapOldToNew( subid, newSubId );
5868 SMESH_GroupBase_i* aGroupImpl = SMESH::DownCast< SMESH_GroupBase_i*>( aNewGroup );
5872 if ( SMESH_GroupOnFilter_i* aFilterGroup =
5873 dynamic_cast< SMESH_GroupOnFilter_i*>( aGroupImpl ))
5875 aFilterGroup->SetFilter( filter );
5876 filter->UnRegister();
5878 SMESHDS_GroupBase* aGroupBaseDS = aGroupImpl->GetGroupDS();
5879 if ( !aGroupBaseDS )
5882 aGroupBaseDS->SetStoreName( name_dataset.c_str() );
5885 // Read color of the group
5886 char aGroupColorName[ 30 ];
5887 sprintf( aGroupColorName, "ColorGroup %d", subid);
5888 if ( mapOfNames.Contains( aGroupColorName ))
5890 aDataset = new HDFdataset( aGroupColorName, aGroup );
5891 aDataset->OpenOnDisk();
5892 size = aDataset->GetSize();
5893 double* anRGB = new double[ size ];
5894 aDataset->ReadFromDisk( anRGB );
5895 aDataset->CloseOnDisk();
5896 Quantity_Color aColor( anRGB[0], anRGB[1], anRGB[2], Quantity_TOC_RGB );
5897 aGroupBaseDS->SetColor( aColor );
5902 aGroup->CloseOnDisk();
5906 // instead of reading mesh data, we read only brief information of all
5907 // objects: mesh, groups, sub-meshes (issue 0021208)
5910 SMESH_PreMeshInfo::LoadFromFile( myNewMeshImpl, meshOldId,
5911 meshfile.ToCString(), filename.ToCString(),
5915 // read Sub-Mesh ORDER if any
5916 if ( aTopGroup->ExistInternalObject( "Mesh Order" )) {
5917 aDataset = new HDFdataset( "Mesh Order", aTopGroup );
5918 aDataset->OpenOnDisk();
5919 size = aDataset->GetSize();
5920 int* smIDs = new int[ size ];
5921 aDataset->ReadFromDisk( smIDs );
5922 aDataset->CloseOnDisk();
5923 TListOfListOfInt anOrderIds;
5924 anOrderIds.push_back( TListOfInt() );
5925 for ( int i = 0; i < size; i++ )
5926 if ( smIDs[ i ] < 0 ) // is separator
5927 anOrderIds.push_back( TListOfInt() );
5929 anOrderIds.back().push_back(smIDs[ i ]);
5931 myNewMeshImpl->GetImpl().SetMeshOrder( anOrderIds );
5936 // update hyps needing full mesh data restored (issue 20918)
5937 for ( hyp_data = hypDataList.begin(); hyp_data != hypDataList.end(); ++hyp_data )
5939 SMESH_Hypothesis_i* hyp = hyp_data->first;
5940 hyp->UpdateAsMeshesRestored();
5943 // notify algos on completed restoration to set sub-mesh event listeners
5944 for ( meshi_group = meshGroupList.begin(); meshi_group != meshGroupList.end(); ++meshi_group )
5946 SMESH_Mesh_i* myNewMeshImpl = meshi_group->first;
5947 ::SMESH_Mesh& myLocMesh = myNewMeshImpl->GetImpl();
5949 TopoDS_Shape myLocShape;
5950 if(myLocMesh.HasShapeToMesh())
5951 myLocShape = myLocMesh.GetShapeToMesh();
5953 myLocShape = SMESH_Mesh::PseudoShape();
5955 myLocMesh.GetSubMesh(myLocShape)->
5956 ComputeStateEngine (SMESH_subMesh::SUBMESH_RESTORED);
5959 // let filters detect dependency on mesh groups via FT_BelongToMeshGroup predicate (22877)
5960 list< SMESH::Filter_var >::iterator f = filters.begin();
5961 for ( ; f != filters.end(); ++f )
5962 if ( SMESH::Filter_i * fi = SMESH::DownCast< SMESH::Filter_i*>( *f ))
5963 fi->FindBaseObjects();
5968 aTopGroup->CloseOnDisk();
5971 aFile->CloseOnDisk();
5974 // Remove temporary files created from the stream
5977 SMESH_File meshFile( meshfile.ToCString() );
5978 if ( !meshFile ) // no meshfile exists
5980 SALOMEDS_Tool::RemoveTemporaryFiles( tmpDir.ToCString(), aFileSeq, true );
5984 Engines::Container_var container = GetContainerRef();
5985 if ( Engines_Container_i* container_i = SMESH::DownCast<Engines_Container_i*>( container ))
5987 container_i->registerTemporaryFile( filename.ToCString() );
5988 container_i->registerTemporaryFile( meshfile.ToCString() );
5989 container_i->registerTemporaryFile( tmpDir.ToCString() );
5993 pd << ""; // prevent optimizing pd out
5995 // creation of tree nodes for all data objects in the study
5996 // to support tree representation customization and drag-n-drop:
5997 SALOMEDS::UseCaseBuilder_wrap useCaseBuilder = aStudy->GetUseCaseBuilder();
5998 if ( !useCaseBuilder->IsUseCaseNode( theComponent ) ) {
5999 useCaseBuilder->SetRootCurrent();
6000 useCaseBuilder->Append( theComponent ); // component object is added as the top level item
6001 SALOMEDS::ChildIterator_wrap it = aStudy->NewChildIterator( theComponent );
6002 for (it->InitEx(true); it->More(); it->Next()) {
6003 useCaseBuilder->AppendTo( it->Value()->GetFather(), it->Value() );
6010 //=============================================================================
6012 * SMESH_Gen_i::LoadASCII
6014 * Load SMESH module's data in ASCII format
6016 //=============================================================================
6018 bool SMESH_Gen_i::LoadASCII( SALOMEDS::SComponent_ptr theComponent,
6019 const SALOMEDS::TMPFile& theStream,
6021 bool isMultiFile ) {
6022 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LoadASCII" );
6023 return Load( theComponent, theStream, theURL, isMultiFile );
6025 //before call main ::Load method it's need for decipher text format to
6026 //binary ( "|xx" => x' )
6027 int size = theStream.length();
6028 if ( int((size / 3 )*3) != size ) //error size of buffer
6031 int real_size = int(size / 3);
6033 _CORBA_Octet* buffer = new _CORBA_Octet[real_size];
6036 unsigned int c = -1;
6037 for ( int i = 0; i < real_size; i++ )
6039 memcpy( &(tmp[0]), &(theStream[i*3+1]), 2 );
6040 sscanf( tmp, "%x", &c );
6041 sprintf( (char*)&(buffer[i]), "%c", (char)c );
6044 SALOMEDS::TMPFile_var aRealStreamFile = new SALOMEDS::TMPFile(real_size, real_size, buffer, 1);
6046 return Load( theComponent, *(aRealStreamFile._retn()), theURL, isMultiFile );
6049 //=============================================================================
6051 * SMESH_Gen_i::Close
6053 * Clears study-connected data when it is closed
6055 //=============================================================================
6057 void SMESH_Gen_i::Close( SALOMEDS::SComponent_ptr theComponent )
6059 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::Close" );
6061 // Clear study contexts data
6062 myStudyContext->Clear();
6064 // remove the tmp files meshes are loaded from
6065 SMESH_PreMeshInfo::RemoveStudyFiles_TMP_METHOD( theComponent );
6067 // Clean trace of API methods calls
6073 //=============================================================================
6075 * SMESH_Gen_i::ComponentDataType
6077 * Get component data type
6079 //=============================================================================
6081 char* SMESH_Gen_i::ComponentDataType()
6083 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::ComponentDataType" );
6084 return CORBA::string_dup( "SMESH" );
6088 //=============================================================================
6090 * SMESH_Gen_i::IORToLocalPersistentID
6092 * Transform data from transient form to persistent
6094 //=============================================================================
6096 char* SMESH_Gen_i::IORToLocalPersistentID( SALOMEDS::SObject_ptr /*theSObject*/,
6097 const char* IORString,
6098 CORBA::Boolean /*isMultiFile*/,
6099 CORBA::Boolean /*isASCII*/ )
6101 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::IORToLocalPersistentID" );
6103 if ( myStudyContext && strcmp( IORString, "" ) != 0 ) {
6104 int anId = myStudyContext->findId( IORString );
6106 if(MYDEBUG) MESSAGE( "VSR " << anId )
6108 sprintf( strId, "%d", anId );
6109 return CORBA::string_dup( strId );
6112 return CORBA::string_dup( "" );
6115 //=============================================================================
6117 * SMESH_Gen_i::LocalPersistentIDToIOR
6119 * Transform data from persistent form to transient
6121 //=============================================================================
6123 char* SMESH_Gen_i::LocalPersistentIDToIOR( SALOMEDS::SObject_ptr /*theSObject*/,
6124 const char* aLocalPersistentID,
6125 CORBA::Boolean /*isMultiFile*/,
6126 CORBA::Boolean /*isASCII*/ )
6128 if(MYDEBUG) MESSAGE( "SMESH_Gen_i::LocalPersistentIDToIOR(): id = " << aLocalPersistentID );
6130 if ( myStudyContext && strcmp( aLocalPersistentID, "" ) != 0 ) {
6131 int anId = atoi( aLocalPersistentID );
6132 return CORBA::string_dup( myStudyContext->getIORbyOldId( anId ).c_str() );
6134 return CORBA::string_dup( "" );
6137 //=======================================================================
6138 //function : RegisterObject
6140 //=======================================================================
6142 int SMESH_Gen_i::RegisterObject(CORBA::Object_ptr theObject)
6144 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6145 CORBA::String_var iorString = GetORB()->object_to_string( theObject );
6146 return myStudyContext->addObject( string( iorString.in() ) );
6151 //================================================================================
6153 * \brief Return id of registered object
6154 * \param theObject - the Object
6155 * \retval int - Object id
6157 //================================================================================
6159 CORBA::Long SMESH_Gen_i::GetObjectId(CORBA::Object_ptr theObject)
6161 if ( myStudyContext && !CORBA::is_nil( theObject )) {
6162 string iorString = GetORB()->object_to_string( theObject );
6163 return myStudyContext->findId( iorString );
6168 //=============================================================================
6170 * SMESH_Gen_i::SetName
6172 * Set a new object name
6174 //=============================================================================
6175 void SMESH_Gen_i::SetName(const char* theIOR,
6176 const char* theName)
6178 if ( theIOR && strcmp( theIOR, "" ) ) {
6179 CORBA::Object_var anObject = GetORB()->string_to_object( theIOR );
6180 SALOMEDS::SObject_wrap aSO = ObjectToSObject( anObject );
6181 if ( !aSO->_is_nil() ) {
6182 SetName( aSO, theName );
6187 // Version information
6188 char* SMESH_Gen_i::getVersion()
6190 #if SMESH_DEVELOPMENT
6191 return CORBA::string_dup(SMESH_VERSION_STR"dev");
6193 return CORBA::string_dup(SMESH_VERSION_STR);
6197 //=================================================================================
6198 // function : Move()
6199 // purpose : Moves objects to the specified position.
6200 // Is used in the drag-n-drop functionality.
6201 //=================================================================================
6202 void SMESH_Gen_i::Move( const SMESH::sobject_list& what,
6203 SALOMEDS::SObject_ptr where,
6206 if ( CORBA::is_nil( where ) ) return;
6208 SALOMEDS::StudyBuilder_var studyBuilder = getStudyServant()->NewBuilder();
6209 SALOMEDS::UseCaseBuilder_var useCaseBuilder = getStudyServant()->GetUseCaseBuilder();
6210 SALOMEDS::SComponent_var father = where->GetFatherComponent();
6211 std::string dataType = father->ComponentDataType();
6212 if ( dataType != "SMESH" ) return; // not a SMESH component
6214 SALOMEDS::SObject_var objAfter;
6215 if ( row >= 0 && useCaseBuilder->HasChildren( where ) ) {
6216 // insert at given row -> find insertion position
6217 SALOMEDS::UseCaseIterator_var useCaseIt = useCaseBuilder->GetUseCaseIterator( where );
6219 for ( i = 0; i < row && useCaseIt->More(); i++, useCaseIt->Next() );
6220 if ( i == row && useCaseIt->More() ) {
6221 objAfter = useCaseIt->Value();
6225 for ( CORBA::ULong i = 0; i < what.length(); i++ ) {
6226 SALOMEDS::SObject_var sobj = what[i];
6227 if ( CORBA::is_nil( sobj ) ) continue; // skip bad object
6228 // insert the object to the use case tree
6229 if ( !CORBA::is_nil( objAfter ) )
6230 useCaseBuilder->InsertBefore( sobj, objAfter ); // insert at given row
6232 useCaseBuilder->AppendTo( where, sobj ); // append to the end of list
6235 //================================================================================
6237 * \brief Returns true if algorithm can be used to mesh a given geometry
6238 * \param [in] theAlgoType - the algorithm type
6239 * \param [in] theLibName - a name of the Plug-in library implementing the algorithm
6240 * \param [in] theGeomObject - the geometry to mesh
6241 * \param [in] toCheckAll - if \c True, returns \c True if all shapes are meshable,
6242 * else, returns \c True if at least one shape is meshable
6243 * \return CORBA::Boolean - can or can't
6245 //================================================================================
6247 CORBA::Boolean SMESH_Gen_i::IsApplicable ( const char* theAlgoType,
6248 const char* theLibName,
6249 GEOM::GEOM_Object_ptr theGeomObject,
6250 CORBA::Boolean toCheckAll)
6254 std::string aPlatformLibName;
6255 typedef GenericHypothesisCreator_i* (*GetHypothesisCreator)(const char*);
6256 GenericHypothesisCreator_i* aCreator =
6257 getHypothesisCreator(theAlgoType, theLibName, aPlatformLibName);
6260 TopoDS_Shape shape = GeomObjectToShape( theGeomObject );
6261 const SMESH_Algo::Features& feat = SMESH_Algo::GetFeatures( theAlgoType );
6262 return shape.IsNull() || aCreator->IsApplicable( shape, toCheckAll, feat._dim );
6269 SMESH_CATCH( SMESH::doNothing );
6272 cout << "SMESH_Gen_i::IsApplicable(): exception in " << ( theAlgoType ? theAlgoType : "") << endl;
6277 //=================================================================================
6278 // function : GetInsideSphere
6279 // purpose : Collect indices of elements, which are located inside the sphere
6280 //=================================================================================
6281 SMESH::long_array* SMESH_Gen_i::GetInsideSphere( SMESH::SMESH_IDSource_ptr meshPart,
6282 SMESH::ElementType theElemType,
6288 SMESH::long_array_var aResult = new SMESH::long_array();
6289 if ( meshPart->_is_nil() )
6290 return aResult._retn();
6292 // 1. Create geometrical object
6293 gp_Pnt aP( theX, theY, theZ );
6294 TopoDS_Shape aShape = BRepPrimAPI_MakeSphere( aP, theR ).Shape();
6296 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6298 if ( lst.size() > 0 ) {
6299 aResult->length( lst.size() );
6300 for ( size_t i = 0; i < lst.size(); i++ ) {
6301 aResult[i] = lst[i];
6304 return aResult._retn();
6307 SMESH::long_array* SMESH_Gen_i::GetInsideBox( SMESH::SMESH_IDSource_ptr meshPart,
6308 SMESH::ElementType theElemType,
6309 CORBA::Double theX1,
6310 CORBA::Double theY1,
6311 CORBA::Double theZ1,
6312 CORBA::Double theX2,
6313 CORBA::Double theY2,
6314 CORBA::Double theZ2) {
6315 SMESH::long_array_var aResult = new SMESH::long_array();
6316 if( meshPart->_is_nil() )
6317 return aResult._retn();
6319 TopoDS_Shape aShape = BRepPrimAPI_MakeBox( gp_Pnt( theX1, theY1, theZ1 ), gp_Pnt( theX2, theY2, theZ2 ) ).Shape();
6321 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6323 if( lst.size() > 0 ) {
6324 aResult->length( lst.size() );
6325 for ( size_t i = 0; i < lst.size(); i++ ) {
6326 aResult[i] = lst[i];
6329 return aResult._retn();
6332 SMESH::long_array* SMESH_Gen_i::GetInsideCylinder( SMESH::SMESH_IDSource_ptr meshPart,
6333 SMESH::ElementType theElemType,
6337 CORBA::Double theDX,
6338 CORBA::Double theDY,
6339 CORBA::Double theDZ,
6341 CORBA::Double theR ){
6342 SMESH::long_array_var aResult = new SMESH::long_array();
6343 if( meshPart->_is_nil() )
6344 return aResult._retn();
6346 gp_Pnt aP( theX, theY, theZ );
6347 gp_Vec aV( theDX, theDY, theDZ );
6348 gp_Ax2 anAxes (aP, aV);
6350 TopoDS_Shape aShape = BRepPrimAPI_MakeCylinder(anAxes, theR, Abs(theH)).Shape();
6352 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape);
6354 if( lst.size() > 0 ) {
6355 aResult->length( lst.size() );
6356 for ( size_t i = 0; i < lst.size(); i++ ) {
6357 aResult[i] = lst[i];
6360 return aResult._retn();
6363 SMESH::long_array* SMESH_Gen_i::GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6364 SMESH::ElementType theElemType,
6365 GEOM::GEOM_Object_ptr theGeom,
6366 CORBA::Double theTolerance ) {
6367 SMESH::long_array_var aResult = new SMESH::long_array();
6368 if( meshPart->_is_nil() || theGeom->_is_nil() )
6369 return aResult._retn();
6371 TopoDS_Shape aShape = GeomObjectToShape( theGeom );
6373 std::vector<long> lst =_GetInside(meshPart, theElemType, aShape, &theTolerance);
6375 if( lst.size() > 0 ) {
6376 aResult->length( lst.size() );
6377 for ( size_t i = 0; i < lst.size(); i++ ) {
6378 aResult[i] = lst[i];
6381 return aResult._retn();
6386 std::vector<long> SMESH_Gen_i::_GetInside( SMESH::SMESH_IDSource_ptr meshPart,
6387 SMESH::ElementType theElemType,
6388 TopoDS_Shape& aShape,
6389 double* theTolerance) {
6391 std::vector<long> res;
6392 SMESH::SMESH_Mesh_var mesh = meshPart->GetMesh();
6394 if ( mesh->_is_nil() )
6397 SMESH_Mesh_i* anImpl = dynamic_cast<SMESH_Mesh_i*>( GetServant( mesh ).in() );
6401 const SMDS_Mesh* meshDS = anImpl->GetImpl().GetMeshDS();
6406 SMDSAbs_ElementType aType = SMDSAbs_ElementType(theElemType);
6407 SMESH::Controls::ElementsOnShape* anElementsOnShape = new SMESH::Controls::ElementsOnShape();
6408 anElementsOnShape->SetAllNodes( true );
6409 anElementsOnShape->SetMesh( meshDS );
6410 anElementsOnShape->SetShape( aShape, aType );
6413 anElementsOnShape->SetTolerance(*theTolerance);
6415 SMESH::SMESH_Mesh_var msource = SMESH::SMESH_Mesh::_narrow(meshPart);
6416 if ( !msource->_is_nil() ) { // Mesh case
6417 SMDS_ElemIteratorPtr elemIt = meshDS->elementsIterator( aType );
6419 while ( elemIt->more() ) {
6420 const SMDS_MeshElement* anElem = elemIt->next();
6421 long anId = anElem->GetID();
6422 if ( anElementsOnShape->IsSatisfy( anId ) )
6423 res.push_back( anId );
6427 SMESH::SMESH_Group_var gsource = SMESH::SMESH_Group::_narrow(meshPart);
6428 if ( !gsource->_is_nil() ) {
6429 if(theElemType == SMESH::NODE) {
6430 SMESH::long_array_var nodes = gsource->GetNodeIDs();
6431 for ( CORBA::ULong i = 0; i < nodes->length(); ++i ) {
6432 if ( const SMDS_MeshNode* node = meshDS->FindNode( nodes[i] )) {
6433 long anId = node->GetID();
6434 if ( anElementsOnShape->IsSatisfy( anId ) )
6435 res.push_back( anId );
6438 } else if (gsource->GetType() == theElemType || theElemType == SMESH::ALL ) {
6439 SMESH::long_array_var elems = gsource->GetListOfID();
6440 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6441 if ( const SMDS_MeshElement* elem = meshDS->FindElement( elems[i] )) {
6442 long anId = elem->GetID();
6443 if ( anElementsOnShape->IsSatisfy( anId ) )
6444 res.push_back( anId );
6449 SMESH::SMESH_subMesh_var smsource = SMESH::SMESH_subMesh::_narrow(meshPart);
6450 if ( !smsource->_is_nil() ) {
6451 SMESH::long_array_var elems = smsource->GetElementsByType( theElemType );
6452 for ( CORBA::ULong i = 0; i < elems->length(); ++i ) {
6453 const SMDS_MeshElement* elem = ( theElemType == SMESH::NODE ) ? meshDS->FindNode( elems[i] ) : meshDS->FindElement( elems[i] );
6455 long anId = elem->GetID();
6456 if ( anElementsOnShape->IsSatisfy( anId ) )
6457 res.push_back( anId );
6465 //=============================================================================
6467 * SMESHEngine_factory
6469 * C factory, accessible with dlsym, after dlopen
6471 //=============================================================================
6475 PortableServer::ObjectId* SMESHEngine_factory( CORBA::ORB_ptr orb,
6476 PortableServer::POA_ptr poa,
6477 PortableServer::ObjectId* contId,
6478 const char* instanceName,
6479 const char* interfaceName )
6481 if(MYDEBUG) MESSAGE( "PortableServer::ObjectId* SMESHEngine_factory()" );
6482 if(MYDEBUG) SCRUTE(interfaceName);
6483 SMESH_Gen_i* aSMESHGen = new SMESH_Gen_i(orb, poa, contId, instanceName, interfaceName);
6484 return aSMESHGen->getId() ;