From 5b130b79009fb8c054f777569fbc7c609f92e266 Mon Sep 17 00:00:00 2001 From: bruneton Date: Wed, 4 Sep 2013 07:28:39 +0000 Subject: [PATCH 01/16] Minor: replacing annoying tabulations with whitespaces ... --- CMakeLists.txt | 7 +- src/Plugins/MedReader/IO/vtkMedDriver.cxx | 2 +- .../IO/vtkMedFamilyOnEntityOnProfile.cxx | 2 +- src/Plugins/MedReader/IO/vtkMedReader.cxx | 6 +- .../NavigationMode/pqSetModeStarter.cxx | 68 ++-- .../VTKMEDCouplingMultiFieldsClient.cxx | 290 ++++++++-------- .../ParaMEDCorba/vtkParaMEDCorbaSource.cxx | 222 ++++++------ .../ParaMEDCorba/vtkParaMEDCorbaSource.h | 6 +- ...qCustomChartDisplayPanelImplementation.cxx | 50 +-- .../pqCustomPlotSettingsModel.cxx | 190 +++++------ .../pqCustomXYChartDisplayPanel.cxx | 267 ++++++++------- .../ParaViewPlugin/pqTableReaderPanel.cxx | 40 +-- .../ParaViewPlugin/pqTableTo3DPanel.cxx | 36 +- .../TableReader/Reader/TableParser.cxx | 318 +++++++++--------- src/Plugins/TableReader/Reader/TableParser.h | 4 +- .../TableReader/Reader/vtkVisuTableReader.cxx | 212 ++++++------ .../TableTo3DFilter/vtkTableTo3D.cxx | 162 ++++----- .../TableTo3DFilter/vtkTableTo3D.h | 2 +- 18 files changed, 940 insertions(+), 944 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 34c9699b..906d2579 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -69,9 +69,6 @@ MARK_AS_ADVANCED(QT_HELP_GENERATOR) # Specific to ParaVis: FIND_PACKAGE(SalomeParaView) -IF(TARGET vtkTools) - message("bli !!") -endif() # GUI has to be loaded AFTER ParaView: the ParaView config doesn't mix # well with the VTK one (and GUI loads VTK): @@ -106,7 +103,7 @@ FIND_PACKAGE(SalomeMED REQUIRED) FIND_PACKAGE(SalomeMEDFile REQUIRED) # TODO: the below requires ParaView in the PYTHONPATH ... not so nice: -MESSAGE(STATUS "Generating wrapped class list (??) ...") +MESSAGE(STATUS "Generating list of wrapped VTK classes ...") LIST(GET PARAVIEW_INCLUDE_DIRS 0 PARAVIEW_INCLUDE_DIR0) EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/getwrapclasses.py ${PARAVIEW_INCLUDE_DIR0} RESULT_VARIABLE _res) @@ -153,7 +150,7 @@ INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/PARAVIS_version.h DESTINATION include/ OPTION(BUILD_TESTING "Build ParaVis Testing" ON) IF(BUILD_TESTING) SET(PARAVIS_TEST_DIR ${ParaVis_BINARY_DIR}/Test/Temporary) - MAKE_DIRECTORY(${PARAVIS_TEST_DIR}) + MAKE_DIRECTORY(${PARAVIS_TEST_DIR}) # TODO: replace with FILE(MAKE_DIRECTORY ...) ENABLE_TESTING() INCLUDE (CTest) ADD_SUBDIRECTORY(test) diff --git a/src/Plugins/MedReader/IO/vtkMedDriver.cxx b/src/Plugins/MedReader/IO/vtkMedDriver.cxx index 938f4f3c..432d836e 100644 --- a/src/Plugins/MedReader/IO/vtkMedDriver.cxx +++ b/src/Plugins/MedReader/IO/vtkMedDriver.cxx @@ -182,7 +182,7 @@ int vtkMedDriver::Open() #ifdef MedReader_HAVE_PARALLEL_INFRASTRUCTURE // the following code opens the file in parallel vtkMultiProcessController* controller = - vtkMultiProcessController::GetGlobalController(); + vtkMultiProcessController::GetGlobalController(); int lpID = 0; if (controller == NULL) { diff --git a/src/Plugins/MedReader/IO/vtkMedFamilyOnEntityOnProfile.cxx b/src/Plugins/MedReader/IO/vtkMedFamilyOnEntityOnProfile.cxx index 6e7db881..e528f2ce 100644 --- a/src/Plugins/MedReader/IO/vtkMedFamilyOnEntityOnProfile.cxx +++ b/src/Plugins/MedReader/IO/vtkMedFamilyOnEntityOnProfile.cxx @@ -102,7 +102,7 @@ int vtkMedFamilyOnEntityOnProfile::CanMapField(vtkMedFieldOnProfile* fop) int numProc = 1; vtkMultiProcessController* controller = - vtkMultiProcessController::GetGlobalController(); + vtkMultiProcessController::GetGlobalController(); if (controller != NULL) { numProc = controller->GetNumberOfProcesses(); diff --git a/src/Plugins/MedReader/IO/vtkMedReader.cxx b/src/Plugins/MedReader/IO/vtkMedReader.cxx index 1a52df2d..4e45660e 100644 --- a/src/Plugins/MedReader/IO/vtkMedReader.cxx +++ b/src/Plugins/MedReader/IO/vtkMedReader.cxx @@ -384,7 +384,7 @@ int vtkMedReader::RequestData(vtkInformation *request, else { vtkMultiProcessController* controller = - vtkMultiProcessController::GetGlobalController(); + vtkMultiProcessController::GetGlobalController(); if(controller) { this->Internal->NumberOfPieces=controller->GetNumberOfProcesses(); @@ -403,7 +403,7 @@ int vtkMedReader::RequestData(vtkInformation *request, { this->Internal->CurrentPieceNumber=0; vtkMultiProcessController* controller = - vtkMultiProcessController::GetGlobalController(); + vtkMultiProcessController::GetGlobalController(); if(controller) { this->Internal->CurrentPieceNumber= controller->GetLocalProcessId(); @@ -2317,7 +2317,7 @@ void vtkMedReader::SetVTKFieldOnSupport(vtkMedFieldOnProfile* fop, { if(vtkfield.DataArray->GetNumberOfTuples()!=ds->GetNumberOfPoints()) { - vtkDebugMacro("the data array " << vtkfield.DataArray->GetName() + vtkDebugMacro("the data array " << vtkfield.DataArray->GetName() << " do not have the good number of tuples"); return; } diff --git a/src/Plugins/NavigationMode/pqSetModeStarter.cxx b/src/Plugins/NavigationMode/pqSetModeStarter.cxx index 7f49003e..19649055 100644 --- a/src/Plugins/NavigationMode/pqSetModeStarter.cxx +++ b/src/Plugins/NavigationMode/pqSetModeStarter.cxx @@ -28,7 +28,7 @@ //----------------------------------------------------------------------------- pqSetModeStarter::pqSetModeStarter(QObject* p/*=0*/) - : QObject(p) +: QObject(p) { } @@ -57,49 +57,49 @@ void pqSetModeStarter::setStandardMode() // Copy default settings, make changes for Ctrl+MB and MB modes for(int i=0; i<9; i++) - { - manips[i] = default3DManips[i]; - - // Ctrl+MB - if (manips[i].Shift == 0 && manips[i].Control == 1) { - if (manips[i].Mouse == 1) - manips[i].Name = QByteArray("Zoom"); - else if (manips[i].Mouse == 2) - manips[i].Name = QByteArray("Pan"); - else if (manips[i].Mouse == 3) - manips[i].Name = QByteArray("Rotate"); - } - - // MB only - if (manips[i].Shift == 0 && manips[i].Control == 0) { - if (manips[i].Mouse == 1) - manips[i].Name = QByteArray("Rotate"); - else if (manips[i].Mouse == 2) - manips[i].Name = QByteArray("Pan"); - else if (manips[i].Mouse == 3) - manips[i].Name = QByteArray("Zoom"); - } + { + manips[i] = default3DManips[i]; + + // Ctrl+MB + if (manips[i].Shift == 0 && manips[i].Control == 1) { + if (manips[i].Mouse == 1) + manips[i].Name = QByteArray("Zoom"); + else if (manips[i].Mouse == 2) + manips[i].Name = QByteArray("Pan"); + else if (manips[i].Mouse == 3) + manips[i].Name = QByteArray("Rotate"); + } + + // MB only + if (manips[i].Shift == 0 && manips[i].Control == 0) { + if (manips[i].Mouse == 1) + manips[i].Name = QByteArray("Rotate"); + else if (manips[i].Mouse == 2) + manips[i].Name = QByteArray("Pan"); + else if (manips[i].Mouse == 3) + manips[i].Name = QByteArray("Zoom"); } + } // Save settings for(int i=0; i<9; i++) - { - strs << QString("Manipulator%1Mouse%2Shift%3Control%4Name%5") - .arg(i+1) - .arg(manips[i].Mouse) - .arg(manips[i].Shift) - .arg(manips[i].Control) - .arg(QString(manips[i].Name)); - } - + { + strs << QString("Manipulator%1Mouse%2Shift%3Control%4Name%5") + .arg(i+1) + .arg(manips[i].Mouse) + .arg(manips[i].Shift) + .arg(manips[i].Control) + .arg(QString(manips[i].Name)); + } + settings->setValue("InteractorStyle/CameraManipulators", strs); } settings->endGroup(); // Loop through render views and apply the settings QList views = - pqApplicationCore::instance()->getServerManagerModel()-> - findItems(); + pqApplicationCore::instance()->getServerManagerModel()-> + findItems(); foreach(pqRenderViewBase* view, views) { view->restoreSettings(true); diff --git a/src/Plugins/ParaMEDCorba/VTKMEDCouplingMultiFieldsClient.cxx b/src/Plugins/ParaMEDCorba/VTKMEDCouplingMultiFieldsClient.cxx index 730a51bf..499503df 100644 --- a/src/Plugins/ParaMEDCorba/VTKMEDCouplingMultiFieldsClient.cxx +++ b/src/Plugins/ParaMEDCorba/VTKMEDCouplingMultiFieldsClient.cxx @@ -40,7 +40,7 @@ const double ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::EPS_TIME=1e-7; ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::MEDCouplingMultiFieldsFetcher(int bufferingPolicy, - SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_ptr mfieldsPtr):_effective_pol(bufferingPolicy),_mfields_ptr_released(false) + SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_ptr mfieldsPtr):_effective_pol(bufferingPolicy),_mfields_ptr_released(false) { _mfields_ptr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_duplicate(mfieldsPtr); _mfields_ptr->Register(); @@ -49,15 +49,15 @@ ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::MEDCouplingMultiFieldsFetcher(int ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::~MEDCouplingMultiFieldsFetcher() { for(std::vector::iterator it=_meshes.begin();it!=_meshes.end();it++) - { - if(*it) - (*it)->Delete(); - } + { + if(*it) + (*it)->Delete(); + } for(std::vector::iterator it2=_arrays.begin();it2!=_arrays.end();it2++) - { - if(*it2) - (*it2)->Delete(); - } + { + if(*it2) + (*it2)->Delete(); + } if(!_mfields_ptr_released) _mfields_ptr->UnRegister(); } @@ -70,36 +70,36 @@ std::vector ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::getTimeStepsF _time_label_per_field.resize(nbOfFields); SALOME_MED::MEDCouplingFieldOverTimeCorbaInterface_var fotPtr=SALOME_MED::MEDCouplingFieldOverTimeCorbaInterface::_narrow(_mfields_ptr); if(CORBA::is_nil(fotPtr)) - { - for(CORBA::Long i=0;i=10) - { - fetchAll(); - return ; - } + { + fetchAll(); + return ; + } if(_effective_pol>=1 && _effective_pol<=9) - { - fetchMeshes(); - return ; - } + { + fetchMeshes(); + return ; + } } vtkDataSet *ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::buildDataSetOnTime(double time) @@ -112,34 +112,34 @@ vtkDataSet *ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::buildDataSetOnTime(do vtkDataSet *ret0=_meshes[meshId]; std::string clsName=ret0->GetClassName(); if(clsName=="vtkUnstructuredGrid") - { - vtkUnstructuredGrid *ret1=vtkUnstructuredGrid::New(); - ret1->DeepCopy(ret0); - if(_is_meshes_polyhedron[meshId])//bug VTK polyhedron - {//bug VTK polyhedron part - ret1->Faces->UnRegister(ret1); - ret1->Faces=vtkIdTypeArray::New(); - ret1->Faces->DeepCopy(((vtkUnstructuredGrid *)ret0)->GetFaces()); - ret1->Faces->Register(ret1); - ret1->Faces->Delete(); - ret1->FaceLocations->UnRegister(ret1); - ret1->FaceLocations=vtkIdTypeArray::New(); - ret1->FaceLocations->DeepCopy(((vtkUnstructuredGrid *)ret0)->GetFaceLocations()); - ret1->FaceLocations->Register(ret1); - ret1->FaceLocations->Delete(); - }//end bug VTK polyhedron part - appendFieldValueOnAlreadyFetchedData(ret1,fieldId); - applyBufferingPolicy(); - return ret1; - } + { + vtkUnstructuredGrid *ret1=vtkUnstructuredGrid::New(); + ret1->DeepCopy(ret0); + if(_is_meshes_polyhedron[meshId])//bug VTK polyhedron + {//bug VTK polyhedron part + ret1->Faces->UnRegister(ret1); + ret1->Faces=vtkIdTypeArray::New(); + ret1->Faces->DeepCopy(((vtkUnstructuredGrid *)ret0)->GetFaces()); + ret1->Faces->Register(ret1); + ret1->Faces->Delete(); + ret1->FaceLocations->UnRegister(ret1); + ret1->FaceLocations=vtkIdTypeArray::New(); + ret1->FaceLocations->DeepCopy(((vtkUnstructuredGrid *)ret0)->GetFaceLocations()); + ret1->FaceLocations->Register(ret1); + ret1->FaceLocations->Delete(); + }//end bug VTK polyhedron part + appendFieldValueOnAlreadyFetchedData(ret1,fieldId); + applyBufferingPolicy(); + return ret1; + } if(clsName=="vtkRectilinearGrid") - { - vtkRectilinearGrid *ret1=vtkRectilinearGrid::New(); - ret1->DeepCopy(ret0); - appendFieldValueOnAlreadyFetchedData(ret1,fieldId); - applyBufferingPolicy(); - return ret1; - } + { + vtkRectilinearGrid *ret1=vtkRectilinearGrid::New(); + ret1->DeepCopy(ret0); + appendFieldValueOnAlreadyFetchedData(ret1,fieldId); + applyBufferingPolicy(); + return ret1; + } return 0; } @@ -161,20 +161,20 @@ void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::retrievesMainTinyInfo() int offsetTime=0; int offsetArrays=0; for(int i=0;igetTinyInfo(i,tinyL,tinyD,tinyS); - _info_per_field[i]._type=(*tinyL)[0]; - _info_per_field[i]._name=(*tinyS)[0]; - delete tinyL; - delete tinyD; - delete tinyS; - } + { + _mfields_ptr->getTinyInfo(i,tinyL,tinyD,tinyS); + _info_per_field[i]._type=(*tinyL)[0]; + _info_per_field[i]._name=(*tinyS)[0]; + delete tinyL; + delete tinyD; + delete tinyS; + } } void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::fetchAll() @@ -199,13 +199,13 @@ void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::fetchAll() fetchMeshes(); int nbOfArrays=_arrays.size(); for(int i=0;igetArray(i); - if(_arrays[i]) - _arrays[i]->Delete(); - _arrays[i]=ParaMEDMEM2VTK::BuildFromMEDCouplingFieldDoubleArr(daPtr); - daPtr->UnRegister(); - } + { + SALOME_MED::DataArrayDoubleCorbaInterface_var daPtr=_mfields_ptr->getArray(i); + if(_arrays[i]) + _arrays[i]->Delete(); + _arrays[i]=ParaMEDMEM2VTK::BuildFromMEDCouplingFieldDoubleArr(daPtr); + daPtr->UnRegister(); + } unregisterRemoteServantIfAllFetched(); } @@ -216,15 +216,15 @@ void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::fetchMeshes() { int nbOfMeshes=_meshes.size(); for(int i=0;igetMeshWithId(i); - if(_meshes[i]) - _meshes[i]->Delete(); - bool polyh=false;//bug VTK - _meshes[i]=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(mPtr,polyh);//bug VTK - _is_meshes_polyhedron[i]=polyh;//bug VTK - mPtr->UnRegister(); - } + { + SALOME_MED::MEDCouplingMeshCorbaInterface_var mPtr=_mfields_ptr->getMeshWithId(i); + if(_meshes[i]) + _meshes[i]->Delete(); + bool polyh=false;//bug VTK + _meshes[i]=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(mPtr,polyh);//bug VTK + _is_meshes_polyhedron[i]=polyh;//bug VTK + mPtr->UnRegister(); + } unregisterRemoteServantIfAllFetched(); } @@ -237,65 +237,65 @@ void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::fetchDataIfNeeded(int fieldI std::vector arrayIds=_array_ids_per_field[fieldId]; int meshId=_mesh_id_per_field[fieldId]; if(!_meshes[meshId]) - { - SALOME_MED::MEDCouplingMeshCorbaInterface_var mPtr=_mfields_ptr->getMeshWithId(meshId); - bool polyh=false;//bug VTK - _meshes[meshId]=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(mPtr,polyh);//bug VTK - _is_meshes_polyhedron[meshId]=polyh;//bug VTK - mPtr->UnRegister(); - } + { + SALOME_MED::MEDCouplingMeshCorbaInterface_var mPtr=_mfields_ptr->getMeshWithId(meshId); + bool polyh=false;//bug VTK + _meshes[meshId]=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(mPtr,polyh);//bug VTK + _is_meshes_polyhedron[meshId]=polyh;//bug VTK + mPtr->UnRegister(); + } for(std::vector::const_iterator it=arrayIds.begin();it!=arrayIds.end();it++) + { + if(!_arrays[*it]) { - if(!_arrays[*it]) - { - SALOME_MED::DataArrayDoubleCorbaInterface_var daPtr=_mfields_ptr->getArray(*it); - _arrays[*it]=ParaMEDMEM2VTK::BuildFromMEDCouplingFieldDoubleArr(daPtr); - daPtr->UnRegister(); - } + SALOME_MED::DataArrayDoubleCorbaInterface_var daPtr=_mfields_ptr->getArray(*it); + _arrays[*it]=ParaMEDMEM2VTK::BuildFromMEDCouplingFieldDoubleArr(daPtr); + daPtr->UnRegister(); } + } unregisterRemoteServantIfAllFetched(); } void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::unregisterRemoteServantIfAllFetched() { for(std::vector::iterator it=_meshes.begin();it!=_meshes.end();it++) - { - if((*it)==0) - return ; - } + { + if((*it)==0) + return ; + } for(std::vector::iterator it2=_arrays.begin();it2!=_arrays.end();it2++) - { - if((*it2)==0) - return ; - } + { + if((*it2)==0) + return ; + } if(!_mfields_ptr_released) - { - _mfields_ptr_released=true; - _mfields_ptr->UnRegister(); - } + { + _mfields_ptr_released=true; + _mfields_ptr->UnRegister(); + } } void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::applyBufferingPolicy() { if(_effective_pol==0) - {// - for(std::vector::iterator it=_meshes.begin();it!=_meshes.end();it++) - { - if(*it) - { - (*it)->Delete(); - *it=0; - } - } - for(std::vector::iterator it2=_arrays.begin();it2!=_arrays.end();it2++) - { - if(*it2) - { - (*it2)->Delete(); - *it2=0; - } - } + {// + for(std::vector::iterator it=_meshes.begin();it!=_meshes.end();it++) + { + if(*it) + { + (*it)->Delete(); + *it=0; + } + } + for(std::vector::iterator it2=_arrays.begin();it2!=_arrays.end();it2++) + { + if(*it2) + { + (*it2)->Delete(); + *it2=0; + } } + } //else nothing to do let the plugin bufferize } @@ -305,15 +305,15 @@ void ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::appendFieldValueOnAlreadyFet vtkDoubleArray *arr=_arrays[_array_ids_per_field[fieldId].front()]; arr->SetName(info._name.c_str()); if(info._type==0)//ON_CELLS - { - ds->GetCellData()->AddArray(arr); - return ; - } + { + ds->GetCellData()->AddArray(arr); + return ; + } if(info._type==1)//ON_NODES - { - ds->GetPointData()->AddArray(arr); - return ; - } + { + ds->GetPointData()->AddArray(arr); + return ; + } } int ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::getPosGivenTimeLabel(double t) @@ -324,7 +324,7 @@ int ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher::getPosGivenTimeLabel(double t return i; //2nd chance std::vector::iterator it=std::find_if(_time_label_per_field.begin(),_time_label_per_field.end(), - std::bind2nd(std::greater(),t)); + std::bind2nd(std::greater(),t)); if(it!=_time_label_per_field.end() && it!=_time_label_per_field.end()) return std::distance(_time_label_per_field.begin(),it); // diff --git a/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.cxx b/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.cxx index 51472886..06b50bf4 100644 --- a/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.cxx +++ b/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.cxx @@ -57,12 +57,12 @@ vtkParaMEDCorbaSource::vtkParaMEDCorbaSource():mfieldsFetcher(0) { this->MyDataSet=0; if(!Orb) - { - CORBA::ORB_var *OrbC=new CORBA::ORB_var; - int argc=0; - *OrbC=CORBA::ORB_init(argc,0); - this->Orb=OrbC; - } + { + CORBA::ORB_var *OrbC=new CORBA::ORB_var; + int argc=0; + *OrbC=CORBA::ORB_init(argc,0); + this->Orb=OrbC; + } this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); } @@ -99,11 +99,11 @@ int vtkParaMEDCorbaSource::GetBufferingPolicy() return BufferingPolicy; } - //int vtkParaMEDCorbaSource::RequestUpdateExtent( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ) - //{ - //return this->Superclass::RequestUpdateExtent(request,inInfo,outInfo); +//int vtkParaMEDCorbaSource::RequestUpdateExtent( vtkInformation* request, vtkInformationVector** inInfo, vtkInformationVector* outInfo ) +//{ +//return this->Superclass::RequestUpdateExtent(request,inInfo,outInfo); - /*vtkParaMEDCorbaDataSet* output = vtkParaMEDCorbaDataSet::SafeDownCast( info->Get( vtkDataObject::DATA_OBJECT() ) ); +/*vtkParaMEDCorbaDataSet* output = vtkParaMEDCorbaDataSet::SafeDownCast( info->Get( vtkDataObject::DATA_OBJECT() ) ); if ( ! output ) { output = vtkParaMEDCorbaDataSet::New(); @@ -112,22 +112,22 @@ int vtkParaMEDCorbaSource::GetBufferingPolicy() this->GetOutputPortInformation( 0 )->Set( vtkDataObject::DATA_EXTENT_TYPE(), output->GetExtentType() ); }*/ - // return 1; - //} +// return 1; +//} int vtkParaMEDCorbaSource::ProcessRequest(vtkInformation* request, - vtkInformationVector** inputVector, - vtkInformationVector* outputVector) + vtkInformationVector** inputVector, + vtkInformationVector* outputVector) { // generate the data if(request->Has(vtkDemandDrivenPipeline::REQUEST_DATA())) - { + { return this->RequestData(request, inputVector, outputVector); - } + } if(request->Has(vtkDemandDrivenPipeline::REQUEST_INFORMATION())) - { + { return this->RequestInformation(request, inputVector, outputVector); - } + } return this->Superclass::ProcessRequest(request, inputVector, outputVector); } @@ -142,44 +142,44 @@ int vtkParaMEDCorbaSource::RequestInformation(vtkInformation* request, vtkInform vtkInformation* myInfo=outInfo->GetInformationObject(0); //myInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUnstructuredGrid"); if(!IOR.empty()) + { + //myInfo->Remove(vtkDataObject::DATA_TYPE_NAME()); + //myInfo->Remove(PORT_REQUIREMENTS_FILLED()); + //myInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUnstructuredGrid"); + //myInfo->Set(PORT_REQUIREMENTS_FILLED(),1); + //vtkUnstructuredGrid *tony=vtkUnstructuredGrid::New(); + //tony->SetInformation(myInfo); + //myInfo->Set(vtkDataObject::DATA_OBJECT(),tony); + // + CORBA::ORB_var *OrbC=(CORBA::ORB_var *)this->Orb; + CORBA::Object_var obj=(*OrbC)->string_to_object(&IOR[0]); + // + Engines::MPIObject_ptr objPara=Engines::MPIObject::_narrow(obj); + if(CORBA::is_nil(objPara)) + {//sequential + this->TotalNumberOfPieces=1; + SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_var multiPtr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_narrow(obj); + if(!CORBA::is_nil(multiPtr)) + {//Request for multiFields + delete mfieldsFetcher; + mfieldsFetcher=new ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher(BufferingPolicy,multiPtr); + std::vector tsteps=mfieldsFetcher->getTimeStepsForPV(); + double timeRange[2]; + timeRange[0]=tsteps.front(); + timeRange[1]=tsteps.back(); + myInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&tsteps[0],tsteps.size()); + myInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); + } + } + else { - //myInfo->Remove(vtkDataObject::DATA_TYPE_NAME()); - //myInfo->Remove(PORT_REQUIREMENTS_FILLED()); - //myInfo->Set(vtkDataObject::DATA_TYPE_NAME(),"vtkUnstructuredGrid"); - //myInfo->Set(PORT_REQUIREMENTS_FILLED(),1); - //vtkUnstructuredGrid *tony=vtkUnstructuredGrid::New(); - //tony->SetInformation(myInfo); - //myInfo->Set(vtkDataObject::DATA_OBJECT(),tony); - // - CORBA::ORB_var *OrbC=(CORBA::ORB_var *)this->Orb; - CORBA::Object_var obj=(*OrbC)->string_to_object(&IOR[0]); - // - Engines::MPIObject_ptr objPara=Engines::MPIObject::_narrow(obj); - if(CORBA::is_nil(objPara)) - {//sequential - this->TotalNumberOfPieces=1; - SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_var multiPtr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_narrow(obj); - if(!CORBA::is_nil(multiPtr)) - {//Request for multiFields - delete mfieldsFetcher; - mfieldsFetcher=new ParaMEDMEM2VTK::MEDCouplingMultiFieldsFetcher(BufferingPolicy,multiPtr); - std::vector tsteps=mfieldsFetcher->getTimeStepsForPV(); - double timeRange[2]; - timeRange[0]=tsteps.front(); - timeRange[1]=tsteps.back(); - myInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&tsteps[0],tsteps.size()); - myInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); - } - } - else - { - Engines::IORTab *iorTab=objPara->tior(); - this->TotalNumberOfPieces=iorTab->length(); - delete iorTab; - CORBA::release(objPara); - } - myInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),this->TotalNumberOfPieces); + Engines::IORTab *iorTab=objPara->tior(); + this->TotalNumberOfPieces=iorTab->length(); + delete iorTab; + CORBA::release(objPara); } + myInfo->Set(vtkStreamingDemandDrivenPipeline::MAXIMUM_NUMBER_OF_PIECES(),this->TotalNumberOfPieces); + } return 1; } @@ -202,67 +202,67 @@ int vtkParaMEDCorbaSource::RequestData(vtkInformation* request, vtkInformationVe // Engines::MPIObject_var objPara=Engines::MPIObject::_narrow(obj); if(CORBA::is_nil(objPara)) - {//sequential - SALOME_MED::MEDCouplingMeshCorbaInterface_var meshPtr=SALOME_MED::MEDCouplingMeshCorbaInterface::_narrow(obj); - if(!CORBA::is_nil(meshPtr)) - { - bool dummy;//bug VTK - vtkDataSet *ret=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(meshPtr,dummy);//bug VTK - if(!ret) - return 0; - ret0->SetBlock(0,ret); - ret->Delete(); - return 1; - } - SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_var fieldPtr=SALOME_MED::MEDCouplingFieldDoubleCorbaInterface::_narrow(obj); - if(!CORBA::is_nil(fieldPtr)) - { - std::vector ret2; - vtkDataSet *ret=ParaMEDMEM2VTK::BuildFullyFilledFromMEDCouplingFieldDoubleInstance(fieldPtr,ret2); - if(!ret) - { - vtkErrorMacro("On single field CORBA fetching an error occurs !"); - return 0; - } - ret0->SetBlock(0,ret); - ret->Delete(); - // - double timeRange[2]; - timeRange[0]=ret2[0]; - timeRange[1]=ret2[0]; - outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&ret2[0],1); - outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); - ret0->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),ret2[0]); - return 1; - } - SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_var multiPtr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_narrow(obj); - if(!CORBA::is_nil(multiPtr)) - { - vtkDataSet *ret=mfieldsFetcher->buildDataSetOnTime(reqTS); - if(!ret) - { - vtkErrorMacro("On multi fields CORBA fetching an error occurs !"); - return 0; - } - ret0->SetBlock(0,ret); - ret->Delete(); - ret0->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),reqTS); - return 1; - } - vtkErrorMacro("Unrecognized sequential CORBA reference !"); - return 0; + {//sequential + SALOME_MED::MEDCouplingMeshCorbaInterface_var meshPtr=SALOME_MED::MEDCouplingMeshCorbaInterface::_narrow(obj); + if(!CORBA::is_nil(meshPtr)) + { + bool dummy;//bug VTK + vtkDataSet *ret=ParaMEDMEM2VTK::BuildFromMEDCouplingMeshInstance(meshPtr,dummy);//bug VTK + if(!ret) + return 0; + ret0->SetBlock(0,ret); + ret->Delete(); + return 1; + } + SALOME_MED::MEDCouplingFieldDoubleCorbaInterface_var fieldPtr=SALOME_MED::MEDCouplingFieldDoubleCorbaInterface::_narrow(obj); + if(!CORBA::is_nil(fieldPtr)) + { + std::vector ret2; + vtkDataSet *ret=ParaMEDMEM2VTK::BuildFullyFilledFromMEDCouplingFieldDoubleInstance(fieldPtr,ret2); + if(!ret) + { + vtkErrorMacro("On single field CORBA fetching an error occurs !"); + return 0; + } + ret0->SetBlock(0,ret); + ret->Delete(); + // + double timeRange[2]; + timeRange[0]=ret2[0]; + timeRange[1]=ret2[0]; + outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_STEPS(),&ret2[0],1); + outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(),timeRange,2); + ret0->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),ret2[0]); + return 1; + } + SALOME_MED::MEDCouplingMultiFieldsCorbaInterface_var multiPtr=SALOME_MED::MEDCouplingMultiFieldsCorbaInterface::_narrow(obj); + if(!CORBA::is_nil(multiPtr)) + { + vtkDataSet *ret=mfieldsFetcher->buildDataSetOnTime(reqTS); + if(!ret) + { + vtkErrorMacro("On multi fields CORBA fetching an error occurs !"); + return 0; + } + ret0->SetBlock(0,ret); + ret->Delete(); + ret0->GetInformation()->Set(vtkDataObject::DATA_TIME_STEP(),reqTS); + return 1; } + vtkErrorMacro("Unrecognized sequential CORBA reference !"); + return 0; + } else + { + SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface_var paraFieldCorba=SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface::_narrow(obj); + if(!CORBA::is_nil(paraFieldCorba)) { - SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface_var paraFieldCorba=SALOME_MED::ParaMEDCouplingFieldDoubleCorbaInterface::_narrow(obj); - if(!CORBA::is_nil(paraFieldCorba)) - { - ParaMEDMEM2VTK::FillMEDCouplingParaFieldDoubleInstanceFrom(paraFieldCorba,this->StartPiece,this->EndPiece,ret0); - return 1; - } - vtkErrorMacro("Unrecognized parallel CORBA reference !"); - return 0; + ParaMEDMEM2VTK::FillMEDCouplingParaFieldDoubleInstanceFrom(paraFieldCorba,this->StartPiece,this->EndPiece,ret0); + return 1; } + vtkErrorMacro("Unrecognized parallel CORBA reference !"); + return 0; + } } void vtkParaMEDCorbaSource::PrintSelf(ostream& os, vtkIndent indent) diff --git a/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.h b/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.h index b9ddf7e7..c01c63e9 100644 --- a/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.h +++ b/src/Plugins/ParaMEDCorba/vtkParaMEDCorbaSource.h @@ -65,10 +65,10 @@ protected: //not clean but to avoid to include CORBA.h in this *.h static void *Orb; //ETX - private: +private: /*void traduceMedMeshToUnstructuredDataset(vtkUnstructuredGrid *ret, int nbOfCells, int nbOfNodes, - int nbOfTypes, const int *types, const int *nbOfEltsPerTypes, const int *nodalConnectivity, - const double *coords, int spaceDim); + int nbOfTypes, const int *types, const int *nbOfEltsPerTypes, const int *nodalConnectivity, + const double *coords, int spaceDim); vtkDoubleArray *buildDataArrayFromMedCoords(const double *coords, int nbOfNodes, int spaceDim); void reorganizeCellConnectivity(int vtkType, int nbOfNodes, const int *medConn, int *vtkConn); int transformMedGeomEltType2VtkType(int typeMed, int *nbOfNodesPerCell);*/ diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqCustomChartDisplayPanelImplementation.cxx b/src/Plugins/TableReader/ParaViewPlugin/pqCustomChartDisplayPanelImplementation.cxx index ca5b9b97..0582ae73 100755 --- a/src/Plugins/TableReader/ParaViewPlugin/pqCustomChartDisplayPanelImplementation.cxx +++ b/src/Plugins/TableReader/ParaViewPlugin/pqCustomChartDisplayPanelImplementation.cxx @@ -28,51 +28,51 @@ pqCustomChartDisplayPanelImplementation::pqCustomChartDisplayPanelImplementation(QObject* p): QObject(p) - { - } +{ +} bool pqCustomChartDisplayPanelImplementation::canCreatePanel(pqRepresentation* repr) const { if(!repr || !repr->getProxy() || - (repr->getProxy()->GetXMLName() != QString("XYChartRepresentation"))) - { - return false; - } + (repr->getProxy()->GetXMLName() != QString("XYChartRepresentation"))) + { + return false; + } pqDataRepresentation* dataRepr = qobject_cast(repr); if(dataRepr) + { + pqPipelineSource* input = dataRepr->getInput(); + QString name = input->getProxy()->GetXMLName(); + if (name == "TableReader") { - pqPipelineSource* input = dataRepr->getInput(); - QString name = input->getProxy()->GetXMLName(); - if (name == "TableReader") - { - return true; - } + return true; } - + } + return false; } pqDisplayPanel* pqCustomChartDisplayPanelImplementation::createPanel(pqRepresentation* repr, QWidget* p) { if(!repr || !repr->getProxy() || - (repr->getProxy()->GetXMLName() != QString("XYChartRepresentation"))) - { - return NULL; - } + (repr->getProxy()->GetXMLName() != QString("XYChartRepresentation"))) + { + return NULL; + } pqDataRepresentation* dataRepr = qobject_cast(repr); if(dataRepr) - { - pqPipelineSource* input = dataRepr->getInput(); - QString name=input->getProxy()->GetXMLName(); + { + pqPipelineSource* input = dataRepr->getInput(); + QString name=input->getProxy()->GetXMLName(); - if (name == "TableReader") - { - return new pqCustomXYChartDisplayPanel(repr, p); - } + if (name == "TableReader") + { + return new pqCustomXYChartDisplayPanel(repr, p); } - + } + return NULL; } diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqCustomPlotSettingsModel.cxx b/src/Plugins/TableReader/ParaViewPlugin/pqCustomPlotSettingsModel.cxx index 789e5cf2..75a65fdb 100644 --- a/src/Plugins/TableReader/ParaViewPlugin/pqCustomPlotSettingsModel.cxx +++ b/src/Plugins/TableReader/ParaViewPlugin/pqCustomPlotSettingsModel.cxx @@ -31,15 +31,15 @@ class pqCustomPlotSettingsModel::pqImplementation { public: pqImplementation() - { - } +{ +} vtkWeakPointer RepresentationProxy; QPointer Representation; }; pqCustomPlotSettingsModel::pqCustomPlotSettingsModel(QObject* parentObject) : - Superclass(parentObject), Implementation(new pqImplementation()) + Superclass(parentObject), Implementation(new pqImplementation()) { } @@ -54,17 +54,17 @@ void pqCustomPlotSettingsModel::setRepresentation(pqDataRepresentation* rep) Superclass::setRepresentation(rep); if (!rep || rep == this->Implementation->Representation) - { + { return; - } + } if (this->Implementation->Representation) - { + { QObject::disconnect(this->Implementation->Representation, 0, this, 0); - } + } this->Implementation->RepresentationProxy = - vtkSMChartRepresentationProxy::SafeDownCast(rep->getProxy()); + vtkSMChartRepresentationProxy::SafeDownCast(rep->getProxy()); this->Implementation->Representation = rep; } @@ -76,26 +76,26 @@ pqDataRepresentation* pqCustomPlotSettingsModel::representation() const //----------------------------------------------------------------------------- bool pqCustomPlotSettingsModel::setData(const QModelIndex &idx, const QVariant &value, - int role) + int role) { bool result = false; if (idx.isValid() && idx.model() == this) - { + { if (idx.column() == 1 && (role == Qt::DisplayRole || role == Qt::EditRole)) - { + { QString name = value.toString(); if (!name.isEmpty()) - { + { this->setSeriesLabel(idx.row(), name); - } } + } else if(idx.column() == 0 && role == Qt::CheckStateRole) - { + { result = true; int checkstate = value.toInt(); this->setSeriesEnabled(idx.row(), checkstate == Qt::Checked); - } } + } return result; } @@ -103,65 +103,65 @@ bool pqCustomPlotSettingsModel::setData(const QModelIndex &idx, const QVariant & void pqCustomPlotSettingsModel::setSeriesEnabled(int row, bool enabled) { if (row >= 0 && row < this->rowCount(QModelIndex())) + { + int minRow = row; + int maxRow = row; + + if (enabled && !(this->IgnoreUnitsModeOn)) { - int minRow = row; - int maxRow = row; - - if (enabled && !(this->IgnoreUnitsModeOn)) - { - QString unit = getUnit(QString(this->getSeriesName(row))); - - for (int i = 0; i < rowCount(QModelIndex()); i++) - { - if (i == row) - { - continue; - } - - bool rowChanged = false; - QString seriesName = QString(this->getSeriesName(i)); - QString seriesUnit = getUnit(seriesName); - - if ((seriesUnit != unit) && getSeriesEnabled(i)) - { - vtkSMPropertyHelper(this->Implementation->RepresentationProxy, - "SeriesVisibility").SetStatus(this->getSeriesName(i), 0); - rowChanged = true; - } - - if (!seriesUnit.isEmpty() && this->AutoSelectModeOn && - (seriesUnit == unit) && !getSeriesEnabled(i)) - { - vtkSMPropertyHelper(this->Implementation->RepresentationProxy, - "SeriesVisibility").SetStatus(this->getSeriesName(i), 1); - rowChanged = true; - } - - if (rowChanged) - { - if (i < minRow) - { - minRow = i; - } - else if (i > maxRow) - { - maxRow = i; - } - } - } - } - - vtkSMPropertyHelper(this->Implementation->RepresentationProxy, - "SeriesVisibility").SetStatus(this->getSeriesName(row), enabled ? 1 : 0); - this->Implementation->RepresentationProxy->UpdateVTKObjects(); - - this->setSeriesColor(row, this->getSeriesColor(row)); - QModelIndex topLeft = this->createIndex(minRow, 0); - QModelIndex bottomRight = this->createIndex(maxRow, 0); - emit this->dataChanged(topLeft, bottomRight); - emit this->redrawChart(); - this->updateCheckState(0, Qt::Horizontal); + QString unit = getUnit(QString(this->getSeriesName(row))); + + for (int i = 0; i < rowCount(QModelIndex()); i++) + { + if (i == row) + { + continue; + } + + bool rowChanged = false; + QString seriesName = QString(this->getSeriesName(i)); + QString seriesUnit = getUnit(seriesName); + + if ((seriesUnit != unit) && getSeriesEnabled(i)) + { + vtkSMPropertyHelper(this->Implementation->RepresentationProxy, + "SeriesVisibility").SetStatus(this->getSeriesName(i), 0); + rowChanged = true; + } + + if (!seriesUnit.isEmpty() && this->AutoSelectModeOn && + (seriesUnit == unit) && !getSeriesEnabled(i)) + { + vtkSMPropertyHelper(this->Implementation->RepresentationProxy, + "SeriesVisibility").SetStatus(this->getSeriesName(i), 1); + rowChanged = true; + } + + if (rowChanged) + { + if (i < minRow) + { + minRow = i; + } + else if (i > maxRow) + { + maxRow = i; + } + } + } } + + vtkSMPropertyHelper(this->Implementation->RepresentationProxy, + "SeriesVisibility").SetStatus(this->getSeriesName(row), enabled ? 1 : 0); + this->Implementation->RepresentationProxy->UpdateVTKObjects(); + + this->setSeriesColor(row, this->getSeriesColor(row)); + QModelIndex topLeft = this->createIndex(minRow, 0); + QModelIndex bottomRight = this->createIndex(maxRow, 0); + emit this->dataChanged(topLeft, bottomRight); + emit this->redrawChart(); + this->updateCheckState(0, Qt::Horizontal); + } } //----------------------------------------------------------------------------- @@ -170,15 +170,15 @@ void pqCustomPlotSettingsModel::SetIgnoreUnitsModeOn(bool enabled) this->IgnoreUnitsModeOn = enabled; if (this->IgnoreUnitsModeOn) - { - this->setCheckable(0, Qt::Horizontal, true); - this->setCheckState(0, Qt::Horizontal, Qt::Unchecked); - } + { + this->setCheckable(0, Qt::Horizontal, true); + this->setCheckState(0, Qt::Horizontal, Qt::Unchecked); + } else - { - this->setCheckState(0, Qt::Horizontal, Qt::Unchecked); - this->setCheckable(0, Qt::Horizontal, false); - } + { + this->setCheckState(0, Qt::Horizontal, Qt::Unchecked); + this->setCheckable(0, Qt::Horizontal, false); + } } //----------------------------------------------------------------------------- @@ -186,33 +186,33 @@ void pqCustomPlotSettingsModel::SetAutoSelectModeOn(bool enabled) { this->AutoSelectModeOn = enabled; if (enabled && !this->IgnoreUnitsModeOn) + { + for (int i = 0; i < rowCount(QModelIndex()); i++) { - for (int i = 0; i < rowCount(QModelIndex()); i++) - { - if (getSeriesEnabled(i)) - { - setSeriesEnabled(i, true); - break; - } - } + if (getSeriesEnabled(i)) + { + setSeriesEnabled(i, true); + break; + } } + } } //----------------------------------------------------------------------------- QString pqCustomPlotSettingsModel::getUnit(const QString& seriesName) { QString unit(""); - + int index1 = seriesName.lastIndexOf("]"); if (index1 == seriesName.size() - 1) + { + int index2 = seriesName.lastIndexOf(" ["); + if (index2 > 0) { - int index2 = seriesName.lastIndexOf(" ["); - if (index2 > 0) - { - int start = index2 + 2; - unit = seriesName.mid(index2 + 2, index1 - start); - } + int start = index2 + 2; + unit = seriesName.mid(index2 + 2, index1 - start); } + } return unit; } diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqCustomXYChartDisplayPanel.cxx b/src/Plugins/TableReader/ParaViewPlugin/pqCustomXYChartDisplayPanel.cxx index a2fb94b9..c4ed2cb1 100644 --- a/src/Plugins/TableReader/ParaViewPlugin/pqCustomXYChartDisplayPanel.cxx +++ b/src/Plugins/TableReader/ParaViewPlugin/pqCustomXYChartDisplayPanel.cxx @@ -58,20 +58,20 @@ class pqCustomXYChartDisplayPanel::pqInternal : public Ui::CustomXYChartDisplayP { public: pqInternal() - { +{ this->SettingsModel = 0; this->XAxisArrayDomain = 0; this->XAxisArrayAdaptor = 0; this->VTKConnect = vtkSmartPointer::New(); - } +} ~pqInternal() - { + { delete this->SettingsModel; delete this->XAxisArrayDomain; delete this->XAxisArrayAdaptor; - } + } vtkWeakPointer ChartRepresentation; pqCustomPlotSettingsModel* SettingsModel; @@ -86,7 +86,7 @@ public: //----------------------------------------------------------------------------- pqCustomXYChartDisplayPanel::pqCustomXYChartDisplayPanel( - pqRepresentation* display,QWidget* p) + pqRepresentation* display,QWidget* p) : pqDisplayPanel(display, p) { this->Internal = new pqCustomXYChartDisplayPanel::pqInternal(); @@ -96,64 +96,64 @@ pqCustomXYChartDisplayPanel::pqCustomXYChartDisplayPanel( this->Internal->SeriesList->setModel(this->Internal->SettingsModel); this->Internal->XAxisArrayAdaptor = new pqSignalAdaptorComboBox( - this->Internal->XAxisArray); + this->Internal->XAxisArray); QObject::connect( - this->Internal->SeriesList, SIGNAL(activated(const QModelIndex &)), - this, SLOT(activateItem(const QModelIndex &))); + this->Internal->SeriesList, SIGNAL(activated(const QModelIndex &)), + this, SLOT(activateItem(const QModelIndex &))); QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); QObject::connect(model, - SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), - this, SLOT(updateOptionsWidgets())); + SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), + this, SLOT(updateOptionsWidgets())); QObject::connect(model, - SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), - this, SLOT(updateOptionsWidgets())); + SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), + this, SLOT(updateOptionsWidgets())); QObject::connect(this->Internal->SettingsModel, SIGNAL(modelReset()), - this, SLOT(updateOptionsWidgets())); + this, SLOT(updateOptionsWidgets())); QObject::connect(this->Internal->SettingsModel, SIGNAL(redrawChart()), - this, SLOT(updateAllViews())); + this, SLOT(updateAllViews())); QObject::connect(this->Internal->XAxisArray, SIGNAL(currentIndexChanged(int)), - this, SLOT(updateAllViews())); + this, SLOT(updateAllViews())); QObject::connect(this->Internal->UseArrayIndex, SIGNAL(toggled(bool)), - this, SLOT(useArrayIndexToggled(bool))); + this, SLOT(useArrayIndexToggled(bool))); QObject::connect(this->Internal->UseDataArray, SIGNAL(toggled(bool)), - this, SLOT(useDataArrayToggled(bool))); + this, SLOT(useDataArrayToggled(bool))); QObject::connect( - this->Internal->ColorButton, SIGNAL(chosenColorChanged(const QColor &)), - this, SLOT(setCurrentSeriesColor(const QColor &))); + this->Internal->ColorButton, SIGNAL(chosenColorChanged(const QColor &)), + this, SLOT(setCurrentSeriesColor(const QColor &))); QObject::connect(this->Internal->Thickness, SIGNAL(valueChanged(int)), - this, SLOT(setCurrentSeriesThickness(int))); + this, SLOT(setCurrentSeriesThickness(int))); QObject::connect(this->Internal->StyleList, SIGNAL(currentIndexChanged(int)), - this, SLOT(setCurrentSeriesStyle(int))); + this, SLOT(setCurrentSeriesStyle(int))); QObject::connect(this->Internal->AxisList, SIGNAL(currentIndexChanged(int)), - this, SLOT(setCurrentSeriesAxes(int))); + this, SLOT(setCurrentSeriesAxes(int))); QObject::connect(this->Internal->MarkerStyleList, SIGNAL(currentIndexChanged(int)), - this, SLOT(setCurrentSeriesMarkerStyle(int))); + this, SLOT(setCurrentSeriesMarkerStyle(int))); QObject::connect( - this->Internal->AutoSelect, SIGNAL(toggled(bool)), - this, SLOT(autoSelectToggled(bool))); + this->Internal->AutoSelect, SIGNAL(toggled(bool)), + this, SLOT(autoSelectToggled(bool))); QObject::connect( - this->Internal->IgnoreUnits, SIGNAL(toggled(bool)), - this, SLOT(ignoreUnitsToggled(bool))); + this->Internal->IgnoreUnits, SIGNAL(toggled(bool)), + this, SLOT(ignoreUnitsToggled(bool))); QObject::connect( - this->Internal->GenerateAxesTitles, SIGNAL(toggled(bool)), - this, SLOT(updateViewOptions())); + this->Internal->GenerateAxesTitles, SIGNAL(toggled(bool)), + this, SLOT(updateViewOptions())); QObject::connect(this->Internal->SettingsModel, SIGNAL(redrawChart()), - this, SLOT(updateViewOptions())); + this, SLOT(updateViewOptions())); resetUnitsControls(); this->setDisplay(display); QObject::connect(&this->Internal->Links, SIGNAL(qtWidgetChanged()), - this, SLOT(reloadSeries()), Qt::QueuedConnection); + this, SLOT(reloadSeries()), Qt::QueuedConnection); QObject::connect(&this->Internal->Links, SIGNAL(qtWidgetChanged()), - this->Internal->SettingsModel, SLOT(reload())); + this->Internal->SettingsModel, SLOT(reload())); } //----------------------------------------------------------------------------- @@ -166,7 +166,7 @@ pqCustomXYChartDisplayPanel::~pqCustomXYChartDisplayPanel() void pqCustomXYChartDisplayPanel::reloadSeries() { updateViewOptions(); - + this->updateAllViews(); this->updateOptionsWidgets(); } @@ -177,14 +177,14 @@ void pqCustomXYChartDisplayPanel::setDisplay(pqRepresentation* disp) this->setEnabled(false); vtkSMChartRepresentationProxy* proxy = - vtkSMChartRepresentationProxy::SafeDownCast(disp->getProxy()); + vtkSMChartRepresentationProxy::SafeDownCast(disp->getProxy()); this->Internal->ChartRepresentation = proxy; if (!this->Internal->ChartRepresentation) - { + { qWarning() << "pqCustomXYChartDisplayPanel given a representation proxy " - "that is not an XYChartRepresentation. Cannot edit."; + "that is not an XYChartRepresentation. Cannot edit."; return; - } + } // this is essential to ensure that when you undo-redo, the representation is // indeed update-to-date, thus ensuring correct domains etc. @@ -204,13 +204,13 @@ void pqCustomXYChartDisplayPanel::setDisplay(pqRepresentation* disp) // Link to set whether the index is used for the x axis this->Internal->Links.addPropertyLink( - this->Internal->UseArrayIndex, "checked", - SIGNAL(toggled(bool)), - proxy, proxy->GetProperty("UseIndexForXAxis")); + this->Internal->UseArrayIndex, "checked", + SIGNAL(toggled(bool)), + proxy, proxy->GetProperty("UseIndexForXAxis")); // Proxy changed this->Internal->VTKConnect->Connect(proxy->GetProperty("SeriesNamesInfo"), - vtkCommand::PropertyModifiedEvent, this, SLOT(resetUnitsControls())); + vtkCommand::PropertyModifiedEvent, this, SLOT(resetUnitsControls())); this->changeDialog(disp); @@ -223,13 +223,13 @@ void pqCustomXYChartDisplayPanel::setDisplay(pqRepresentation* disp) void pqCustomXYChartDisplayPanel::changeDialog(pqRepresentation* disp) { vtkSMChartRepresentationProxy* proxy = - vtkSMChartRepresentationProxy::SafeDownCast(disp->getProxy()); + vtkSMChartRepresentationProxy::SafeDownCast(disp->getProxy()); bool visible = true; if (QString("Bar") == vtkSMPropertyHelper(proxy,"ChartType").GetAsString()) - { - visible = false; - } - + { + visible = false; + } + this->Internal->Thickness->setVisible(visible); this->Internal->ThicknessLabel->setVisible(visible); this->Internal->StyleList->setVisible(visible); @@ -245,10 +245,10 @@ void pqCustomXYChartDisplayPanel::activateItem(const QModelIndex &index) { if(!this->Internal->ChartRepresentation || !index.isValid() || index.column() != 1) - { + { // We are interested in clicks on the color swab alone. return; - } + } // Get current color QColor color = this->Internal->SettingsModel->getSeriesColor(index.row()); @@ -256,14 +256,14 @@ void pqCustomXYChartDisplayPanel::activateItem(const QModelIndex &index) // Show color selector dialog to get a new color color = QColorDialog::getColor(color, this); if (color.isValid()) - { + { // Set the new color this->Internal->SettingsModel->setSeriesColor(index.row(), color); this->Internal->ColorButton->blockSignals(true); this->Internal->ColorButton->setChosenColor(color); this->Internal->ColorButton->blockSignals(false); this->updateAllViews(); - } + } } //----------------------------------------------------------------------------- @@ -271,15 +271,15 @@ void pqCustomXYChartDisplayPanel::updateOptionsWidgets() { QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); if(model) - { + { // Show the options for the current item. QModelIndex current = model->currentIndex(); QModelIndexList indexes = model->selectedIndexes(); if((!current.isValid() || !model->isSelected(current)) && indexes.size() > 0) - { + { current = indexes.last(); - } + } this->Internal->ColorButton->blockSignals(true); this->Internal->Thickness->blockSignals(true); @@ -287,27 +287,27 @@ void pqCustomXYChartDisplayPanel::updateOptionsWidgets() this->Internal->MarkerStyleList->blockSignals(true); this->Internal->AxisList->blockSignals(true); if (current.isValid()) - { + { int seriesIndex = current.row(); QColor color = this->Internal->SettingsModel->getSeriesColor(seriesIndex); this->Internal->ColorButton->setChosenColor(color); this->Internal->Thickness->setValue( - this->Internal->SettingsModel->getSeriesThickness(seriesIndex)); + this->Internal->SettingsModel->getSeriesThickness(seriesIndex)); this->Internal->StyleList->setCurrentIndex( - this->Internal->SettingsModel->getSeriesStyle(seriesIndex)); + this->Internal->SettingsModel->getSeriesStyle(seriesIndex)); this->Internal->MarkerStyleList->setCurrentIndex( - this->Internal->SettingsModel->getSeriesMarkerStyle(seriesIndex)); + this->Internal->SettingsModel->getSeriesMarkerStyle(seriesIndex)); this->Internal->AxisList->setCurrentIndex( - this->Internal->SettingsModel->getSeriesAxisCorner(seriesIndex)); - } + this->Internal->SettingsModel->getSeriesAxisCorner(seriesIndex)); + } else - { + { this->Internal->ColorButton->setChosenColor(Qt::white); this->Internal->Thickness->setValue(1); this->Internal->StyleList->setCurrentIndex(0); this->Internal->MarkerStyleList->setCurrentIndex(0); this->Internal->AxisList->setCurrentIndex(0); - } + } this->Internal->ColorButton->blockSignals(false); this->Internal->Thickness->blockSignals(false); @@ -322,7 +322,7 @@ void pqCustomXYChartDisplayPanel::updateOptionsWidgets() this->Internal->StyleList->setEnabled(hasItems); this->Internal->MarkerStyleList->setEnabled(hasItems); this->Internal->AxisList->setEnabled(hasItems); - } + } } //----------------------------------------------------------------------------- @@ -330,16 +330,16 @@ void pqCustomXYChartDisplayPanel::setCurrentSeriesColor(const QColor &color) { QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); if(model) - { + { this->Internal->InChange = true; QModelIndexList indexes = model->selectedIndexes(); QModelIndexList::Iterator iter = indexes.begin(); for( ; iter != indexes.end(); ++iter) - { + { this->Internal->SettingsModel->setSeriesColor(iter->row(), color); - } - this->Internal->InChange = false; } + this->Internal->InChange = false; + } } //----------------------------------------------------------------------------- @@ -347,16 +347,16 @@ void pqCustomXYChartDisplayPanel::setCurrentSeriesThickness(int thickness) { QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); if (model) - { + { this->Internal->InChange = true; QModelIndexList indexes = model->selectedIndexes(); QModelIndexList::Iterator iter = indexes.begin(); for( ; iter != indexes.end(); ++iter) - { + { this->Internal->SettingsModel->setSeriesThickness(iter->row(), thickness); - } - this->Internal->InChange = false; } + this->Internal->InChange = false; + } } //----------------------------------------------------------------------------- @@ -364,16 +364,16 @@ void pqCustomXYChartDisplayPanel::setCurrentSeriesStyle(int style) { QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); if (model) - { + { this->Internal->InChange = true; QModelIndexList indexes = model->selectedIndexes(); QModelIndexList::Iterator iter = indexes.begin(); for( ; iter != indexes.end(); ++iter) - { + { this->Internal->SettingsModel->setSeriesStyle(iter->row(), style); - } - this->Internal->InChange = false; } + this->Internal->InChange = false; + } } //----------------------------------------------------------------------------- @@ -381,16 +381,16 @@ void pqCustomXYChartDisplayPanel::setCurrentSeriesMarkerStyle(int style) { QItemSelectionModel *model = this->Internal->SeriesList->selectionModel(); if (model) - { + { this->Internal->InChange = true; QModelIndexList indexes = model->selectedIndexes(); QModelIndexList::Iterator iter = indexes.begin(); for( ; iter != indexes.end(); ++iter) - { + { this->Internal->SettingsModel->setSeriesMarkerStyle(iter->row(), style); - } - this->Internal->InChange = false; } + this->Internal->InChange = false; + } } //----------------------------------------------------------------------------- @@ -432,7 +432,7 @@ void pqCustomXYChartDisplayPanel::ignoreUnitsToggled(bool checked) this->Internal->AutoSelect->setEnabled(!checked); this->Internal->SettingsModel->SetIgnoreUnitsModeOn(checked); this->Internal->SettingsModel->SetAutoSelectModeOn(!checked && - this->Internal->AutoSelect->isChecked()); + this->Internal->AutoSelect->isChecked()); } //----------------------------------------------------------------------------- @@ -447,65 +447,64 @@ void pqCustomXYChartDisplayPanel::updateViewOptions() { pqRepresentation* disp = this->getRepresentation(); if (!disp || !this->Internal->ChartRepresentation) + { + return; + } + + pqXYChartView* view = qobject_cast(disp->getView()); + if (view && view->getProxy()) + { + vtkSMProxy* proxy = view->getProxy(); + + QList values = + pqSMAdaptor::getMultipleElementProperty(proxy->GetProperty("AxisTitle")); + if (values.size() < 2) { return; } - pqXYChartView* view = qobject_cast(disp->getView()); - if (view && view->getProxy()) + if (!this->Internal->GenerateAxesTitles->isChecked()) { - vtkSMProxy* proxy = view->getProxy(); - - QList values = - pqSMAdaptor::getMultipleElementProperty(proxy->GetProperty("AxisTitle")); - if (values.size() < 2) - { - return; - } - - if (!this->Internal->GenerateAxesTitles->isChecked()) - { - values.insert(0, QVariant("")); - values.insert(1, QVariant("")); - } - else - { - // Set X axis title - int useIndexForXAxis = vtkSMPropertyHelper( - this->Internal->ChartRepresentation, "UseIndexForXAxis").GetAsInt(); - - QString xTitle(""); - if (!useIndexForXAxis) - { - xTitle = vtkSMPropertyHelper(this->Internal->ChartRepresentation, "XArrayName") - .GetAsString(); - } - - // Set Y axis title - int nbRows = this->Internal->SettingsModel->rowCount(QModelIndex()); - int nbEnabled = 0; - int row = 0; - for (int i = 0; i < nbRows && nbEnabled < 2; i++) - { - if (this->Internal->SettingsModel->getSeriesEnabled(i)) - { - nbEnabled++; - row = i; - } - } - - QString yTitle(""); - if (nbEnabled == 1) - { - yTitle = this->Internal->SettingsModel->getSeriesName(row); - } - values.insert(0, QVariant(yTitle)); - values.insert(1, QVariant(xTitle)); - } - - pqSMAdaptor::setMultipleElementProperty(proxy->GetProperty("AxisTitle"), values); - - view->getProxy()->UpdateVTKObjects(); - view->render(); + values.insert(0, QVariant("")); + values.insert(1, QVariant("")); + } + else + { + // Set X axis title + int useIndexForXAxis = vtkSMPropertyHelper( + this->Internal->ChartRepresentation, "UseIndexForXAxis").GetAsInt(); + + QString xTitle(""); + if (!useIndexForXAxis) + { + xTitle = vtkSMPropertyHelper(this->Internal->ChartRepresentation, "XArrayName").GetAsString(); + } + + // Set Y axis title + int nbRows = this->Internal->SettingsModel->rowCount(QModelIndex()); + int nbEnabled = 0; + int row = 0; + for (int i = 0; i < nbRows && nbEnabled < 2; i++) + { + if (this->Internal->SettingsModel->getSeriesEnabled(i)) + { + nbEnabled++; + row = i; + } + } + + QString yTitle(""); + if (nbEnabled == 1) + { + yTitle = this->Internal->SettingsModel->getSeriesName(row); + } + values.insert(0, QVariant(yTitle)); + values.insert(1, QVariant(xTitle)); } + + pqSMAdaptor::setMultipleElementProperty(proxy->GetProperty("AxisTitle"), values); + + view->getProxy()->UpdateVTKObjects(); + view->render(); + } } diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqTableReaderPanel.cxx b/src/Plugins/TableReader/ParaViewPlugin/pqTableReaderPanel.cxx index f5594f3c..ef676539 100644 --- a/src/Plugins/TableReader/ParaViewPlugin/pqTableReaderPanel.cxx +++ b/src/Plugins/TableReader/ParaViewPlugin/pqTableReaderPanel.cxx @@ -33,8 +33,8 @@ class pqTableReaderPanel::pqUI: public QObject, public Ui::TableReaderPanel { public: pqUI(pqTableReaderPanel* p) : QObject(p) - { - } +{ +} ~pqUI() { @@ -45,18 +45,18 @@ public: pqTableReaderPanel::pqTableReaderPanel(pqProxy* proxy, QWidget* p) : - Superclass(proxy, p) + Superclass(proxy, p) { this->UI = new pqUI(this); this->UI->setupUi(this); - + this->linkServerManagerProperties(); this->updateAvailableTables(false); this->connect(this->UI->ValueDelimiter, SIGNAL(textChanged(const QString&)), - this, SLOT(onDelimiterChanged(const QString&))); + this, SLOT(onDelimiterChanged(const QString&))); this->connect(this->UI->TableNames, SIGNAL(currentIndexChanged(int)), - this, SLOT(onCurrentTableChanged(int))); + this, SLOT(onCurrentTableChanged(int))); } pqTableReaderPanel::~pqTableReaderPanel() @@ -76,8 +76,8 @@ void pqTableReaderPanel::onDelimiterChanged(const QString& value) void pqTableReaderPanel::linkServerManagerProperties() { this->UI->Links.addPropertyLink(this->UI->TableNames, "currentIndex", - SIGNAL(currentIndexChanged(int)), this->proxy(), - this->proxy()->GetProperty("TableNumber")); + SIGNAL(currentIndexChanged(int)), this->proxy(), + this->proxy()->GetProperty("TableNumber")); // To hook up the rest widgets this->Superclass::linkServerManagerProperties(); @@ -86,27 +86,27 @@ void pqTableReaderPanel::linkServerManagerProperties() void pqTableReaderPanel::updateAvailableTables(const bool keepCurrent) { vtkSMStringVectorProperty* prop = vtkSMStringVectorProperty::SafeDownCast( - this->proxy()->GetProperty("AvailableTables")); - + this->proxy()->GetProperty("AvailableTables")); + int currentIndex = this->UI->TableNames->currentIndex(); QString currentText = this->UI->TableNames->currentText(); this->UI->TableNames->clear(); - + for(int id = 0; id < prop->GetNumberOfElements(); id++) + { + QString text(prop->GetElement(id)); + if (text.isEmpty()) { - QString text(prop->GetElement(id)); - if (text.isEmpty()) - { - text = QString("Table:%1").arg(id); - } - this->UI->TableNames->addItem(text); + text = QString("Table:%1").arg(id); } + this->UI->TableNames->addItem(text); + } if (keepCurrent && currentIndex < this->UI->TableNames->maxCount() && currentText == this->UI->TableNames->itemText(currentIndex)) - { - this->UI->TableNames->setCurrentIndex(currentIndex); - } + { + this->UI->TableNames->setCurrentIndex(currentIndex); + } } diff --git a/src/Plugins/TableReader/ParaViewPlugin/pqTableTo3DPanel.cxx b/src/Plugins/TableReader/ParaViewPlugin/pqTableTo3DPanel.cxx index 09db1565..f5a418a2 100644 --- a/src/Plugins/TableReader/ParaViewPlugin/pqTableTo3DPanel.cxx +++ b/src/Plugins/TableReader/ParaViewPlugin/pqTableTo3DPanel.cxx @@ -24,26 +24,26 @@ #include pqTableTo3DPanel::pqTableTo3DPanel(pqProxy* proxy, QWidget* p) : - Superclass(proxy, p) +Superclass(proxy, p) { QLineEdit* scaleFactor = this->findChild("ScaleFactor"); QCheckBox* useOptimusScale = this->findChild("UseOptimusScale"); QComboBox* presentationType = this->findChild("PresentationType"); QWidget* numberContours = this->findChild("NumberOfContours"); - + if (scaleFactor && useOptimusScale) - { - this->connect(useOptimusScale, SIGNAL(toggled(bool)), - this, SLOT(onScaleModeChanged(bool))); - onScaleModeChanged(useOptimusScale->isChecked()); - } + { + this->connect(useOptimusScale, SIGNAL(toggled(bool)), + this, SLOT(onScaleModeChanged(bool))); + onScaleModeChanged(useOptimusScale->isChecked()); + } if (presentationType && numberContours) - { - this->connect(presentationType, SIGNAL(currentIndexChanged(const QString &)), - this, SLOT(onPrsTypeChanged(const QString &))); - onPrsTypeChanged(presentationType->currentText()); - } + { + this->connect(presentationType, SIGNAL(currentIndexChanged(const QString &)), + this, SLOT(onPrsTypeChanged(const QString &))); + onPrsTypeChanged(presentationType->currentText()); + } } pqTableTo3DPanel::~pqTableTo3DPanel() @@ -54,16 +54,16 @@ void pqTableTo3DPanel::onScaleModeChanged(bool checked) { QLineEdit* scaleFactor = this->findChild("ScaleFactor"); if (scaleFactor) - { - scaleFactor->setEnabled(!checked); - } + { + scaleFactor->setEnabled(!checked); + } } void pqTableTo3DPanel::onPrsTypeChanged(const QString& type) { QWidget* numberContours = this->findChild("NumberOfContours"); if (numberContours) - { - numberContours->setEnabled(type == "Contour"); - } + { + numberContours->setEnabled(type == "Contour"); + } } diff --git a/src/Plugins/TableReader/Reader/TableParser.cxx b/src/Plugins/TableReader/Reader/TableParser.cxx index 887b42bb..b8ae1b31 100644 --- a/src/Plugins/TableReader/Reader/TableParser.cxx +++ b/src/Plugins/TableReader/Reader/TableParser.cxx @@ -33,16 +33,16 @@ int getLine(std::ifstream& streamIn, QString& str) { char tmp; std::ostringstream streamOut; - + while (streamIn.get(tmp)) { streamOut< GetTableNames(const char* fname, const char* separator, - const bool firstStringAsTitles) -{ + const bool firstStringAsTitles) + { Table2D table; std::vector tableTitles; @@ -92,20 +92,20 @@ std::vector GetTableNames(const char* fname, const char* separator, tableTitles.push_back(table.myTitle); table = GetTable(fname, separator, ++nb, firstStringAsTitles); } - + return tableTitles; -} + } Table2D GetTable(const char* fname, const char* separator, const int tableNb, - const bool firstStringAsTitles) + const bool firstStringAsTitles) { std::ifstream streamIn(fname); - + if(!streamIn.good()) - { - throw std::runtime_error("Unable to open input Post-Pro table file."); - } - + { + throw std::runtime_error("Unable to open input Post-Pro table file."); + } + QString tmp; int count = 0; do { @@ -116,145 +116,145 @@ Table2D GetTable(const char* fname, const char* separator, const int tableNb, bool isFirst = true; while (!streamIn.eof() && tmp.trimmed() != "") + { + QString data = tmp.trimmed(); + QString cmt = ""; + QString keyword = ""; + + // Split string to data and comment (comment starts from '#' symbol) + int index = tmp.indexOf("#"); + if (index >= 0) { - QString data = tmp.trimmed(); - QString cmt = ""; - QString keyword = ""; - - // Split string to data and comment (comment starts from '#' symbol) - int index = tmp.indexOf("#"); - if (index >= 0) - { - data = tmp.left(index).trimmed(); - cmt = tmp.mid(index+1).trimmed(); - } - - // If comment is not empty, try to get keyword from it (separated by ':' symbol) - if (!cmt.isEmpty()) - { - int index1 = cmt.indexOf(":"); - - if (index1 >= 0) - { - QString tmpstr = cmt.left(index1).trimmed(); - if (tmpstr == QString("TITLE") || - tmpstr == QString("COLUMN_TITLES") || - tmpstr == QString("COLUMN_UNITS") || - tmpstr == QString("COMMENT")) - { - keyword = tmpstr; - cmt = cmt.mid(index1+1).trimmed(); - } - } - } - - // If data is empty, process only comment - if (data.isEmpty()) - { - // If keyword is found, try to process it - // elsewise it is a simple comment, just ignore it - if (!keyword.isEmpty()) - { - if (keyword == QString( "TITLE" )) - { - QString title = cmt; - if (table2D.myTitle != "") { - title = QString(table2D.myTitle.c_str()) + QString(" ") + title; - } - table2D.myTitle = title.toLatin1().constData(); - } - else if (keyword == QString("COLUMN_TITLES")) - { - // Comment may contain column headers - QStringList strList = cmt.split("|", QString::SkipEmptyParts); - - for ( int i = 0; i < strList.count(); i++ ) - { - QString tmpstr = strList[i].trimmed(); - table2D.myColumnTitles.push_back(tmpstr.toLatin1().constData()); - } - } - else if (keyword == QString("COLUMN_UNITS")) - { - // Comment may contain column units - QStringList strList = cmt.split( " ", QString::SkipEmptyParts ); - - for (int i = 0; i < strList.count(); i++) - { - QString tmpstr = strList[i].trimmed(); - table2D.myColumnUnits.push_back(tmpstr.toLatin1().constData()); - } - } - else if (keyword == QString("COMMENT")) - { - // Keyword 'COMMENT' processing can be here, - // currently it is ignored - } - } - else { - // Simple comment processing can be here, - // currently it is ignored - } - } - // If data is not empty, try to process it - else { - Table2D::Row row; - - QString datar1 = data.replace(QRegExp("\t"), " "); - QStringList valList = datar1.split(separator, QString::SkipEmptyParts); - if(table2D.myColumnTitles.size() == 0 && isFirst && firstStringAsTitles) - { - for ( int i = 0; i < valList.count(); i++ ) - { - QString tmpstr = valList[i].trimmed(); - table2D.myColumnTitles.push_back(tmpstr.toLatin1().constData()); - } - } - else - { - if (!cmt.isEmpty()) - { - row.myTitle = cmt.toLatin1().constData(); - } - - for (int i = 0; i < valList.count(); i++) - { - if (valList[i].trimmed() != "") - { - Table2D::Value val = valList[i].trimmed().toLatin1().constData(); - row.myValues.push_back(val); - } - } - - if(row.myValues.size() > 0) - { - table2D.myRows.push_back(row); - } - } - - isFirst = false; - } - getLine(streamIn, tmp); + data = tmp.left(index).trimmed(); + cmt = tmp.mid(index+1).trimmed(); + } + + // If comment is not empty, try to get keyword from it (separated by ':' symbol) + if (!cmt.isEmpty()) + { + int index1 = cmt.indexOf(":"); + + if (index1 >= 0) + { + QString tmpstr = cmt.left(index1).trimmed(); + if (tmpstr == QString("TITLE") || + tmpstr == QString("COLUMN_TITLES") || + tmpstr == QString("COLUMN_UNITS") || + tmpstr == QString("COMMENT")) + { + keyword = tmpstr; + cmt = cmt.mid(index1+1).trimmed(); + } + } } - - + + // If data is empty, process only comment + if (data.isEmpty()) + { + // If keyword is found, try to process it + // elsewise it is a simple comment, just ignore it + if (!keyword.isEmpty()) + { + if (keyword == QString( "TITLE" )) + { + QString title = cmt; + if (table2D.myTitle != "") { + title = QString(table2D.myTitle.c_str()) + QString(" ") + title; + } + table2D.myTitle = title.toLatin1().constData(); + } + else if (keyword == QString("COLUMN_TITLES")) + { + // Comment may contain column headers + QStringList strList = cmt.split("|", QString::SkipEmptyParts); + + for ( int i = 0; i < strList.count(); i++ ) + { + QString tmpstr = strList[i].trimmed(); + table2D.myColumnTitles.push_back(tmpstr.toLatin1().constData()); + } + } + else if (keyword == QString("COLUMN_UNITS")) + { + // Comment may contain column units + QStringList strList = cmt.split( " ", QString::SkipEmptyParts ); + + for (int i = 0; i < strList.count(); i++) + { + QString tmpstr = strList[i].trimmed(); + table2D.myColumnUnits.push_back(tmpstr.toLatin1().constData()); + } + } + else if (keyword == QString("COMMENT")) + { + // Keyword 'COMMENT' processing can be here, + // currently it is ignored + } + } + else { + // Simple comment processing can be here, + // currently it is ignored + } + } + // If data is not empty, try to process it + else { + Table2D::Row row; + + QString datar1 = data.replace(QRegExp("\t"), " "); + QStringList valList = datar1.split(separator, QString::SkipEmptyParts); + if(table2D.myColumnTitles.size() == 0 && isFirst && firstStringAsTitles) + { + for ( int i = 0; i < valList.count(); i++ ) + { + QString tmpstr = valList[i].trimmed(); + table2D.myColumnTitles.push_back(tmpstr.toLatin1().constData()); + } + } + else + { + if (!cmt.isEmpty()) + { + row.myTitle = cmt.toLatin1().constData(); + } + + for (int i = 0; i < valList.count(); i++) + { + if (valList[i].trimmed() != "") + { + Table2D::Value val = valList[i].trimmed().toLatin1().constData(); + row.myValues.push_back(val); + } + } + + if(row.myValues.size() > 0) + { + table2D.myRows.push_back(row); + } + } + + isFirst = false; + } + getLine(streamIn, tmp); + } + + if(table2D.Check()) + { + if (count == tableNb) { - if (count == tableNb) - { - if (QString::fromStdString(table2D.myTitle).isEmpty()) - { - table2D.myTitle = QString("Table:%1").arg(tableNb).toStdString(); - } - return table2D; - } - count++; + if (QString::fromStdString(table2D.myTitle).isEmpty()) + { + table2D.myTitle = QString("Table:%1").arg(tableNb).toStdString(); + } + return table2D; } - + count++; + } + } while (!streamIn.eof()); - + streamIn.close(); - + // Return empty table Table2D emptyTable; return emptyTable; diff --git a/src/Plugins/TableReader/Reader/TableParser.h b/src/Plugins/TableReader/Reader/TableParser.h index a8dbe954..5086fdf0 100644 --- a/src/Plugins/TableReader/Reader/TableParser.h +++ b/src/Plugins/TableReader/Reader/TableParser.h @@ -46,8 +46,8 @@ struct Table2D }; std::vector GetTableNames(const char* fname, const char* separator, - const bool firstStringAsTitles); + const bool firstStringAsTitles); Table2D GetTable(const char* fname, const char* separator, const int tableNb, - const bool firstStringAsTitles); + const bool firstStringAsTitles); #endif //__TableParser_h_ diff --git a/src/Plugins/TableReader/Reader/vtkVisuTableReader.cxx b/src/Plugins/TableReader/Reader/vtkVisuTableReader.cxx index 4a5e8c9f..383eaaa1 100644 --- a/src/Plugins/TableReader/Reader/vtkVisuTableReader.cxx +++ b/src/Plugins/TableReader/Reader/vtkVisuTableReader.cxx @@ -40,13 +40,13 @@ using namespace std; vtkStandardNewMacro(vtkVisuTableReader); vtkVisuTableReader::vtkVisuTableReader(): - FileName(0) + FileName(0) { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->FileName = NULL; - + this->DetectNumericColumns = true; this->FirstStringAsTitles = false; @@ -54,7 +54,7 @@ vtkVisuTableReader::vtkVisuTableReader(): this->ValueDelimiter = 0; this->SetValueDelimiter(" "); - + this->AvailableTables = vtkStringArray::New(); } @@ -74,131 +74,131 @@ void vtkVisuTableReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "FileName: " - << (this->FileName ? this->FileName : "(none)") << endl; + << (this->FileName ? this->FileName : "(none)") << endl; os << indent << "DetectNumericColumns: " - << (this->DetectNumericColumns? "true" : "false") << endl; + << (this->DetectNumericColumns? "true" : "false") << endl; os << indent << "ValueDelimiter: " - << (this->ValueDelimiter ? this->ValueDelimiter : "(none)") << endl; + << (this->ValueDelimiter ? this->ValueDelimiter : "(none)") << endl; os << indent << "TableNumber: " << this->TableNumber<< endl; } int vtkVisuTableReader::RequestData(vtkInformation*, - vtkInformationVector**, - vtkInformationVector* outputVector) + vtkInformationVector**, + vtkInformationVector* outputVector) { vtkTable* const output_table = vtkTable::GetData(outputVector); try + { + vtkInformation* const outInfo = outputVector->GetInformationObject(0); + if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) && + outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) { - vtkInformation* const outInfo = outputVector->GetInformationObject(0); - if(outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) && - outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()) > 0) - { - return 1; - } - - // If the filename is not defined - if(!this->FileName || this->TableNumber < 0) - { - return 1; - } - - // Read table with the given number from the file - Table2D table = GetTable(this->FileName, this->ValueDelimiter, - this->TableNumber, this->FirstStringAsTitles); - - // Set table name - output_table->GetInformation()->Set(vtkDataObject::FIELD_NAME(), - table.myTitle.c_str()); - - int nbRows = table.myRows.size(); - int nbCols = table.myRows[0].myValues.size(); - - for (int col=0; col < nbCols; col++) - { - vtkStringArray* newCol = vtkStringArray::New(); - newCol->SetNumberOfValues(nbRows); - - // Set value - for (int row=0; row < nbRows; row++) - { - newCol->SetValue(row, table.myRows[row].myValues[col].c_str()); - } - - // Set title - bool hasUnit = !table.myColumnUnits[col].empty(); - - if (table.myColumnTitles[col].empty()) - { - vtksys_ios::stringstream buffer; - if (hasUnit) - { - buffer << col <<" [" << table.myColumnUnits[col].c_str() << "]"; - } - else - { - buffer << col; - } - newCol->SetName(buffer.str().c_str()); - } - else - { - if (hasUnit) - { - vtksys_ios::stringstream buffer; - buffer << table.myColumnTitles[col].c_str() - <<" [" << table.myColumnUnits[col].c_str() << "]"; - newCol->SetName(buffer.str().c_str()); - } - else - { - newCol->SetName(table.myColumnTitles[col].c_str()); - } - } - - output_table->AddColumn(newCol); - newCol->Delete(); - } - - // Detect numeric columns if needed - if (this->DetectNumericColumns) - { - vtkStringToNumeric* convertor = vtkStringToNumeric::New(); - vtkTable* clone = output_table->NewInstance(); - clone->ShallowCopy(output_table); - convertor->SetInputData(clone); - convertor->Update(); - clone->Delete(); - output_table->ShallowCopy(convertor->GetOutputDataObject(0)); - convertor->Delete(); - } - } - catch(vtksys_stl::exception& e) + return 1; + } + + // If the filename is not defined + if(!this->FileName || this->TableNumber < 0) { - vtkErrorMacro(<< "caught exception: " << e.what() << endl); - output_table->Initialize(); + return 1; } - catch(...) + + // Read table with the given number from the file + Table2D table = GetTable(this->FileName, this->ValueDelimiter, + this->TableNumber, this->FirstStringAsTitles); + + // Set table name + output_table->GetInformation()->Set(vtkDataObject::FIELD_NAME(), + table.myTitle.c_str()); + + int nbRows = table.myRows.size(); + int nbCols = table.myRows[0].myValues.size(); + + for (int col=0; col < nbCols; col++) { - vtkErrorMacro(<< "caught unknown exception." << endl); - output_table->Initialize(); + vtkStringArray* newCol = vtkStringArray::New(); + newCol->SetNumberOfValues(nbRows); + + // Set value + for (int row=0; row < nbRows; row++) + { + newCol->SetValue(row, table.myRows[row].myValues[col].c_str()); + } + + // Set title + bool hasUnit = !table.myColumnUnits[col].empty(); + + if (table.myColumnTitles[col].empty()) + { + vtksys_ios::stringstream buffer; + if (hasUnit) + { + buffer << col <<" [" << table.myColumnUnits[col].c_str() << "]"; + } + else + { + buffer << col; + } + newCol->SetName(buffer.str().c_str()); + } + else + { + if (hasUnit) + { + vtksys_ios::stringstream buffer; + buffer << table.myColumnTitles[col].c_str() + <<" [" << table.myColumnUnits[col].c_str() << "]"; + newCol->SetName(buffer.str().c_str()); + } + else + { + newCol->SetName(table.myColumnTitles[col].c_str()); + } + } + + output_table->AddColumn(newCol); + newCol->Delete(); } - + + // Detect numeric columns if needed + if (this->DetectNumericColumns) + { + vtkStringToNumeric* convertor = vtkStringToNumeric::New(); + vtkTable* clone = output_table->NewInstance(); + clone->ShallowCopy(output_table); + convertor->SetInputData(clone); + convertor->Update(); + clone->Delete(); + output_table->ShallowCopy(convertor->GetOutputDataObject(0)); + convertor->Delete(); + } + } + catch(vtksys_stl::exception& e) + { + vtkErrorMacro(<< "caught exception: " << e.what() << endl); + output_table->Initialize(); + } + catch(...) + { + vtkErrorMacro(<< "caught unknown exception." << endl); + output_table->Initialize(); + } + return 1; } vtkStringArray* vtkVisuTableReader::GetAvailableTables() { this->AvailableTables->Initialize(); - + vector titles = - GetTableNames(this->FileName, this->ValueDelimiter, - this->FirstStringAsTitles); - + GetTableNames(this->FileName, this->ValueDelimiter, + this->FirstStringAsTitles); + for(int i = 0; i < titles.size(); i++) - { - this->AvailableTables->InsertNextValue(titles[i].c_str()); - } - + { + this->AvailableTables->InsertNextValue(titles[i].c_str()); + } + return this->AvailableTables; } diff --git a/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.cxx b/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.cxx index 77c99585..3a3e0da3 100644 --- a/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.cxx +++ b/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.cxx @@ -50,152 +50,152 @@ vtkTableTo3D::~vtkTableTo3D() } int vtkTableTo3D::FillInputPortInformation( - int vtkNotUsed(port), vtkInformation* info) + int vtkNotUsed(port), vtkInformation* info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkTable"); return 1; } int vtkTableTo3D::RequestData(vtkInformation* vtkNotUsed(request), - vtkInformationVector** inputVector, vtkInformationVector* outputVector) + vtkInformationVector** inputVector, vtkInformationVector* outputVector) { vtkTable* input = vtkTable::GetData(inputVector[0], 0); vtkPolyData* output = vtkPolyData::GetData(outputVector, 0); if (input->GetNumberOfRows() == 0 ||input->GetNumberOfColumns() < 2) - { - return 1; - } - + { + return 1; + } + vtkIdType xSize = input->GetNumberOfRows(); vtkIdType ySize = input->GetNumberOfColumns() - 1; vtkIdType nbPoints = xSize * ySize; vtkDataArray* xAxis = vtkDataArray::SafeDownCast(input->GetColumn(0)); if (!xAxis) - { - vtkErrorMacro("The first column is not numeric."); - return 1; - } - + { + vtkErrorMacro("The first column is not numeric."); + return 1; + } + double xRange = xAxis->GetTuple1(xSize - 1) - xAxis->GetTuple1(0); double yDelta = xRange / ySize; - + vtkSmartPointer yAxis = - vtkSmartPointer::New(); + vtkSmartPointer::New(); yAxis->SetNumberOfValues(ySize); for (vtkIdType i = 0; i < ySize; i++ ) - { - yAxis->SetValue(i, i*yDelta); - } + { + yAxis->SetValue(i, i*yDelta); + } vtkSmartPointer points = - vtkSmartPointer::New(); + vtkSmartPointer::New(); points->SetNumberOfPoints(nbPoints); vtkSmartPointer pointsIdMapper = - vtkSmartPointer::New(); + vtkSmartPointer::New(); pointsIdMapper->SetName("POINTS_ID_MAPPER"); pointsIdMapper->SetNumberOfComponents(2); pointsIdMapper->SetNumberOfTuples(nbPoints); int *pointsIdMapperPtr = pointsIdMapper->GetPointer(0); for (vtkIdType i = 0, pntId = 0; i < ySize; i++) + { + for (vtkIdType j = 0; j < xSize; j++, pntId++) { - for (vtkIdType j = 0; j < xSize; j++, pntId++) - { - points->SetPoint(pntId, xAxis->GetTuple1(j), - yAxis->GetValue(i), - 0.0); - - *pointsIdMapperPtr++ = pntId; - *pointsIdMapperPtr++ = 0; - } + points->SetPoint(pntId, xAxis->GetTuple1(j), + yAxis->GetValue(i), + 0.0); + + *pointsIdMapperPtr++ = pntId; + *pointsIdMapperPtr++ = 0; } + } vtkSmartPointer scalars = - vtkSmartPointer::New(); + vtkSmartPointer::New(); scalars->SetNumberOfComponents(1); scalars->SetNumberOfTuples(nbPoints); double *scalarsPtr = scalars->GetPointer(0); for (vtkIdType i = 0; i < ySize; i++) + { + vtkDataArray* col = + vtkDataArray::SafeDownCast(input->GetColumn(i + 1)); + + if (!col) + { + vtkErrorMacro("Column "<< i <<"is not numeric."); + return 1; + } + + for ( vtkIdType j = 0; j < xSize; j++ ) { - vtkDataArray* col = - vtkDataArray::SafeDownCast(input->GetColumn(i + 1)); - - if (!col) - { - vtkErrorMacro("Column "<< i <<"is not numeric."); - return 1; - } - - for ( vtkIdType j = 0; j < xSize; j++ ) - { - double value = col->GetTuple1(j); - *scalarsPtr++ = value; - } + double value = col->GetTuple1(j); + *scalarsPtr++ = value; } + } vtkSmartPointer structuredGrid = - vtkSmartPointer::New(); + vtkSmartPointer::New(); structuredGrid->SetPoints(points); structuredGrid->SetDimensions(xSize, ySize, 1); // structuredGrid->GetPointData()->AddArray(pointsIdMapper); if (input->GetInformation()->Has(vtkDataObject::FIELD_NAME())) - { - scalars->SetName(input->GetInformation()->Get(vtkDataObject::FIELD_NAME())); - } + { + scalars->SetName(input->GetInformation()->Get(vtkDataObject::FIELD_NAME())); + } else - { - scalars->SetName("Table"); - } + { + scalars->SetName("Table"); + } structuredGrid->GetPointData()->SetScalars(scalars); vtkSmartPointer geomFilter = - vtkSmartPointer::New(); + vtkSmartPointer::New(); geomFilter->SetInputData(structuredGrid); geomFilter->Update(); - + vtkSmartPointer warpScalar = - vtkSmartPointer::New(); - + vtkSmartPointer::New(); + double scaleFactor = this->ScaleFactor; if (this->UseOptimusScale) + { + double range[2]; + geomFilter->GetOutput()->GetScalarRange(range); + double length = geomFilter->GetOutput()->GetLength(); + if (range[1] > 0) { - double range[2]; - geomFilter->GetOutput()->GetScalarRange(range); - double length = geomFilter->GetOutput()->GetLength(); - if (range[1] > 0) - { - scaleFactor = length / range[1] * 0.3; - } - else - { - scaleFactor = 0; - } + scaleFactor = length / range[1] * 0.3; } - - if (this->PresentationType == TABLETO3D_SURFACE) + else { - warpScalar->SetInputConnection(geomFilter->GetOutputPort(0)); - warpScalar->SetScaleFactor(scaleFactor); + scaleFactor = 0; } + } + + if (this->PresentationType == TABLETO3D_SURFACE) + { + warpScalar->SetInputConnection(geomFilter->GetOutputPort(0)); + warpScalar->SetScaleFactor(scaleFactor); + } else - { - vtkSmartPointer contourFilter = - vtkSmartPointer::New(); - contourFilter->SetInputConnection(geomFilter->GetOutputPort(0)); - contourFilter->GenerateValues(this->NumberOfContours, - geomFilter->GetOutput()->GetScalarRange()); - warpScalar->SetInputConnection(contourFilter->GetOutputPort(0)); - warpScalar->SetScaleFactor(scaleFactor); - } + { + vtkSmartPointer contourFilter = + vtkSmartPointer::New(); + contourFilter->SetInputConnection(geomFilter->GetOutputPort(0)); + contourFilter->GenerateValues(this->NumberOfContours, + geomFilter->GetOutput()->GetScalarRange()); + warpScalar->SetInputConnection(contourFilter->GetOutputPort(0)); + warpScalar->SetScaleFactor(scaleFactor); + } warpScalar->Update(); output->ShallowCopy(warpScalar->GetPolyDataOutput()); - + return 1; } @@ -206,9 +206,9 @@ void vtkTableTo3D::PrintSelf(ostream& os, vtkIndent indent) os << indent << "ScaleFactor: " << this->ScaleFactor << endl; os << indent << "UseOptimusScale: " - << (this->UseOptimusScale? "true" : "false") << endl; + << (this->UseOptimusScale? "true" : "false") << endl; os << indent << "PresentationType: " - << ((this->PresentationType == TABLETO3D_SURFACE)? "Surface" : "Contour") - << endl; + << ((this->PresentationType == TABLETO3D_SURFACE)? "Surface" : "Contour") + << endl; os << indent << "NumberOfContours: " << this->NumberOfContours << endl; } diff --git a/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.h b/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.h index 8afdd412..dca55b55 100644 --- a/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.h +++ b/src/Plugins/TableReader/TableTo3DFilter/vtkTableTo3D.h @@ -47,7 +47,7 @@ public: // Description: // Specify type of presentation: surface of contour. vtkSetClampMacro(PresentationType, int, - TABLETO3D_SURFACE, TABLETO3D_CONTOUR); + TABLETO3D_SURFACE, TABLETO3D_CONTOUR); vtkGetMacro(PresentationType, int); // Description: -- 2.30.2 From 137da6515933db160a26aded31138f2474f53634 Mon Sep 17 00:00:00 2001 From: rnv Date: Fri, 4 Oct 2013 14:04:09 +0000 Subject: [PATCH 02/16] Implementation of the "0021709: [CEA 583] Toolbar preferences" issue. --- resources/SalomeApp.xml.in | 6 +++ src/PVGUI/PVGUI_Module.cxx | 4 ++ src/PVGUI/PVGUI_Module.h | 9 ++++ src/PVGUI/PVGUI_Module_widgets.cxx | 69 ++++++++++++++++++++++++++++++ 4 files changed, 88 insertions(+) diff --git a/resources/SalomeApp.xml.in b/resources/SalomeApp.xml.in index 7ac28971..3b41bfc5 100644 --- a/resources/SalomeApp.xml.in +++ b/resources/SalomeApp.xml.in @@ -45,4 +45,10 @@
+
+ +
+
+ +
diff --git a/src/PVGUI/PVGUI_Module.cxx b/src/PVGUI/PVGUI_Module.cxx index 70b4b50f..5aa1d7b9 100644 --- a/src/PVGUI/PVGUI_Module.cxx +++ b/src/PVGUI/PVGUI_Module.cxx @@ -861,6 +861,8 @@ bool PVGUI_Module::activateModule( SUIT_Study* study ) SUIT_ExceptionHandler::addCleanUpRoutine( paravisCleanUp ); + storeCommonWindowsState(); + bool isDone = SalomeApp_Module::activateModule( study ); if ( !isDone ) return false; @@ -951,6 +953,8 @@ bool PVGUI_Module::deactivateModule( SUIT_Study* study ) if (myOldMsgHandler) qInstallMsgHandler(myOldMsgHandler); + restoreCommonWindowsState(); + return SalomeApp_Module::deactivateModule( study ); } diff --git a/src/PVGUI/PVGUI_Module.h b/src/PVGUI/PVGUI_Module.h index 90c33146..b56bf235 100644 --- a/src/PVGUI/PVGUI_Module.h +++ b/src/PVGUI/PVGUI_Module.h @@ -211,6 +211,12 @@ private: //! update macros state void updateMacros(); + //! store visibility of the common dockable windows (OB, PyConsole, ... etc.) + void storeCommonWindowsState(); + + //! restore visibility of the common dockable windows (OB, PyConsole, ... etc.) + void restoreCommonWindowsState(); + private slots: void showHelpForProxy( const QString&, const QString& ); @@ -273,6 +279,9 @@ private: WgMap myToolbarBreaks; QList myMenus; + typedef QMap DockWindowMap; + DockWindowMap myCommonMap; + QStringList myTemporaryFiles; QtMsgHandler myOldMsgHandler; diff --git a/src/PVGUI/PVGUI_Module_widgets.cxx b/src/PVGUI/PVGUI_Module_widgets.cxx index 58189278..455c282a 100644 --- a/src/PVGUI/PVGUI_Module_widgets.cxx +++ b/src/PVGUI/PVGUI_Module_widgets.cxx @@ -26,6 +26,7 @@ #include #include +#include #include #include @@ -342,3 +343,71 @@ void PVGUI_Module::restoreDockWidgetsState() tb->toggleViewAction()->setVisible( true ); } } + + + +/*! + \brief Store visibility of the common dockable windows (OB, PyConsole, ... etc.) +*/ +void PVGUI_Module::storeCommonWindowsState() { + //rnv: Make behaviour of the dockable windows and toolbars coherent with others + // modules: if 'Save position of the windows' or 'Save position of the toolbars' + // in the General SALOME preferences are cheked, then properties of the windows and/or toolbars + // are stored/restored using standard Qt saveState(...) and restoreState(...) methods. + // Otherwise to the windows and toolbars applied default settins stored int the SalomeApp.xml + // configuration file. + // + // But in contrast to others modules ParaVis module default settings hide some dockable + // windows, so to restore it at the moment of the ParaVis de-activation we call + // restoreCommonWindowsState() method, and at the moment of the ParaVis activation we call + // this method. + + SalomeApp_Application* anApp = getApp(); + if(!anApp) + return; + + int begin = SalomeApp_Application::WT_ObjectBrowser; + int end = SalomeApp_Application::WT_NoteBook; + for( int i = begin; i <= end; i++ ) { + QWidget* wg = anApp->getWindow(i); + if(wg) { + QDockWidget* dock = 0; + QWidget* w = wg->parentWidget(); + while ( w && !dock ) { + dock = ::qobject_cast( w ); + w = w->parentWidget(); + } + if(dock){ + if(!myCommonMap.contains(i)){ + myCommonMap.insert(i,dock->isVisible()); + } else { + myCommonMap[i] = dock->isVisible(); + } + } + } + } +} + +/*! + \brief Restore visibility of the common dockable windows (OB, PyConsole, ... etc.) +*/ +void PVGUI_Module::restoreCommonWindowsState() { + SalomeApp_Application* anApp = getApp(); + if(!anApp) + return; + DockWindowMap::const_iterator it = myCommonMap.begin(); + for( ;it != myCommonMap.end(); it++ ) { + QWidget* wg = anApp->getWindow(it.key()); + if(wg) { + QDockWidget* dock = 0; + QWidget* w = wg->parentWidget(); + while ( w && !dock ) { + dock = ::qobject_cast( w ); + w = w->parentWidget(); + } + if(dock) { + dock->setVisible(it.value()); + } + } + } +} -- 2.30.2 From 895d61232e0037a500b269315b88c63140b37b37 Mon Sep 17 00:00:00 2001 From: rnv Date: Tue, 8 Oct 2013 15:24:59 +0000 Subject: [PATCH 03/16] Fix remarks related to the "0021709: [CEA 583] Toolbar preferences" issue. --- resources/SalomeApp.xml.in | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/resources/SalomeApp.xml.in b/resources/SalomeApp.xml.in index 3b41bfc5..96a187f9 100644 --- a/resources/SalomeApp.xml.in +++ b/resources/SalomeApp.xml.in @@ -46,9 +46,9 @@
- +
- +
-- 2.30.2 From 0abec28f55a64e8215742e9b02f955d161a8b865 Mon Sep 17 00:00:00 2001 From: bruneton Date: Mon, 21 Oct 2013 09:52:54 +0000 Subject: [PATCH 04/16] CMake: porting module to the new CMake procedure. Isolated as much as possible IDL wrapping logic. Introduced flag SALOME_PARAVIS_MINIMAL_CORBA to turn the wrapping off. --- CMakeLists.txt | 330 ++++++++++++------ SalomePARAVISConfig.cmake.in | 112 ++++++ adm_local/cmake_files/CMakeLists.txt | 6 +- bin/CMakeLists.txt | 2 +- idl/CMakeLists.txt | 143 ++------ idl/PARAVIS_Gen.idl | 2 + idl/wrap.cmake | 10 +- resources/CMakeLists.txt | 6 +- src/CMakeLists.txt | 25 +- src/ENGINE/CMakeLists.txt | 29 +- src/ENGINE/PARAVIS_Engine_i.cc | 2 + src/ENGINE/PARAVIS_Engine_i.hh | 3 +- src/Macro/CMakeLists.txt | 12 +- src/PVGUI/CMakeLists.txt | 330 +++++++----------- src/PVGUI/PARAVIS_Gen_i.cc | 9 +- src/PVGUI/PARAVIS_Gen_i.hh | 2 + src/PV_SWIG/CMakeLists.txt | 27 +- src/Plugins/CMakeLists.txt | 15 +- src/VTKParser/CMakeLists.txt | 113 ++++++ .../VTKParser/GenerateWrapList.cmake | 6 +- src/{PVGUI => VTKParser}/create_class.py | 0 src/{PVGUI => VTKParser}/create_class.sh | 0 .../VTKParser/getwrapclasses.py | 0 src/VTKParser/readme.txt | 3 + src/{PVGUI => VTKParser}/wrap.cmake | 23 +- src/VTKWrapping/CMakeLists.txt | 113 ++++++ test/CMakeLists.txt | 23 +- test/VisuPrs/CMakeLists.txt | 45 +-- 28 files changed, 864 insertions(+), 527 deletions(-) create mode 100644 SalomePARAVISConfig.cmake.in create mode 100644 src/VTKParser/CMakeLists.txt rename wrapfiles.cmake => src/VTKParser/GenerateWrapList.cmake (80%) rename src/{PVGUI => VTKParser}/create_class.py (100%) rename src/{PVGUI => VTKParser}/create_class.sh (100%) rename getwrapclasses.py => src/VTKParser/getwrapclasses.py (100%) create mode 100644 src/VTKParser/readme.txt rename src/{PVGUI => VTKParser}/wrap.cmake (82%) create mode 100644 src/VTKWrapping/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index 906d2579..d7c67868 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,47 +16,105 @@ # # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # - -PROJECT(PARAVIS C CXX) +CMAKE_MINIMUM_REQUIRED(VERSION 2.8.8 FATAL_ERROR) +PROJECT(SalomePARAVIS C CXX) IF(WINDOWS) STRING( REPLACE "INCREMENTAL:YES" "INCREMENTAL:NO" replacementFlags ${CMAKE_SHARED_LINKER_FLAGS_DEBUG} ) SET( CMAKE_SHARED_LINKER_FLAGS_DEBUG "${replacementFlags}" ) ENDIF(WINDOWS) -CMAKE_MINIMUM_REQUIRED(VERSION 2.8.7 FATAL_ERROR) -IF(COMMAND cmake_policy) - cmake_policy(SET CMP0003 NEW) -ENDIF(COMMAND cmake_policy) +# Ensure a proper linker behavior: +CMAKE_POLICY(SET CMP0003 NEW) + +# Versioning +# =========== +# Project name, upper case +STRING(TOUPPER ${PROJECT_NAME} PROJECT_NAME_UC) + +SET(${PROJECT_NAME_UC}_MAJOR_VERSION 7) +SET(${PROJECT_NAME_UC}_MINOR_VERSION 2) +SET(${PROJECT_NAME_UC}_PATCH_VERSION 0) +SET(${PROJECT_NAME_UC}_VERSION + ${${PROJECT_NAME_UC}_MAJOR_VERSION}.${${PROJECT_NAME_UC}_MINOR_VERSION}.${${PROJECT_NAME_UC}_PATCH_VERSION}) +SET(${PROJECT_NAME_UC}_VERSION_DEV 1) + +# Find KERNEL +# =========== +SET(KERNEL_ROOT_DIR $ENV{KERNEL_ROOT_DIR} CACHE PATH "Path to the Salome KERNEL") +IF(EXISTS ${KERNEL_ROOT_DIR}) + LIST(APPEND CMAKE_MODULE_PATH "${KERNEL_ROOT_DIR}/salome_adm/cmake_files") + INCLUDE(SalomeMacros) + FIND_PACKAGE(SalomeKERNEL REQUIRED) + ADD_DEFINITIONS(${KERNEL_DEFINITIONS}) + INCLUDE_DIRECTORIES(${KERNEL_INCLUDE_DIRS}) +ELSE(EXISTS ${KERNEL_ROOT_DIR}) + MESSAGE(FATAL_ERROR "We absolutely need a Salome KERNEL, please define KERNEL_ROOT_DIR") +ENDIF(EXISTS ${KERNEL_ROOT_DIR}) + +# Platform setup +# ============== +INCLUDE(SalomeSetupPlatform) # From KERNEL +# Always build libraries as shared objects: +SET(BUILD_SHARED_LIBS TRUE) +# Local macros: +LIST(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/adm_local/cmake_files") + +# Detect GUI root dir (but doesn't find GUI yet! See below) +# =================== +SET(GUI_ROOT_DIR $ENV{GUI_ROOT_DIR} CACHE PATH "Path to the Salome GUI") +IF(EXISTS ${GUI_ROOT_DIR}) + LIST(APPEND CMAKE_MODULE_PATH "${GUI_ROOT_DIR}/adm_local/cmake_files") +ELSE() + MESSAGE(FATAL_ERROR "We absolutely need a Salome GUI, please define GUI_ROOT_DIR") +ENDIF() + -SET(KERNEL_ROOT_DIR $ENV{KERNEL_ROOT_DIR} CACHE PATH "KERNEL_ROOT_DIR") -SET(GUI_ROOT_DIR $ENV{GUI_ROOT_DIR} CACHE PATH "GUI_ROOT_DIR") -SET(MODULE PARAVIS) +# User options +# (some options have already been defined in KERNEL) +# ============ +OPTION(SALOME_BUILD_DOC "Generate SALOME GUI documentation" ${SALOME_BUILD_DOC}) +OPTION(SALOME_BUILD_TESTS "Build SALOME tests" ${SALOME_BUILD_TESTS}) +OPTION(SALOME_PARAVIS_MINIMAL_CORBA "Build PARAVIS with a minimal CORBA interface" OFF) +OPTION(SALOME_PARAVIS_BUILD_PLUGINS "Build PARAVIS plugins (MEDReader, etc ...)" ON) -SET(CMAKE_MODULE_PATH - "${KERNEL_ROOT_DIR}/salome_adm/cmake_files" - "${GUI_ROOT_DIR}/adm_local/cmake_files" - "${PROJECT_SOURCE_DIR}/adm_local/cmake_files") -INCLUDE(SalomeMacros) -INCLUDE(SalomeSetupPlatform) +# Prerequisites +# ============= +# Find "big" prerequisites first - they reference themselves many others +# -> this can help finding the smaller prerequisites and detect conficts. +# In our case KERNEL has already loaded many prereq which are also used in GUI: -FIND_PACKAGE(SalomeKERNEL REQUIRED) +## +## From KERNEL: +## -# From KERNEL: FIND_PACKAGE(SalomePython REQUIRED) -FIND_PACKAGE(SalomeOmniORB REQUIRED) -FIND_PACKAGE(SalomeOmniORBPy REQUIRED) -SET(OMNIORB_IDL_PYTHON ${OMNIORB_IDL_COMPILER}) -FIND_PACKAGE(SalomePThread REQUIRED) FIND_PACKAGE(SalomeHDF5 REQUIRED) -FIND_PACKAGE(SalomeBoost REQUIRED) -FIND_PACKAGE(SalomeLibXml2 REQUIRED) FIND_PACKAGE(SalomeSWIG REQUIRED) -FIND_PACKAGE(SalomeCppUnit REQUIRED) -FIND_PACKAGE(SalomeDoxygen REQUIRED) -# From GUI: part 1 (Qt must be checked before ParaView) +IF(NOT SALOME_LIGHT_ONLY) + FIND_PACKAGE(SalomeOmniORB REQUIRED) + FIND_PACKAGE(SalomeOmniORBPy REQUIRED) +ENDIF() + +#IF(SALOME_BUILD_TESTS) +# ENABLE_TESTING() +# FIND_PACKAGE(SalomeCppUnit) +# SALOME_LOG_OPTIONAL_PACKAGE(CppUnit SALOME_BUILD_TESTS) +#ENDIF() +IF(SALOME_BUILD_DOC) + FIND_PACKAGE(SalomeDoxygen) + FIND_PACKAGE(SalomeGraphviz) + FIND_PACKAGE(SalomeSphinx) + SALOME_LOG_OPTIONAL_PACKAGE(Doxygen SALOME_BUILD_DOC) + SALOME_LOG_OPTIONAL_PACKAGE(Graphviz SALOME_BUILD_DOC) + SALOME_LOG_OPTIONAL_PACKAGE(Sphinx SALOME_BUILD_DOC) +ENDIF() + +## +## From GUI: part 1 (Qt must be checked before ParaView) +## FIND_PACKAGE(SalomeQt4 REQUIRED COMPONENTS QtCore QtGui QtXml QtHelp) # This search for qhelpgenerator is required here # to avoid detecting native one due to bug in ParaViewMacros.cmake @@ -67,91 +125,149 @@ FIND_PROGRAM(QT_HELP_GENERATOR DOC "qhelpgenerator used to compile Qt help project files") MARK_AS_ADVANCED(QT_HELP_GENERATOR) -# Specific to ParaVis: -FIND_PACKAGE(SalomeParaView) +## +## Specific to ParaViS: +## +FIND_PACKAGE(SalomeParaView REQUIRED) -# GUI has to be loaded AFTER ParaView: the ParaView config doesn't mix +# GUI itself has to be loaded AFTER ParaView: the ParaView config doesn't mix # well with the VTK one (and GUI loads VTK): FIND_PACKAGE(SalomeGUI REQUIRED) +ADD_DEFINITIONS(${GUI_DEFINITIONS}) +INCLUDE_DIRECTORIES(${GUI_INCLUDE_DIRS}) -# From GUI: part 2 +## +## From GUI: part 2 +## FIND_PACKAGE(SalomeCAS REQUIRED) -FIND_PACKAGE(SalomeOpenGL REQUIRED) -FIND_PACKAGE(SalomeVTK REQUIRED) -FIND_PACKAGE(SalomeQwt REQUIRED) -FIND_PACKAGE(SalomeSIP REQUIRED) -FIND_PACKAGE(SalomePyQt4 REQUIRED) - -SET(VERSION_MAJOR 7) -SET(VERSION_MINOR 2) -SET(VERSION_MAINTENANCE 0) -SET(VERSION "${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MAINTENANCE}") -SET(XVERSION 0x0${VERSION_MAJOR}0${VERSION_MINOR}0${VERSION_MAINTENANCE}) -SET(VERSION_DEV 0) - -SET(BUILD_PLUGINS 1) - -#SET(VISU_ROOT_DIR $ENV{VISU_ROOT_DIR} CACHE PATH "VISU_ROOT_DIR") -#IF(EXISTS ${VISU_ROOT_DIR}/adm_local/cmake_files/FindVISU.cmake) - #INCLUDE(${VISU_ROOT_DIR}/adm_local/cmake_files/FindVISU.cmake) - #SET(WITH_VISU 1) -#ENDIF(EXISTS ${VISU_ROOT_DIR}/adm_local/cmake_files/FindVISU.cmake) - -SET(MED_ROOT_DIR "$ENV{MED_ROOT_DIR}" CACHE PATH "Path to the MED Salome module") -LIST(APPEND CMAKE_MODULE_PATH "${MED_ROOT_DIR}/adm_local/cmake_files") -FIND_PACKAGE(SalomeMED REQUIRED) -FIND_PACKAGE(SalomeMEDFile REQUIRED) - -# TODO: the below requires ParaView in the PYTHONPATH ... not so nice: -MESSAGE(STATUS "Generating list of wrapped VTK classes ...") -LIST(GET PARAVIEW_INCLUDE_DIRS 0 PARAVIEW_INCLUDE_DIR0) -EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/getwrapclasses.py ${PARAVIEW_INCLUDE_DIR0} - RESULT_VARIABLE _res) -IF(NOT _res EQUAL 0) - MESSAGE(FATAL_ERROR "Unable to run the Python script retrieving the list of VTK classes.") + +## +## From MED +## +IF(SALOME_PARAVIS_BUILD_PLUGINS) + SET(MED_ROOT_DIR $ENV{MED_ROOT_DIR} CACHE PATH "Path to the Salome MED module") + IF(EXISTS ${MED_ROOT_DIR}) + LIST(APPEND CMAKE_MODULE_PATH "${MED_ROOT_DIR}/adm_local/cmake_files") + FIND_PACKAGE(SalomeMED REQUIRED) # Should load MEDFile too + ELSE() + MESSAGE(FATAL_ERROR "We absolutely need the Salome MED module to build plugins, please define MED_ROOT_DIR") + ENDIF() +ENDIF() + +## Detection summary: +SALOME_PACKAGE_REPORT_AND_CHECK() + +# Directories +# (default values taken from KERNEL) +# =========== +SET(SALOME_INSTALL_BINS "${SALOME_INSTALL_BINS}" CACHE PATH "Install path: SALOME binaries") +SET(SALOME_INSTALL_LIBS "${SALOME_INSTALL_LIBS}" CACHE PATH "Install path: SALOME libs") +SET(SALOME_INSTALL_IDLS "${SALOME_INSTALL_IDLS}" CACHE PATH "Install path: SALOME IDL files") +SET(SALOME_INSTALL_HEADERS "${SALOME_INSTALL_HEADERS}" CACHE PATH "Install path: SALOME headers") +SET(SALOME_INSTALL_SCRIPT_SCRIPTS "${SALOME_INSTALL_SCRIPT_SCRIPTS}" CACHE PATH + "Install path: SALOME scripts") +SET(SALOME_INSTALL_SCRIPT_DATA "${SALOME_INSTALL_SCRIPT_DATA}" CACHE PATH + "Install path: SALOME script data") +SET(SALOME_INSTALL_SCRIPT_PYTHON "${SALOME_INSTALL_SCRIPT_PYTHON}" CACHE PATH + "Install path: SALOME Python scripts") +SET(SALOME_INSTALL_PYTHON "${SALOME_INSTALL_PYTHON}" CACHE PATH "Install path: SALOME Python stuff") +SET(SALOME_INSTALL_PYTHON_SHARED "${SALOME_INSTALL_PYTHON_SHARED}" CACHE PATH + "Install path: SALOME Python shared modules") +SET(SALOME_INSTALL_CMAKE "${SALOME_INSTALL_CMAKE}" CACHE PATH "Install path: SALOME CMake files") +SET(SALOME_INSTALL_CMAKE_LOCAL "${SALOME_INSTALL_CMAKE_LOCAL}" CACHE PATH + "Install path: local SALOME CMake files") +SET(SALOME_INSTALL_AMCONFIG_LOCAL "${SALOME_INSTALL_AMCONFIG_LOCAL}" CACHE PATH + "Install path: local SALOME config files (obsolete, to be removed)") + +SET(SALOME_INSTALL_RES "${SALOME_INSTALL_RES}" CACHE PATH "Install path: SALOME resources") +SET(SALOME_INSTALL_DOC "${SALOME_INSTALL_DOC}" CACHE PATH "Install path: SALOME documentation") + +# Specific to PARAVIS: +SET(SALOME_PARAVIS_INSTALL_RES_DATA "${SALOME_INSTALL_RES}/paravis" CACHE PATH "Install path: SALOME PARAVIS specific data") + +MARK_AS_ADVANCED(SALOME_INSTALL_BINS SALOME_INSTALL_LIBS SALOME_INSTALL_IDLS SALOME_INSTALL_HEADERS) +MARK_AS_ADVANCED(SALOME_INSTALL_SCRIPT_SCRIPTS SALOME_INSTALL_SCRIPT_DATA SALOME_INSTALL_SCRIPT_PYTHON) +MARK_AS_ADVANCED(SALOME_INSTALL_APPLISKEL_SCRIPTS SALOME_INSTALL_APPLISKEL_PYTHON SALOME_INSTALL_CMAKE SALOME_INSTALL_CMAKE_LOCAL SALOME_INSTALL_RES) +MARK_AS_ADVANCED(SALOME_INSTALL_PYTHON SALOME_INSTALL_PYTHON_SHARED) +MARK_AS_ADVANCED(SALOME_INSTALL_AMCONFIG_LOCAL SALOME_INSTALL_DOC SALOME_PARAVIS_INSTALL_RES_DATA) + +# Sources +# ======== +ADD_SUBDIRECTORY(src) + +IF(NOT SALOME_LIGHT_ONLY) + ADD_SUBDIRECTORY(idl) # Order matters when using the wrapping - to be added AFTER src +ENDIF() + +ADD_SUBDIRECTORY(adm_local) +ADD_SUBDIRECTORY(resources) + +IF(SALOME_BUILD_DOC) + ADD_SUBDIRECTORY(doc) ENDIF() +ADD_SUBDIRECTORY(bin) + +# Header configuration +# ==================== +SALOME_XVERSION(${PROJECT_NAME}) +SALOME_CONFIGURE_FILE(PARAVIS_version.h.in PARAVIS_version.h INSTALL ${SALOME_INSTALL_HEADERS}) + +# Configuration export +# (here only the level 1 prerequisites are exposed) +# ==================== +INCLUDE(CMakePackageConfigHelpers) + +# List of targets in this project we want to make visible to the rest of the world. +# They all have to be INSTALL'd with the option "EXPORT ${PROJECT_NAME}TargetGroup" +SET(_${PROJECT_NAME}_exposed_targets + SalomeIDLPARAVIS PARAVIS PARAVISEngine +) + +# Add all targets to the build-tree export set +EXPORT(TARGETS ${_${PROJECT_NAME}_exposed_targets} + FILE ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Targets.cmake) + +# Create the configuration files: +# - in the build tree: + +# Ensure the variables are always defined for the configure: +SET(SIP_ROOT_DIR "${SIP_ROOT_DIR}") +SET(QT4_ROOT_DIR "${QT4_ROOT_DIR}") +SET(PYQT4_ROOT_DIR "${PYQT4_ROOT_DIR}") +SET(CAS_ROOT_DIR "${CAS_ROOT_DIR}") +SET(OPENGL_ROOT_DIR "${OPENGL_ROOT_DIR}") +SET(VTK_ROOT_DIR "${VTK_ROOT_DIR}") +SET(QWT_ROOT_DIR "${QWT_ROOT_DIR}") + +SET(CONF_INCLUDE_DIRS "${PROJECT_SOURCE_DIR}/include" "${PROJECT_BINARY_DIR}/include") +CONFIGURE_PACKAGE_CONFIG_FILE(${PROJECT_NAME}Config.cmake.in + ${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake + INSTALL_DESTINATION "${SALOME_INSTALL_CMAKE_LOCAL}" + PATH_VARS CONF_INCLUDE_DIRS SALOME_INSTALL_CMAKE_LOCAL CMAKE_INSTALL_PREFIX + KERNEL_ROOT_DIR SIP_ROOT_DIR QT4_ROOT_DIR PYQT4_ROOT_DIR CAS_ROOT_DIR + OPENGL_ROOT_DIR VTK_ROOT_DIR QWT_ROOT_DIR) + +# - in the install tree (VSR 16/08/2013: TEMPORARILY COMMENT THIS - TO REMOVE?): +# Get the relative path of the include directory so +# we can register it in the generated configuration files: +#SET(CONF_INCLUDE_DIRS "${CMAKE_INSTALL_PREFIX}/${INSTALL_INCLUDE_DIR}") +#CONFIGURE_PACKAGE_CONFIG_FILE(adm_local/cmake_files/${PROJECT_NAME}Config.cmake.in +# ${PROJECT_BINARY_DIR}/to_install/${PROJECT_NAME}Config.cmake +# INSTALL_DESTINATION "${SALOME_INSTALL_CMAKE_LOCAL}" +# PATH_VARS CONF_INCLUDE_DIRS SALOME_INSTALL_CMAKE_LOCAL CMAKE_INSTALL_PREFIX +# KERNEL_ROOT_DIR SIP_ROOT_DIR QT4_ROOT_DIR PYQT4_ROOT_DIR CAS_ROOT_DIR +# OPENGL_ROOT_DIR VTK_ROOT_DIR QWT_ROOT_DIR) + +WRITE_BASIC_PACKAGE_VERSION_FILE(${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake + VERSION ${${PROJECT_NAME_UC}_VERSION} + COMPATIBILITY AnyNewerVersion) + +# Install the CMake configuration files: +INSTALL(FILES + "${PROJECT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" + "${PROJECT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" + DESTINATION "${SALOME_INSTALL_CMAKE_LOCAL}") -SET(SUBDIRS - idl - adm_local - resources - src - doc - bin - ) - -SET(DISTCLEANFILES - wrapfiles.txt - ) - -INCLUDE(wrapfiles.cmake) - -SET(input ${CMAKE_CURRENT_SOURCE_DIR}/PARAVIS_version.h.in) -SET(output ${CMAKE_CURRENT_BINARY_DIR}/PARAVIS_version.h) - -MESSAGE(STATUS "Creation of ${output}") -CONFIGURE_FILE(${input} ${output}) - -FOREACH(dir ${SUBDIRS}) - ADD_SUBDIRECTORY(${dir}) -ENDFOREACH(dir ${SUBDIRS}) - -# Reset CMAKE_CONFIGURATION_TYPES to the good value defined by CMAKE_BUILD_TYPE -IF(CMAKE_BUILD_TYPE) - IF(WINDOWS) - MARK_AS_ADVANCED(CLEAR CMAKE_CONFIGURATION_TYPES) - SET(CMAKE_CONFIGURATION_TYPES ${CMAKE_BUILD_TYPE} CACHE STRING "compilation types" FORCE) - ENDIF(WINDOWS) -ENDIF(CMAKE_BUILD_TYPE) - -INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/PARAVIS_version.h DESTINATION include/salome) - -# Configure Testing -OPTION(BUILD_TESTING "Build ParaVis Testing" ON) -IF(BUILD_TESTING) - SET(PARAVIS_TEST_DIR ${ParaVis_BINARY_DIR}/Test/Temporary) - MAKE_DIRECTORY(${PARAVIS_TEST_DIR}) # TODO: replace with FILE(MAKE_DIRECTORY ...) - ENABLE_TESTING() - INCLUDE (CTest) - ADD_SUBDIRECTORY(test) -ENDIF(BUILD_TESTING) +# Install the export set for use with the install-tree +INSTALL(EXPORT ${PROJECT_NAME}TargetGroup DESTINATION "${SALOME_INSTALL_CMAKE_LOCAL}" + FILE ${PROJECT_NAME}Targets.cmake) diff --git a/SalomePARAVISConfig.cmake.in b/SalomePARAVISConfig.cmake.in new file mode 100644 index 00000000..0266beb6 --- /dev/null +++ b/SalomePARAVISConfig.cmake.in @@ -0,0 +1,112 @@ +# - Config file for the @PROJECT_NAME@ package +# It defines the following variables. +# Specific to the pacakge @PROJECT_NAME@ itself: +# @PROJECT_NAME_UC@_ROOT_DIR_EXP - the root path of the installation providing this CMake file +# + +############################################################### +# Copyright (C) 2007-2013 CEA/DEN, EDF R&D, OPEN CASCADE +# +# Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, +# CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or +# email : webmaster.salome@opencascade.com +############################################################### + +### Initialisation performed by CONFIGURE_PACKAGE_CONFIG_FILE: +@PACKAGE_INIT@ + +# Load the dependencies for the libraries of @PROJECT_NAME@ +# (contains definitions for IMPORTED targets). This is only +# imported if we are not built as a subproject (in this case targets are already there) +IF(NOT TARGET Event AND NOT @PROJECT_NAME@_BINARY_DIR) + INCLUDE("@PACKAGE_SALOME_INSTALL_CMAKE_LOCAL@/@PROJECT_NAME@Targets.cmake") +ENDIF() + +# Package root dir: +SET_AND_CHECK(PARAVIS_ROOT_DIR_EXP "@PACKAGE_CMAKE_INSTALL_PREFIX@") + +# Include directories +SET_AND_CHECK(PARAVIS_INCLUDE_DIRS "${PARAVIS_ROOT_DIR_EXP}/@SALOME_INSTALL_HEADERS@") +SET(PARAVIS_INCLUDE_DIRS "${PARAVIS_INCLUDE_DIRS};@_SalomePARAVIS_EXTRA_HEADERS@") +SET(PARAVIS_DEFINITIONS "@KERNEL_DEFINITIONS@") + +#### Now the specificities + +# Options exported by the package: +SET(SALOME_BUILD_DOC @SALOME_BUILD_DOC@) +SET(SALOME_BUILD_TESTS @SALOME_BUILD_TESTS@) +SET(SALOME_LIGHT_ONLY @SALOME_LIGHT_ONLY@) + +# Advanced options +SET(SALOME_USE_OCCVIEWER @SALOME_USE_OCCVIEWER@) +SET(SALOME_USE_GLVIEWER @SALOME_USE_GLVIEWER@) +SET(SALOME_USE_VTKVIEWER @SALOME_USE_VTKVIEWER@) +SET(SALOME_USE_PLOT2DVIEWER @SALOME_USE_PLOT2DVIEWER@) + +# Level 1 prerequisites: +SET_AND_CHECK(KERNEL_ROOT_DIR_EXP "@PACKAGE_KERNEL_ROOT_DIR@") +SET_AND_CHECK(SIP_ROOT_DIR_EXP "@PACKAGE_SIP_ROOT_DIR@") +SET_AND_CHECK(QT4_ROOT_DIR_EXP "@PACKAGE_QT4_ROOT_DIR@") +SET_AND_CHECK(PYQT4_ROOT_DIR_EXP "@PACKAGE_PYQT4_ROOT_DIR@") + +# Optional level 1 prerequisites: + +# For all prerequisites, load the corresponding targets if the package was used +# in CONFIG mode. This ensures dependent projects link correctly +# without having to set LD_LIBRARY_PATH: +SET(_PREREQ ) +SET(_PREREQ_CONFIG_DIR ) +LIST(LENGTH _PREREQ_CONFIG_DIR _list_len) +# Another CMake stupidity - FOREACH(... RANGE r) generates r+1 numbers ... +MATH(EXPR _range "${_list_len}-1") +FOREACH(_p RANGE ${_range}) + LIST(GET _PREREQ ${_p} _pkg ) + LIST(GET _PREREQ_CONFIG_DIR ${_p} _pkg_dir) + IF(_pkg_dir) + MESSAGE(STATUS "===> Reloading targets from ${_pkg} ...") + FIND_PACKAGE(${_pkg} REQUIRED NO_MODULE + PATHS "${_pkg_dir}" + NO_DEFAULT_PATH) + ENDIF() +ENDFOREACH() + +# Installation directories +SET(SALOME_INSTALL_BINS "@SALOME_INSTALL_BINS@") +SET(SALOME_INSTALL_LIBS "@SALOME_INSTALL_LIBS@") +SET(SALOME_INSTALL_IDLS "@SALOME_INSTALL_IDLS@") +SET(SALOME_INSTALL_HEADERS "@SALOME_INSTALL_HEADERS@") +SET(SALOME_INSTALL_SCRIPT_SCRIPTS "@SALOME_INSTALL_SCRIPT_SCRIPTS@") +SET(SALOME_INSTALL_SCRIPT_DATA "@SALOME_INSTALL_SCRIPT_DATA@") +SET(SALOME_INSTALL_SCRIPT_PYTHON "@SALOME_INSTALL_SCRIPT_PYTHON@") +SET(SALOME_INSTALL_APPLISKEL_SCRIPTS "@SALOME_INSTALL_APPLISKEL_SCRIPTS@") +SET(SALOME_INSTALL_APPLISKEL_PYTHON "@SALOME_INSTALL_APPLISKEL_PYTHON@") +SET(SALOME_INSTALL_CMAKE "@SALOME_INSTALL_CMAKE@") +SET(SALOME_INSTALL_CMAKE_LOCAL "@SALOME_INSTALL_CMAKE_LOCAL@") +SET(SALOME_INSTALL_PYTHON "@SALOME_INSTALL_PYTHON@") +SET(SALOME_INSTALL_PYTHON_SHARED "@SALOME_INSTALL_PYTHON_SHARED@") +SET(SALOME_INSTALL_RES "@SALOME_INSTALL_RES@") +SET(SALOME_INSTALL_DOC "@SALOME_INSTALL_DOC@") +SET(SALOME_INSTALL_AMCONFIG_LOCAL "@SALOME_INSTALL_AMCONFIG_LOCAL@") + +# Include KERNEL targets if they were not already loaded: +IF(NOT (TARGET SALOMEBasics)) + INCLUDE("${KERNEL_ROOT_DIR_EXP}/${SALOME_INSTALL_CMAKE}/SalomeKERNELTargets.cmake") +ENDIF() + +# Exposed PARAVIS targets: diff --git a/adm_local/cmake_files/CMakeLists.txt b/adm_local/cmake_files/CMakeLists.txt index a7af866f..b23aa695 100644 --- a/adm_local/cmake_files/CMakeLists.txt +++ b/adm_local/cmake_files/CMakeLists.txt @@ -17,4 +17,8 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/FindSalomeParaView.cmake DESTINATION adm_local/cmake_files) +SET(_adm_data + FindSalomeParaView.cmake + ) + +INSTALL(FILES ${_adm_data} DESTINATION ${SALOME_INSTALL_CMAKE_LOCAL}) diff --git a/bin/CMakeLists.txt b/bin/CMakeLists.txt index 7f1ced89..b9d75112 100644 --- a/bin/CMakeLists.txt +++ b/bin/CMakeLists.txt @@ -23,4 +23,4 @@ SET(output ${CMAKE_CURRENT_BINARY_DIR}/VERSION) MESSAGE(STATUS "Creation of ${output}") CONFIGURE_FILE(${input} ${output}) -INSTALL(FILES paravis_setenv.py ${CMAKE_CURRENT_BINARY_DIR}/VERSION DESTINATION bin/salome) +INSTALL(FILES paravis_setenv.py ${CMAKE_CURRENT_BINARY_DIR}/VERSION DESTINATION ${SALOME_INSTALL_BINS}) diff --git a/idl/CMakeLists.txt b/idl/CMakeLists.txt index f3706e0e..3789eb18 100644 --- a/idl/CMakeLists.txt +++ b/idl/CMakeLists.txt @@ -17,124 +17,35 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -SET(VERSION_INFO ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MAINTENANCE}) -SET(SOVERSION_INFO ${VERSION_MAJOR}.${VERSION_MINOR}) - -ADD_DEFINITIONS(-DHAVE_SALOME_CONFIG) -INCLUDE_DIRECTORIES(${OMNIORB_INCLUDE_DIR} ${KERNEL_ROOT_DIR}/include/salome ${PROJECT_BINARY_DIR}/idl) - -INCLUDE(wrap.cmake) - - -SET(BASEIDL_FILES - PARAVIS_Gen_Types.idl +INCLUDE(UseOmniORB) # Provided by KERNEL + +INCLUDE_DIRECTORIES( + ${OMNIORB_INCLUDE_DIR} + ${PROJECT_BINARY_DIR}/idl +) + +IF(NOT SALOME_PARAVIS_MINIMAL_CORBA) + INCLUDE(wrap.cmake) + # Hack to have a -D on the omniidl command line: + # (again, this shouldn't last for long ...) + SET(OMNIORB_IDLCXXFLAGS "${OMNIORB_IDLCXXFLAGS};-DPARAVIS_WITH_FULL_CORBA") + ADD_DEFINITIONS(-DPARAVIS_WITH_FULL_CORBA) +ENDIF() + +SET(SalomeIDLPARAVIS_IDLSOURCES PARAVIS_Gen.idl + PARAVIS_Gen_Types.idl + ${WRAP_IDL} ) -SET(BASEIDL_SK_FILES - PARAVIS_Gen_TypesSK.cc - PARAVIS_GenSK.cc - ) - -# potential problem on parallel make on the following - multiple outputs -SET(SUFFIXES - .idl - .hh - SK.cc - ) - -SET(srcs) -FOREACH(f ${BASEIDL_SK_FILES} ${WRAP_SK_FILES}) - SET(srcs ${srcs} ${CMAKE_CURRENT_BINARY_DIR}/${f}) -ENDFOREACH(f ${BASEIDL_SK_FILES} ${WRAP_SK_FILES}) - -IF(WINDOWS) -ADD_LIBRARY(SalomeIDLPARAVIS STATIC ${srcs}) -ELSE(WINDOWS) -ADD_LIBRARY(SalomeIDLPARAVIS SHARED ${srcs}) -ENDIF(WINDOWS) - -SET(flags) -FOREACH(f ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${OMNIORB_DEFINITIONS} ${KERNEL_CXXFLAGS}) - SET(flags "${flags} ${f}") -ENDFOREACH(f ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${OMNIORB_DEFINITIONS} ${KERNEL_CXXFLAGS}) - -SET_TARGET_PROPERTIES(SalomeIDLPARAVIS PROPERTIES COMPILE_FLAGS "${flags}") -SET_TARGET_PROPERTIES(SalomeIDLPARAVIS PROPERTIES VERSION ${VERSION_INFO} SOVERSION ${SOVERSION_INFO}) - -TARGET_LINK_LIBRARIES(SalomeIDLPARAVIS ${PLATFORM_LIBADD} ${PLATFORM_LDFLAGS} ${OMNIORB_LIBRARIES}) -INSTALL(TARGETS SalomeIDLPARAVIS DESTINATION lib/salome) - -ADD_EXECUTABLE(vtkWrapIDL - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParse.tab.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParsePreprocess.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseHierarchy.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseExtras.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseMain.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseData.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseString.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkWrap.c -# ${PROJECT_SOURCE_DIR}/src/ParaView/vtkWrapText.c - ${CMAKE_CURRENT_SOURCE_DIR}/vtkWrapIDL.c) - -set_property(SOURCE ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseMain.c PROPERTY COMPILE_DEFINITIONS - VTK_PARSE_VERSION="${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION}") - -ADD_DEPENDENCIES(vtkWrapIDL generate_txt) - -INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/ParaView) -SET(flags) -FOREACH(f ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${PARAVIEW_INCLUDES} ${VTK_INCLUDES}) - SET(flags "${flags} ${f}") -ENDFOREACH(f ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${PARAVIEW_INCLUDES} ${VTK_INCLUDES}) - -#VTN TODO: vtkParseData supports two types of structures for wrapping. -#We use old structures currently, but is is not influent for results of wrapping. -#It may be necessary to port vtkWrapIDL to new approach in future. -#IF(VTK_LEGACY_REMOVE) -# ADD_DEFINITIONS(-DVTK_PARSE_LEGACY_REMOVE) -#ENDIF() -SET_TARGET_PROPERTIES(vtkWrapIDL PROPERTIES COMPILE_FLAGS "${flags}") - -TARGET_LINK_LIBRARIES(vtkWrapIDL ${PLATFORM_LDFLAGS} ${PLATFORM_LIBADD}) -SET(vtkWrapIDL_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/vtkWrapIDL) -IF(WINDOWS) - IF(CMAKE_BUILD_TOOL STREQUAL nmake) - SET(vtkWrapIDL_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/vtkWrapIDL.exe) - ELSE(CMAKE_BUILD_TOOL STREQUAL nmake) - SET(vtkWrapIDL_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}/vtkWrapIDL.exe) - ENDIF(CMAKE_BUILD_TOOL STREQUAL nmake) -ENDIF(WINDOWS) -INSTALL(FILES ${vtkWrapIDL_EXEFILE} DESTINATION bin/salome PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) - -FOREACH(input ${BASEIDL_FILES} ${WRAP_IDL}) - STRING(REGEX REPLACE ".idl" "" base ${input}) - SET(src ${CMAKE_CURRENT_BINARY_DIR}/${base}SK.cc) - SET(outputs ${src}) - SET(dynsrc ${CMAKE_CURRENT_BINARY_DIR}/${base}DynSK.cc) - SET(outputs ${outputs} ${dynsrc}) - SET(inc ${CMAKE_CURRENT_BINARY_DIR}/${base}.hh) - SET(outputs ${outputs} ${inc}) - LIST(FIND BASEIDL_FILES ${input} BASE_INDEX) - IF(${BASE_INDEX} EQUAL -1) - SET(input ${CMAKE_CURRENT_BINARY_DIR}/${input}) - ELSE(${BASE_INDEX} EQUAL -1) - SET(input ${CMAKE_CURRENT_SOURCE_DIR}/${input}) - ENDIF(${BASE_INDEX} EQUAL -1) - ADD_CUSTOM_COMMAND( - OUTPUT ${outputs} - COMMAND ${OMNIORB_IDL_PYTHON} ${OMNIORB_IDLCXXFLAGS} -I${CMAKE_CURRENT_SOURCE_DIR} -I${KERNEL_ROOT_DIR}/idl/salome ${input} - MAIN_DEPENDENCY ${input} - ) - INSTALL(FILES ${input} DESTINATION idl/salome) +SET(_idl_include_dirs + ${CMAKE_CURRENT_SOURCE_DIR} + ${KERNEL_ROOT_DIR}/idl/salome +) - SET(IDL_HEADER ${CMAKE_CURRENT_BINARY_DIR}/${base}.hh) - INSTALL(FILES ${IDL_HEADER} DESTINATION include/salome) - INSTALL(CODE "SET(IDL_FILE ${input})") - INSTALL(CODE "SET(DIR lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages/salome)") - INSTALL(CODE "SET(CMAKE_CURRENT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR})") - INSTALL(CODE "SET(OMNIORB_IDL_PYTHON ${OMNIORB_IDL_PYTHON})") - INSTALL(CODE "SET(IDLPYFLAGS -bpythonIDL -p${CMAKE_CURRENT_SOURCE_DIR} -I${CMAKE_CURRENT_SOURCE_DIR} -I${KERNEL_ROOT_DIR}/idl/salome)") - INSTALL(SCRIPT ${KERNEL_ROOT_DIR}/salome_adm/cmake_files/deprecated/install_python_from_idl.cmake) +SET(_idl_link_flags + ${KERNEL_SalomeIDLKernel} +) -ENDFOREACH(input ${IDL_FILES}) +OMNIORB_ADD_MODULE(SalomeIDLPARAVIS "${SalomeIDLPARAVIS_IDLSOURCES}" "${_idl_include_dirs}" "${_idl_link_flags}") +INSTALL(TARGETS SalomeIDLPARAVIS EXPORT ${PROJECT_NAME}TargetGroup DESTINATION ${SALOME_INSTALL_LIBS}) diff --git a/idl/PARAVIS_Gen.idl b/idl/PARAVIS_Gen.idl index acaa0eb3..9708f247 100644 --- a/idl/PARAVIS_Gen.idl +++ b/idl/PARAVIS_Gen.idl @@ -82,6 +82,7 @@ module PARAVIS { */ void SaveTrace(in string theFileName); +#ifdef PARAVIS_WITH_FULL_CORBA /*! * \brief Returns list of names of extracted Paraview and VTK classes */ @@ -91,6 +92,7 @@ module PARAVIS { * \brief Returns container class for the requested Paraview class */ PARAVIS_Base CreateClass(in string theClassName); +#endif /*! * Returns parameters of current (usually built-in) connection which is active in GUI (Paraview client). diff --git a/idl/wrap.cmake b/idl/wrap.cmake index b442571a..64063d43 100755 --- a/idl/wrap.cmake +++ b/idl/wrap.cmake @@ -33,7 +33,7 @@ ADD_CUSTOM_COMMAND( ) SET(WRAP_IDL) -SET(WRAP_SK_FILES) +#SET(WRAP_SK_FILES) IF(EXISTS ${CMAKE_BINARY_DIR}/wrapfiles.txt) EXECUTE_PROCESS( @@ -60,9 +60,9 @@ IF(EXISTS ${CMAKE_BINARY_DIR}/wrapfiles.txt) ENDIF(WRAP_LEN GREATER 1) - SET(WRAP_IDL ${WRAP_IDL} PARAVIS_Gen_${VAL}.idl) - SET(WRAP_SK_FILES ${WRAP_SK_FILES} PARAVIS_Gen_${VAL}SK.cc) - SET(vtkWrapIDL_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/vtkWrapIDL) + LIST(APPEND WRAP_IDL PARAVIS_Gen_${VAL}.idl) + #SET(WRAP_SK_FILES ${WRAP_SK_FILES} PARAVIS_Gen_${VAL}SK.cc) + SET(vtkWrapIDL_EXEFILE ${PROJECT_BINARY_DIR}/src/VTKWrapping/vtkWrapIDL) IF(WINDOWS) IF(CMAKE_BUILD_TOOL STREQUAL nmake) SET(vtkWrapIDL_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/vtkWrapIDL.exe) @@ -81,3 +81,5 @@ ENDIF(EXISTS ${CMAKE_BINARY_DIR}/wrapfiles.txt) ADD_CUSTOM_TARGET(generate_txt DEPENDS ${CMAKE_BINARY_DIR}/wrapfiles.txt vtkWrapIDL.h hints) ADD_CUSTOM_TARGET(generate_idl ALL DEPENDS ${CMAKE_BINARY_DIR}/wrapfiles.txt vtkWrapIDL.h hints ${WRAP_IDL}) + + diff --git a/resources/CMakeLists.txt b/resources/CMakeLists.txt index 85a0133d..90c4f604 100644 --- a/resources/CMakeLists.txt +++ b/resources/CMakeLists.txt @@ -32,7 +32,7 @@ SET(output ${CMAKE_CURRENT_BINARY_DIR}/PARAVISCatalog.xml) MESSAGE(STATUS "Creation of ${output}") CONFIGURE_FILE(${input} ${output}) -INSTALL(FILES ${output} DESTINATION share/salome/resources/paravis) +INSTALL(FILES ${output} DESTINATION ${SALOME_PARAVIS_INSTALL_RES_DATA}) SET(input ${CMAKE_CURRENT_SOURCE_DIR}/SalomeApp.xml.in) SET(output ${CMAKE_CURRENT_BINARY_DIR}/SalomeApp.xml) @@ -40,8 +40,8 @@ SET(output ${CMAKE_CURRENT_BINARY_DIR}/SalomeApp.xml) MESSAGE(STATUS "Creation of ${output}") CONFIGURE_FILE(${input} ${output}) -INSTALL(FILES ${output} DESTINATION share/salome/resources/paravis) +INSTALL(FILES ${output} DESTINATION ${SALOME_PARAVIS_INSTALL_RES_DATA}) FOREACH(f ${dist_salomeres_DATA}) - INSTALL(FILES ${f} DESTINATION share/salome/resources/paravis) + INSTALL(FILES ${f} DESTINATION ${SALOME_PARAVIS_INSTALL_RES_DATA}) ENDFOREACH(f ${dist_salomeres_DATA}) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 843f402e..3aa7a985 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -17,20 +17,27 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -SET(SUBDIRS +SET(_subdirs ENGINE PVGUI PV_SWIG Macro ) + +IF(NOT SALOME_PARAVIS_MINIMAL_CORBA) + # Append in first position + LIST(INSERT _subdirs 0 VTKWrapping) + ADD_DEFINITIONS(-DPARAVIS_WITH_FULL_CORBA) +ENDIF() -IF(BUILD_PLUGINS) - SET(SUBDIRS - ${SUBDIRS} - Plugins - ) -ENDIF(BUILD_PLUGINS) +IF(SALOME_PARAVIS_BUILD_PLUGINS) + LIST(APPEND _subdirs Plugins) +ENDIF() -FOREACH(dir ${SUBDIRS}) +FOREACH(dir ${_subdirs}) ADD_SUBDIRECTORY(${dir}) -ENDFOREACH(dir ${SUBDIRS}) +ENDFOREACH() + +SET(WRAP_IDL_I_HH "${WRAP_IDL_I_HH}" PARENT_SCOPE) +SET(WRAP_IDL_I_CC "${WRAP_IDL_I_CC}" PARENT_SCOPE) + diff --git a/src/ENGINE/CMakeLists.txt b/src/ENGINE/CMakeLists.txt index 053a3a16..9c84f52c 100644 --- a/src/ENGINE/CMakeLists.txt +++ b/src/ENGINE/CMakeLists.txt @@ -17,25 +17,20 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -SET(VERSION_INFO ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MAINTENANCE}) -SET(SOVERSION_INFO ${VERSION_MAJOR}.${VERSION_MINOR}) +INCLUDE_DIRECTORIES( + ${OMNIORB_INCLUDE_DIR} + ${KERNEL_INCLUDE_DIRS} + ${PROJECT_BINARY_DIR}/idl) -ADD_DEFINITIONS(-DHAVE_SALOME_CONFIG) -INCLUDE_DIRECTORIES(${OMNIORB_INCLUDE_DIR} ${KERNEL_ROOT_DIR}/include/salome ${PROJECT_BINARY_DIR}/idl) +ADD_DEFINITIONS(${KERNEL_DEFINITIONS}) +ADD_DEFINITIONS(${OMNIORB_DEFINITIONS}) -ADD_LIBRARY(PARAVISEngine SHARED PARAVIS_Engine_i.cc) +ADD_LIBRARY(PARAVISEngine PARAVIS_Engine_i.cc) -SET(flags) -FOREACH(f ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${KERNEL_CXXFLAGS} ${OMNIORB_DEFINITIONS}) - SET(flags "${flags} ${f}") -ENDFOREACH(f ${var}) - -SET_TARGET_PROPERTIES(PARAVISEngine PROPERTIES COMPILE_FLAGS "${flags}") -SET_TARGET_PROPERTIES(PARAVISEngine PROPERTIES VERSION ${VERSION_INFO} SOVERSION ${SOVERSION_INFO}) - -TARGET_LINK_LIBRARIES(PARAVISEngine ${PLATFORM_LIBADD} ${PLATFORM_LDFLAGS} ${KERNEL_LDFLAGS} +TARGET_LINK_LIBRARIES(PARAVISEngine ${KERNEL_SalomeIDLKernel} ${KERNEL_SalomeNS} ${KERNEL_SalomeContainer} ${KERNEL_SALOMELocalTrace} - ${OMNIORB_LIBRARIES} SalomeIDLPARAVIS) -INSTALL(TARGETS PARAVISEngine DESTINATION lib/salome) + ${OMNIORB_LIBRARIES} + SalomeIDLPARAVIS) +INSTALL(TARGETS PARAVISEngine EXPORT ${PROJECT_NAME}TargetGroup DESTINATION ${SALOME_INSTALL_LIBS}) -INSTALL(FILES PARAVIS_Engine_i.hh DESTINATION include/salome) +INSTALL(FILES PARAVIS_Engine_i.hh DESTINATION ${SALOME_INSTALL_HEADERS}) diff --git a/src/ENGINE/PARAVIS_Engine_i.cc b/src/ENGINE/PARAVIS_Engine_i.cc index 6d4e99b5..3f53d0a8 100644 --- a/src/ENGINE/PARAVIS_Engine_i.cc +++ b/src/ENGINE/PARAVIS_Engine_i.cc @@ -257,6 +257,7 @@ namespace PARAVIS { return myParaVisGen->PasteInto(theStream,theObjectID,theObject); } +#ifdef PARAVIS_WITH_FULL_CORBA //=========================================================================== PARAVIS::string_array* PARAVIS_Gen_i::GetClassesList() { @@ -268,6 +269,7 @@ namespace PARAVIS { { return myParaVisGen->CreateClass(theClassName); } +#endif //=========================================================================== void PARAVIS_Gen_i::GetConnectionParameters(CORBA::Long& theId, diff --git a/src/ENGINE/PARAVIS_Engine_i.hh b/src/ENGINE/PARAVIS_Engine_i.hh index 732b236f..643d119d 100644 --- a/src/ENGINE/PARAVIS_Engine_i.hh +++ b/src/ENGINE/PARAVIS_Engine_i.hh @@ -103,9 +103,10 @@ namespace PARAVIS virtual SALOMEDS::SObject_ptr PasteInto(const SALOMEDS::TMPFile& theStream, CORBA::Long theObjectID, SALOMEDS::SObject_ptr theObject); - +#ifdef PARAVIS_WITH_FULL_CORBA virtual PARAVIS::string_array* GetClassesList(); virtual PARAVIS_Base_ptr CreateClass(const char* theClassName); +#endif virtual void GetConnectionParameters(CORBA::Long& theId, CORBA::String_out theDHost, CORBA::Long& theDPort, CORBA::String_out theRHost, CORBA::Long& theRPort, diff --git a/src/Macro/CMakeLists.txt b/src/Macro/CMakeLists.txt index 3562651f..455de015 100644 --- a/src/Macro/CMakeLists.txt +++ b/src/Macro/CMakeLists.txt @@ -17,10 +17,8 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -#FILE(GLOB copy_FILES "*py") -#INSTALL(FILES ${copy_FILES} DESTINATION ${CMAKE_INSTALL_PREFIX}/bin/salome/Macros) -INSTALL(DIRECTORY ${PROJECT_SOURCE_DIR}/src/Macro - DESTINATION ${CMAKE_INSTALL_PREFIX}/bin/salome - FILES_MATCHING PATTERN "*.py" - PATTERN "CVS" EXCLUDE - ) +SET(_PYFILES_TO_INSTALL + modes.py + ) + +INSTALL_AND_COMPILE_PYTHON_FILE("${_PYFILES_TO_INSTALL}" ${SALOME_INSTALL_SCRIPT_PYTHON}) diff --git a/src/PVGUI/CMakeLists.txt b/src/PVGUI/CMakeLists.txt index 1e250244..bb6e15ff 100644 --- a/src/PVGUI/CMakeLists.txt +++ b/src/PVGUI/CMakeLists.txt @@ -17,241 +17,181 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -SET(VERSION_INFO ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MAINTENANCE}) -SET(SOVERSION_INFO ${VERSION_MAJOR}.${VERSION_MINOR}) +INCLUDE(UseQt4Ext) -ADD_DEFINITIONS(-DHAVE_SALOME_CONFIG ${CAS_DEFINITIONS}) +# --- options --- INCLUDE_DIRECTORIES(${OMNIORB_INCLUDE_DIR} - ${KERNEL_ROOT_DIR}/include/salome - ${GUI_ROOT_DIR}/include/salome - ${CMAKE_CURRENT_SOURCE_DIR}/../ParaView + ${KERNEL_INCLUDE_DIRS} + ${GUI_INCLUDE_DIRS} ${PROJECT_BINARY_DIR}/idl ${PROJECT_BINARY_DIR} - ${CMAKE_CURRENT_SOURCE_DIR} ${CAS_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} ${QT_INCLUDES} + ${CMAKE_CURRENT_SOURCE_DIR} ) -INCLUDE(${QT_USE_FILE}) - -#IF(WITH_VISU) -# SET(VISU_PARAVIS_LIBS -# ${SalomeIDLVISU} -# ) -# -# ADD_DEFINITIONS(-DWITH_VISU) -#ENDIF(WITH_VISU) +# additional preprocessor / compiler flags +ADD_DEFINITIONS(${CAS_DEFINITIONS}) +ADD_DEFINITIONS(${KERNEL_DEFINITIONS}) +ADD_DEFINITIONS(${OMNIORB_DEFINITIONS}) -#Executable -SET(bin_PROGRAMS - vtkWrapIDL_HH - vtkWrapIDL_CC +# libraries to link to +SET(_PARAVIEW_APP_COMPO_LIB + pqApplicationComponents ) -SET(vtkWrapIDL_HH_CPPFLAGS - -DIDL_I_HH - ) +SET(_link_LIBRARIES + ${OMNIORB_LIBRARIES} + ${QT_LIBS} + ${CAS_KERNEL} + ${PYTHON_LIBS} + ${KERNEL_LDFLAGS} ${KERNEL_SalomeDS} ${KERNEL_SALOMELocalTrace} ${KERNEL_SalomeIDLKernel} + ${KERNEL_SalomeNS} ${KERNEL_SalomeLifeCycleCORBA} ${KERNEL_SalomeContainer} ${KERNEL_TOOLSDS} + ${GUI_LDFLAGS} ${GUI_SalomeApp} ${GUI_LightApp} ${GUI_CAM} ${GUI_qtx} ${GUI_suit} ${GUI_Event} ${GUI_PyInterp} + ${GUI_SalomeObject} ${GUI_vtkTools} + ${MED_SalomeIDLMED} + ${_PARAVIEW_APP_COMPO_LIB} + SalomeIDLPARAVIS +) -SET(vtkWrapIDL_CC_CPPFLAGS - -DIDL_I_CC - ) -#VTN TODO: vtkParseData supports two types of structures for wrapping. -#We use old structures currently, but is is not influent for results of wrapping. -#It may be necessary to port vtkWrapIDL to new approach in future. -#IF(VTK_LEGACY_REMOVE) -# ADD_DEFINITIONS(-DVTK_PARSE_LEGACY_REMOVE) -#ENDIF() +# --- headers --- -INCLUDE(wrap.cmake) +# header files / to be processed by moc +SET(_moc_HEADERS + PVGUI_Module.h + PVGUI_ViewManager.h + PVGUI_ViewModel.h + PVGUI_ViewWindow.h + PVGUI_ParaViewSettingsPane.h +) + +# header files / no moc processing +SET(_other_HEADERS + PVGUI_OutputWindowAdapter.h + PVGUI_Tools.h + PVGUI_MatplotlibMathTextUtilities.h + PV_I.h + PARAVIS_Gen_i.hh + PV_Events.h + PV_Tools.h +) + +# header files / to install +SET(PVGUI_HEADERS ${_moc_HEADERS} ${_other_HEADERS}) -INCLUDE(${ParaView_CMAKE_DIR}/vtkWrapClientServer.cmake) +# --- resources --- + +# resource files / to be processed by lrelease +SET(_ts_RESOURCES + resources/PARAVIS_images.ts + resources/PARAVIS_msg_en.ts + resources/PARAVIS_msg_fr.ts +) + +# resource files / static +SET(_other_RESOURCES + # sampleservers.pvsc ??? +) + +IF(SALOME_BUILD_DOC) + # --- ParaView documentation is built as a resource --- + # Check ParaView documentation file existence + # if it exists add it to the resources (compile into binary form) + # otherwise print warning message + SET(PV_DOC_FILE ${VTK_INSTALL_PREFIX}/share/doc/paraview-${PARAVIEW_VERSION_MAJOR}.${PARAVIEW_VERSION_MINOR}/paraview.qch) + IF (EXISTS ${PV_DOC_FILE}) + SET(RC_SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/PVGUI.qrc.in) + SET(RC_GENERATED ${CMAKE_CURRENT_BINARY_DIR}/PVGUI.qrc) + MESSAGE(STATUS "Creation of ${RC_GENERATED}") + CONFIGURE_FILE(${RC_SOURCE} ${RC_GENERATED}) + SET(_rcc_RESOURCES ${RC_GENERATED}) + ADD_DEFINITIONS(-DHAS_PV_DOC) + ELSE () + MESSAGE(WARNING "Help file for ParaView has not been found! ParaView documentation will not be available.") + ENDIF () +ENDIF() + +# --- sources --- + +# sources / rcc wrappings +QT4_ADD_RESOURCES(_rcc_SOURCES ${_rcc_RESOURCES}) + +# sources / moc wrappings +QT4_WRAP_CPP(_moc_SOURCES ${_moc_HEADERS}) + +# sources / EDF specific stuff +INCLUDE(vtkWrapClientServer) VTK_WRAP_ClientServer(vtkEDFCutterCS vtkEDFCutter_SRCS ${GUI_ROOT_DIR}/include/salome/vtkEDFCutter.h) -# Library sources -SET(dist_libPARAVIS_la_SOURCES - PVGUI_Module.h +# sources / static +SET(_other_SOURCES PVGUI_Module.cxx PVGUI_Module_actions.cxx PVGUI_Module_widgets.cxx - PVGUI_ViewManager.h PVGUI_ViewManager.cxx - PVGUI_ViewModel.h PVGUI_ViewModel.cxx - PVGUI_ViewWindow.h PVGUI_ViewWindow.cxx - PVGUI_OutputWindowAdapter.h PVGUI_OutputWindowAdapter.cxx - PVGUI_Tools.h PVGUI_Tools.cxx - PVGUI_ParaViewSettingsPane.h PVGUI_ParaViewSettingsPane.cxx - PVGUI_MatplotlibMathTextUtilities.h PVGUI_MatplotlibMathTextUtilities.cxx - PV_I.h - PARAVIS_Gen_i.hh - PV_Events.h - PV_Tools.h PARAVIS_Gen_i.cc PV_Tools.cxx - ${WRAP_IDL_I_HH} - ${WRAP_IDL_I_CC} - PARAVIS_CreateClass.cxx - ${vtkEDFCutter_SRCS} ) -# Check ParaView documentation file existence -# if it exists add it to the resources (compile into binary form) -# otherwise print warning message -SET(PV_DOC_FILE ${VTK_INSTALL_PREFIX}/share/doc/paraview-${PARAVIEW_VERSION_MAJOR}.${PARAVIEW_VERSION_MINOR}/paraview.qch) -IF (EXISTS ${PV_DOC_FILE}) - SET(RC_SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/PVGUI.qrc.in) - SET(RC_GENERATED ${CMAKE_CURRENT_BINARY_DIR}/PVGUI.qrc) - MESSAGE(STATUS "Creation of ${RC_GENERATED}") - CONFIGURE_FILE(${RC_SOURCE} ${RC_GENERATED}) - QT4_ADD_RESOURCES(RCS_SOURCES ${RC_GENERATED}) - SET(dist_libPARAVIS_la_SOURCES ${dist_libPARAVIS_la_SOURCES} ${RCS_SOURCES}) - ADD_DEFINITIONS(-DHAS_PV_DOC) -ELSE (EXISTS ${PV_DOC_FILE}) - MESSAGE(WARNING "Help file for ParaView has not been found! ParaView documentation will not be available.") -ENDIF (EXISTS ${PV_DOC_FILE}) - -# MOC pre-processing -SET(MOC_FILES - PVGUI_Module_moc.cxx - PVGUI_ViewManager_moc.cxx - PVGUI_ViewModel_moc.cxx - PVGUI_ViewWindow_moc.cxx - PVGUI_ParaViewSettingsPane_moc.cxx +IF(NOT SALOME_PARAVIS_MINIMAL_CORBA) + SET(_VTK_wrap_SOURCES + PARAVIS_CreateClass.cxx + $ ) - -# additionnal compilation flags -# Note that ParaView uses HDF5 -SET(libPARAVIS_la_CPPFLAGS - -ftemplate-depth-32 - ${QT_ASSISTANT_INCLUDES} - ${PYTHON_INCLUDES} - ${CAS_CPPFLAGS} - ${CAS_CXXFLAGS} - ${KERNEL_CXXFLAGS} - ${OMNIORB_DEFINITIONS} - ${BOOST_CPPFLAGS} - ${GUI_CXXFLAGS} - ${MED_CXXFLAGS} - ${VISU_CXXFLAGS} - ${VISU_PARAVIS_DEFINES} +ENDIF() + +# sources / to compile +SET(PVGUI_SOURCES + ${_other_SOURCES} + ${_moc_SOURCES} + ${_rcc_SOURCES} + ${vtkEDFCutter_SRCS} + ${_VTK_wrap_SOURCES} ) -# remove deprecation warnings from Paraview -IF(WINDOWS) -ELSE(WINDOWS) - SET (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-deprecated-declarations") -ENDIF(WINDOWS) +# --- rules --- -# resources files -SET(nodist_salomeres_DATA - PARAVIS_images.qm - PARAVIS_msg_en.qm - PARAVIS_msg_fr.qm +IF(NOT SALOME_PARAVIS_MINIMAL_CORBA) + ADD_CUSTOM_COMMAND( + OUTPUT PARAVIS_CreateClass.cxx + COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/src/VTKWrapping/create_class.py ${CMAKE_BINARY_DIR} + DEPENDS ${CMAKE_BINARY_DIR}/wrapfiles.txt + ${PROJECT_BINARY_DIR}/idl/PARAVIS_Gen.hh + ${PROJECT_BINARY_DIR}/idl/PARAVIS_Gen_Types.hh + SalomeIDLPARAVIS + generate_implements ) -SET(srcs) -FOREACH(src ${dist_libPARAVIS_la_SOURCES}) - SET(srcs ${srcs} ${src}) -ENDFOREACH(src ${dist_libPARAVIS_la_SOURCES}) - -FOREACH(f ${MOC_FILES}) - SET(srcs ${srcs} ${CMAKE_CURRENT_BINARY_DIR}/${f}) -ENDFOREACH(f ${MOC_FILES}) - -ADD_LIBRARY(PARAVIS SHARED ${srcs}) - -SET(flags) -FOREACH(f ${PARAVIEW_INCLUDES} ${VTK_INCLUDES} ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${libPARAVIS_la_CPPFLAGS}) - SET(flags "${flags} ${f}") -ENDFOREACH(f ${PARAVIEW_INCLUDES} ${VTK_INCLUDES} ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${libPARAVIS_la_CPPFLAGS}) + # All wrapping tools have to be build before generating the above module - NEEDED? + ###ADD_DEPENDENCIES(SalomeIDLPARAVIS vtkWrapIDL_HH vtkWrapIDL_CC vtkWrapIDL) -SET_TARGET_PROPERTIES(PARAVIS PROPERTIES COMPILE_FLAGS "${flags}") -SET_TARGET_PROPERTIES(PARAVIS PROPERTIES VERSION ${VERSION_INFO} SOVERSION ${SOVERSION_INFO}) - -#FIND_PACKAGE(VTK 6.0 COMPONENTS vtkPVClientServerCoreCore vtkPVServerImplementationCore NO_MODULE) -#SET(VTK_LIBS vtkPVClientServerCoreCore vtkPVServerImplementationCore) -SET(VTK_LIBS) -FIND_PACKAGE(ParaView COMPONENTS pqApplicationComponents NO_MODULE) -SET(PARAVIEW_LIBS pqApplicationComponents) + # Intermediate target used in PVGUI directory (we can not cross reference + # a generated source file across directories, hence this trick): + INCLUDE_DIRECTORIES( + ${PROJECT_BINARY_DIR}/idl + ${PROJECT_BINARY_DIR}/src/VTKWrapping + ) +ENDIF() -TARGET_LINK_LIBRARIES(PARAVIS - ${PLATFORM_LIBADD} ${PLATFORM_LDFLAGS} - ${OMNIORB_LIBRARIES} - ${QT_LIBS} - ${CAS_KERNEL} - ${VTK_LIBS} - ${PYTHON_LIBS} - ${KERNEL_LDFLAGS} ${KERNEL_SalomeDS} ${KERNEL_SALOMELocalTrace} ${KERNEL_SalomeIDLKernel} - ${KERNEL_SalomeNS} ${KERNEL_SalomeLifeCycleCORBA} ${KERNEL_SalomeContainer} ${KERNEL_TOOLSDS} - ${GUI_LDFLAGS} ${GUI_SalomeApp} ${GUI_LightApp} ${GUI_CAM} ${GUI_qtx} ${GUI_suit} ${GUI_Event} ${GUI_PyInterp} - ${GUI_SalomeObject} ${GUI_vtkTools} - ${MED_LDFLAGS} ${MED_SalomeIDLMED} - ${VISU_LDFLAGS} - ${VISU_PARAVIS_LIBS} - ${PARAVIEW_LIBS} - SalomeIDLPARAVIS -) -INSTALL(TARGETS PARAVIS DESTINATION lib/salome) +ADD_LIBRARY(PARAVIS ${PVGUI_SOURCES}) +IF(NOT SALOME_PARAVIS_MINIMAL_CORBA) + # Make sure the generation of the VTK wrapping get executed first: + ADD_DEPENDENCIES(PARAVIS PARAVIS_CreateClass.cxx) +ENDIF() -FOREACH(name ${bin_PROGRAMS}) - ADD_EXECUTABLE(${name} - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParse.tab.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParsePreprocess.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseHierarchy.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseExtras.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseMain.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseData.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseString.c - ${PROJECT_SOURCE_DIR}/src/ParaView/vtkWrap.c -# ${PROJECT_SOURCE_DIR}/src/ParaView/vtkWrapText.c - ${PROJECT_SOURCE_DIR}/idl/vtkWrapIDL.c) - ADD_DEPENDENCIES(${name} generate_txt) - - set_property(SOURCE ${PROJECT_SOURCE_DIR}/src/ParaView/vtkParseMain.c PROPERTY COMPILE_DEFINITIONS - VTK_PARSE_VERSION="${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION}") +TARGET_LINK_LIBRARIES(PARAVIS ${_link_LIBRARIES}) +INSTALL(TARGETS PARAVIS EXPORT ${PROJECT_NAME}TargetGroup DESTINATION ${SALOME_INSTALL_LIBS}) - SET(flags) - FOREACH(f ${PARAVIEW_INCLUDES} ${VTK_INCLUDES} ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${${name}_CPPFLAGS}) - SET(flags "${flags} ${f}") - ENDFOREACH(f ${PARAVIEW_INCLUDES} ${VTK_INCLUDES} ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${${name}_CPPFLAGS}) - - SET_TARGET_PROPERTIES(${name} PROPERTIES COMPILE_FLAGS "${flags}") - TARGET_LINK_LIBRARIES(${name} ${PLATFORM_LIBADD}) - - SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${name}) - IF(WINDOWS) - IF(CMAKE_BUILD_TOOL STREQUAL nmake) - SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${name}.exe) - ELSE(CMAKE_BUILD_TOOL STREQUAL nmake) - SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}/${name}.exe) - ENDIF(CMAKE_BUILD_TOOL STREQUAL nmake) - ENDIF(WINDOWS) - INSTALL(FILES ${${name}_EXEFILE} DESTINATION bin/salome PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) -ENDFOREACH(name ${bin_PROGRAMS}) -FOREACH(output ${MOC_FILES}) - STRING(REGEX REPLACE _moc.cxx .h input ${output}) - - SET(input ${CMAKE_CURRENT_SOURCE_DIR}/${input}) - SET(output ${CMAKE_CURRENT_BINARY_DIR}/${output}) - ADD_CUSTOM_COMMAND( - OUTPUT ${output} - COMMAND ${QT_MOC_EXECUTABLE} ${MOC_FLAGS} ${input} -o ${output} - MAIN_DEPENDENCY ${input} - ) -ENDFOREACH(output ${MOC_FILES}) - -FOREACH(f ${nodist_salomeres_DATA}) - STRING(REGEX REPLACE .qm .ts input ${f}) - SET(input ${CMAKE_CURRENT_SOURCE_DIR}/resources/${input}) - SET(output ${CMAKE_CURRENT_BINARY_DIR}/${f}) - EXECUTE_PROCESS(COMMAND ${QT_LRELEASE_EXECUTABLE} ${input} -qm ${output}) - INSTALL(FILES ${output} DESTINATION share/salome/resources/paravis) -ENDFOREACH(f ${nodist_salomeres_DATA}) +# --- header and resources installation --- +INSTALL(FILES ${PVGUI_HEADERS} DESTINATION ${SALOME_INSTALL_HEADERS}) +QT4_INSTALL_TS_RESOURCES("${_ts_RESOURCES}" "${SALOME_PARAVIS_INSTALL_RES_DATA}") +INSTALL(FILES ${_other_RESOURCES} DESTINATION ${SALOME_PARAVIS_INSTALL_RES_DATA}) diff --git a/src/PVGUI/PARAVIS_Gen_i.cc b/src/PVGUI/PARAVIS_Gen_i.cc index f0d49019..e0c03499 100644 --- a/src/PVGUI/PARAVIS_Gen_i.cc +++ b/src/PVGUI/PARAVIS_Gen_i.cc @@ -48,7 +48,10 @@ #include "QDir" #include "QTextStream" -#include "vtkWrapIDL.h" +#ifdef PARAVIS_WITH_FULL_CORBA + // List of VTK classes wrapped into IDL: +# include "vtkWrapIDL.h" +#endif #include #include @@ -593,6 +596,7 @@ namespace PARAVIS return SALOMEDS::SObject::_nil(); } +#ifdef PARAVIS_WITH_FULL_CORBA //---------------------------------------------------------------------------- PARAVIS::string_array* PARAVIS_Gen_i::GetClassesList() { @@ -611,6 +615,7 @@ namespace PARAVIS PARAVIS::PARAVIS_Base_i* aClass = CreateInstance(NULL, QString(theClassName)); return aClass->_this(); } +#endif //---------------------------------------------------------------------------- void PARAVIS_Gen_i::GetConnectionParameters(CORBA::Long& theId, @@ -729,7 +734,7 @@ namespace PARAVIS // Version information char* PARAVIS_Gen_i::getVersion() { -#if PARAVIS_DEVELOPMENT +#ifdef PARAVIS_DEVELOPMENT return CORBA::string_dup( PARAVIS_VERSION_STR"dev" ); #else return CORBA::string_dup( PARAVIS_VERSION_STR ); diff --git a/src/PVGUI/PARAVIS_Gen_i.hh b/src/PVGUI/PARAVIS_Gen_i.hh index d023cb7b..3e50fdb9 100644 --- a/src/PVGUI/PARAVIS_Gen_i.hh +++ b/src/PVGUI/PARAVIS_Gen_i.hh @@ -182,11 +182,13 @@ namespace PARAVIS //! inherited methods from Engines::EngineComponent. Returns module version. virtual char* getVersion(); +#ifdef PARAVIS_WITH_FULL_CORBA //! Implementation of PARAVIS_Gen interface virtual PARAVIS::string_array* GetClassesList(); //! Implementation of PARAVIS_Gen interface virtual PARAVIS_Base_ptr CreateClass(const char* theClassName); +#endif //! Implementation of PARAVIS_Gen interface virtual void GetConnectionParameters(CORBA::Long& theId, diff --git a/src/PV_SWIG/CMakeLists.txt b/src/PV_SWIG/CMakeLists.txt index e4bdaf3a..3ab6b0f9 100644 --- a/src/PV_SWIG/CMakeLists.txt +++ b/src/PV_SWIG/CMakeLists.txt @@ -17,20 +17,17 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -SET(dist_salomescript_DATA - paravis.py - paravisSM.py - pvsimple.py - presentations.py +IF(SALOME_PARAVIS_MINIMAL_CORBA) + # Use another set of Python files + SET(_PYFILES_TO_INSTALL) + MESSAGE(WARNING "New Python scripts not impl !!!") +ELSE() + SET(_PYFILES_TO_INSTALL + paravis.py + paravisSM.py + pvsimple.py + presentations.py ) +ENDIF() -FOREACH(f ${dist_salomescript_DATA}) - INSTALL(FILES ${f} DESTINATION bin/salome) - - INSTALL(CODE "SET(PYTHON_FILE ${f})") - INSTALL(CODE "SET(CMAKE_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX})") - INSTALL(CODE "SET(DEST bin/salome)") - INSTALL(CODE "SET(PYTHON_EXECUTABLE ${PYTHON_EXECUTABLE})") - INSTALL(SCRIPT ${KERNEL_ROOT_DIR}/salome_adm/cmake_files/deprecated/install_and_compile_python_file.cmake) - -ENDFOREACH(f ${dist_salomescript_DATA}) +INSTALL_AND_COMPILE_PYTHON_FILE("${_PYFILES_TO_INSTALL}" ${SALOME_INSTALL_SCRIPT_PYTHON}) diff --git a/src/Plugins/CMakeLists.txt b/src/Plugins/CMakeLists.txt index 54f5279e..64238c27 100755 --- a/src/Plugins/CMakeLists.txt +++ b/src/Plugins/CMakeLists.txt @@ -17,16 +17,9 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -PROJECT(SamplePlugins) -CMAKE_MINIMUM_REQUIRED(VERSION 2.4.5) -IF(COMMAND CMAKE_POLICY) - CMAKE_POLICY(SET CMP0003 NEW) -ENDIF(COMMAND CMAKE_POLICY) - -FIND_PACKAGE(ParaView REQUIRED) INCLUDE(${PARAVIEW_USE_FILE}) -SUBDIRS( +SET(_subdirs #Filter #ToolBar MedReader @@ -36,4 +29,8 @@ SUBDIRS( IntegrationPoints ElevationSurface ScaleVector -) + ) + +FOREACH(_dir ${_subdirs}) + ADD_SUBDIRECTORY(${_dir}) +ENDFOREACH() diff --git a/src/VTKParser/CMakeLists.txt b/src/VTKParser/CMakeLists.txt new file mode 100644 index 00000000..ca407da1 --- /dev/null +++ b/src/VTKParser/CMakeLists.txt @@ -0,0 +1,113 @@ +# Copyright (C) 2010-2013 CEA/DEN, EDF R&D +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + + +## Generation of the list of VTK classes (to be wrapped into IDLs) +## ===================================== +IF(NOT SALOME_LIGHT_ONLY) + # TODO: the below requires ParaView in the PYTHONPATH ... not so nice: + MESSAGE(STATUS "Generating list of wrapped VTK classes ...") + LIST(GET PARAVIEW_INCLUDE_DIRS 0 PARAVIEW_INCLUDE_DIR0) + EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/getwrapclasses.py ${PARAVIEW_INCLUDE_DIR0} + RESULT_VARIABLE _res) + IF(NOT _res EQUAL 0) + MESSAGE(FATAL_ERROR "Unable to run the Python script retrieving the list of VTK classes.") + ENDIF() +ENDIF() + +INCLUDE(GenerateWrapList.cmake) + +## Parser for VTK header files +## =========================== +## +## Everything under the ParaView subdirectory is a pure copy of ParaView source +## code. + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/ParaView + ${PROJECT_BINARY_DIR}/idl + ${PROJECT_SOURCE_DIR}/src/PVGUI + ) + +# Wrapper executable generating the headers, source files and IDL files +# corresponding to VTK wrapping: +SET(_wrap_PROGRAMS + vtkWrapIDL_HH + vtkWrapIDL_CC + vtkWrapIDL + ) + +SET(vtkWrapIDL_HH_CPPFLAGS -DIDL_I_HH) +SET(vtkWrapIDL_CC_CPPFLAGS -DIDL_I_CC) +SET(vtkWrapIDL_CPPFLAGS) + +#VTN TODO: vtkParseData supports two types of structures for wrapping. +#We use old structures currently, but is is not influent for results of wrapping. +#It may be necessary to port vtkWrapIDL to new approach in future. +#IF(VTK_LEGACY_REMOVE) +# ADD_DEFINITIONS(-DVTK_PARSE_LEGACY_REMOVE) +#ENDIF() + +FOREACH(name ${_wrap_PROGRAMS}) + ADD_EXECUTABLE(${name} + ParaView/vtkParse.tab.c + ParaView/vtkParsePreprocess.c + ParaView/vtkParseHierarchy.c + ParaView/vtkParseExtras.c + ParaView/vtkParseMain.c + ParaView/vtkParseData.c + ParaView/vtkParseString.c + ParaView/vtkWrap.c +# ParaView/vtkWrapText.c + ${PROJECT_SOURCE_DIR}/idl/vtkWrapIDL.c) + ADD_DEPENDENCIES(${name} generate_txt) + + set_property(SOURCE ParaView/vtkParseMain.c PROPERTY COMPILE_DEFINITIONS + VTK_PARSE_VERSION="${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION}") + + SET(flags) + FOREACH(f ${PARAVIEW_INCLUDES} ${VTK_INCLUDES} ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${${name}_CPPFLAGS}) + SET(flags "${flags} ${f}") + ENDFOREACH(f ${PARAVIEW_INCLUDES} ${VTK_INCLUDES} ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${${name}_CPPFLAGS}) + + SET_TARGET_PROPERTIES(${name} PROPERTIES COMPILE_FLAGS "${flags}") + TARGET_LINK_LIBRARIES(${name} ${PLATFORM_LIBADD}) + + SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${name}) + IF(WINDOWS) + IF(CMAKE_BUILD_TOOL STREQUAL nmake) + SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${name}.exe) + ELSE(CMAKE_BUILD_TOOL STREQUAL nmake) + SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}/${name}.exe) + ENDIF(CMAKE_BUILD_TOOL STREQUAL nmake) + ENDIF(WINDOWS) + INSTALL(FILES ${${name}_EXEFILE} DESTINATION bin/salome PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) +ENDFOREACH(name ${_wrap_PROGRAMS}) + +# Generate headers and sources corresponding to the IDL implementations: +INCLUDE(wrap.cmake) + +## From 2.8.10, we should use: +## SET(CMAKE_POSITION_INDEPENDENT_CODE ON) +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") +ADD_LIBRARY(VTK_IDL_Impl OBJECT ${WRAP_IDL_I_CC}) + +# Make the list of wrapped files visible from the top directory (will be used in PVGUI and idl): +SET(WRAP_IDL_I_HH "${WRAP_IDL_I_HH}" PARENT_SCOPE) +SET(WRAP_IDL_I_CC "${WRAP_IDL_I_CC}" PARENT_SCOPE) diff --git a/wrapfiles.cmake b/src/VTKParser/GenerateWrapList.cmake similarity index 80% rename from wrapfiles.cmake rename to src/VTKParser/GenerateWrapList.cmake index 631f4251..c884b5b5 100644 --- a/wrapfiles.cmake +++ b/src/VTKParser/GenerateWrapList.cmake @@ -18,7 +18,7 @@ # ADD_CUSTOM_COMMAND( - OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/wrapfiles.txt - COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_SOURCE_DIR}/getwrapclasses.py - DEPENDS ${CMAKE_SOURCE_DIR}/getwrapclasses.py ${PARAVIEW_PYTHON_EXECUTABLE} + OUTPUT ${PROJECT_BINARY_DIR}/wrapfiles.txt + COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/getwrapclasses.py + DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/getwrapclasses.py ${PARAVIEW_PYTHON_EXECUTABLE} ) diff --git a/src/PVGUI/create_class.py b/src/VTKParser/create_class.py similarity index 100% rename from src/PVGUI/create_class.py rename to src/VTKParser/create_class.py diff --git a/src/PVGUI/create_class.sh b/src/VTKParser/create_class.sh similarity index 100% rename from src/PVGUI/create_class.sh rename to src/VTKParser/create_class.sh diff --git a/getwrapclasses.py b/src/VTKParser/getwrapclasses.py similarity index 100% rename from getwrapclasses.py rename to src/VTKParser/getwrapclasses.py diff --git a/src/VTKParser/readme.txt b/src/VTKParser/readme.txt new file mode 100644 index 00000000..cdceac2c --- /dev/null +++ b/src/VTKParser/readme.txt @@ -0,0 +1,3 @@ +The files under the ParaView directory are pure copy from Paraview sources. +They need for extractor building. +Them has to be updated if the corresponded files in paraview will be changed \ No newline at end of file diff --git a/src/PVGUI/wrap.cmake b/src/VTKParser/wrap.cmake similarity index 82% rename from src/PVGUI/wrap.cmake rename to src/VTKParser/wrap.cmake index ff9939f4..daf5d126 100755 --- a/src/PVGUI/wrap.cmake +++ b/src/VTKParser/wrap.cmake @@ -29,28 +29,28 @@ IF(EXISTS ${CMAKE_BINARY_DIR}/wrapfiles.txt) ) STRING(REGEX MATCHALL "[^\n]+" WRAP_LIST_REG ${WRAP_LIST_FULL}) - FOREACH(STR ${WRAP_LIST_REG}) + FOREACH(_str ${WRAP_LIST_REG}) - SEPARATE_ARGUMENTS(STR) - LIST(LENGTH STR WRAP_LEN) + SEPARATE_ARGUMENTS(_str) + LIST(LENGTH _str WRAP_LEN) SET(DEP_HH) SET(DEP_CC) - LIST(GET STR 0 VAL) + LIST(GET _str 0 VAL) IF(WRAP_LEN GREATER 1) MATH(EXPR WRAP_LEN1 "${WRAP_LEN} - 1" ) FOREACH(IND RANGE 1 ${WRAP_LEN1}) - LIST(GET STR ${IND} DEP_VAL) + LIST(GET _str ${IND} DEP_VAL) SET(DEP_HH ${DEP_HH} PARAVIS_Gen_${DEP_VAL}_i.hh) SET(DEP_CC ${DEP_CC} PARAVIS_Gen_${DEP_VAL}_i.cc) ENDFOREACH(IND RANGE 1 ${WRAP_LEN1}) ENDIF(WRAP_LEN GREATER 1) - SET(WRAP_IDL_I_HH ${WRAP_IDL_I_HH} PARAVIS_Gen_${VAL}_i.hh) - SET(WRAP_IDL_I_CC ${WRAP_IDL_I_CC} PARAVIS_Gen_${VAL}_i.cc) + LIST(APPEND WRAP_IDL_I_HH PARAVIS_Gen_${VAL}_i.hh) + LIST(APPEND WRAP_IDL_I_CC PARAVIS_Gen_${VAL}_i.cc) SET(vtkWrapIDL_HH_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/vtkWrapIDL_HH) IF(WINDOWS) @@ -82,12 +82,7 @@ IF(EXISTS ${CMAKE_BINARY_DIR}/wrapfiles.txt) DEPENDS PARAVIS_Gen_${VAL}_i.hh vtkWrapIDL_CC ${PARAVIEW_INCLUDE_DIR0}/${VAL}.h ${CMAKE_BINARY_DIR}/idl/hints ${DEP_CC} ) - ENDFOREACH(STR ${WRAP_LIST_REG}) + ENDFOREACH(_str ${WRAP_LIST_REG}) ENDIF(EXISTS ${CMAKE_BINARY_DIR}/wrapfiles.txt) -ADD_CUSTOM_COMMAND( - OUTPUT PARAVIS_CreateClass.cxx - COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/create_class.py ${CMAKE_BINARY_DIR} - DEPENDS ${CMAKE_BINARY_DIR}/wrapfiles.txt ${WRAP_IDL_I_HH} -) -ADD_CUSTOM_TARGET(generate_pvgui ALL DEPENDS ${CMAKE_BINARY_DIR}/wrapfiles.txt PARAVIS_CreateClass.cxx ${WRAP_IDL_I_HH} ${WRAP_IDL_I_CC}) +ADD_CUSTOM_TARGET(generate_implements ALL DEPENDS ${CMAKE_BINARY_DIR}/wrapfiles.txt ${WRAP_IDL_I_HH} ${WRAP_IDL_I_CC}) diff --git a/src/VTKWrapping/CMakeLists.txt b/src/VTKWrapping/CMakeLists.txt new file mode 100644 index 00000000..ca407da1 --- /dev/null +++ b/src/VTKWrapping/CMakeLists.txt @@ -0,0 +1,113 @@ +# Copyright (C) 2010-2013 CEA/DEN, EDF R&D +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + + +## Generation of the list of VTK classes (to be wrapped into IDLs) +## ===================================== +IF(NOT SALOME_LIGHT_ONLY) + # TODO: the below requires ParaView in the PYTHONPATH ... not so nice: + MESSAGE(STATUS "Generating list of wrapped VTK classes ...") + LIST(GET PARAVIEW_INCLUDE_DIRS 0 PARAVIEW_INCLUDE_DIR0) + EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/getwrapclasses.py ${PARAVIEW_INCLUDE_DIR0} + RESULT_VARIABLE _res) + IF(NOT _res EQUAL 0) + MESSAGE(FATAL_ERROR "Unable to run the Python script retrieving the list of VTK classes.") + ENDIF() +ENDIF() + +INCLUDE(GenerateWrapList.cmake) + +## Parser for VTK header files +## =========================== +## +## Everything under the ParaView subdirectory is a pure copy of ParaView source +## code. + +INCLUDE_DIRECTORIES( + ${CMAKE_CURRENT_SOURCE_DIR}/ParaView + ${PROJECT_BINARY_DIR}/idl + ${PROJECT_SOURCE_DIR}/src/PVGUI + ) + +# Wrapper executable generating the headers, source files and IDL files +# corresponding to VTK wrapping: +SET(_wrap_PROGRAMS + vtkWrapIDL_HH + vtkWrapIDL_CC + vtkWrapIDL + ) + +SET(vtkWrapIDL_HH_CPPFLAGS -DIDL_I_HH) +SET(vtkWrapIDL_CC_CPPFLAGS -DIDL_I_CC) +SET(vtkWrapIDL_CPPFLAGS) + +#VTN TODO: vtkParseData supports two types of structures for wrapping. +#We use old structures currently, but is is not influent for results of wrapping. +#It may be necessary to port vtkWrapIDL to new approach in future. +#IF(VTK_LEGACY_REMOVE) +# ADD_DEFINITIONS(-DVTK_PARSE_LEGACY_REMOVE) +#ENDIF() + +FOREACH(name ${_wrap_PROGRAMS}) + ADD_EXECUTABLE(${name} + ParaView/vtkParse.tab.c + ParaView/vtkParsePreprocess.c + ParaView/vtkParseHierarchy.c + ParaView/vtkParseExtras.c + ParaView/vtkParseMain.c + ParaView/vtkParseData.c + ParaView/vtkParseString.c + ParaView/vtkWrap.c +# ParaView/vtkWrapText.c + ${PROJECT_SOURCE_DIR}/idl/vtkWrapIDL.c) + ADD_DEPENDENCIES(${name} generate_txt) + + set_property(SOURCE ParaView/vtkParseMain.c PROPERTY COMPILE_DEFINITIONS + VTK_PARSE_VERSION="${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION}") + + SET(flags) + FOREACH(f ${PARAVIEW_INCLUDES} ${VTK_INCLUDES} ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${${name}_CPPFLAGS}) + SET(flags "${flags} ${f}") + ENDFOREACH(f ${PARAVIEW_INCLUDES} ${VTK_INCLUDES} ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${${name}_CPPFLAGS}) + + SET_TARGET_PROPERTIES(${name} PROPERTIES COMPILE_FLAGS "${flags}") + TARGET_LINK_LIBRARIES(${name} ${PLATFORM_LIBADD}) + + SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${name}) + IF(WINDOWS) + IF(CMAKE_BUILD_TOOL STREQUAL nmake) + SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${name}.exe) + ELSE(CMAKE_BUILD_TOOL STREQUAL nmake) + SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}/${name}.exe) + ENDIF(CMAKE_BUILD_TOOL STREQUAL nmake) + ENDIF(WINDOWS) + INSTALL(FILES ${${name}_EXEFILE} DESTINATION bin/salome PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) +ENDFOREACH(name ${_wrap_PROGRAMS}) + +# Generate headers and sources corresponding to the IDL implementations: +INCLUDE(wrap.cmake) + +## From 2.8.10, we should use: +## SET(CMAKE_POSITION_INDEPENDENT_CODE ON) +SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") +ADD_LIBRARY(VTK_IDL_Impl OBJECT ${WRAP_IDL_I_CC}) + +# Make the list of wrapped files visible from the top directory (will be used in PVGUI and idl): +SET(WRAP_IDL_I_HH "${WRAP_IDL_I_HH}" PARENT_SCOPE) +SET(WRAP_IDL_I_CC "${WRAP_IDL_I_CC}" PARENT_SCOPE) diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 43f8145c..4cc1f0f2 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -17,5 +17,26 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -SUBDIRS(VisuPrs) +ADD_SUBDIRECTORY(VisuPrs) +SET(_demo_files + demo_0_med.py + demo_1_med.py + demo_2_med.py + demo_3_med.py + demo_4_med.py + demo_5_med.py + demo_6_med.py + demo_7_med.py + demo_8_med.py + demo_9_med.py + demo_10_med.py + demo_11_med.py + demo_12_med.py + demo_13_med.py + demo_14_med.py + demo_15_med.py + ) + +INSTALL_AND_COMPILE_PYTHON_FILE("${_demo_files}" ${SALOME_INSTALL_SCRIPT_PYTHON}) + \ No newline at end of file diff --git a/test/VisuPrs/CMakeLists.txt b/test/VisuPrs/CMakeLists.txt index 228d3c06..7e48950e 100644 --- a/test/VisuPrs/CMakeLists.txt +++ b/test/VisuPrs/CMakeLists.txt @@ -17,26 +17,27 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -SUBDIRS(Util - 2D_viewer - 3D_viewer - ScalarMap - DeformedShape - ScalarMap_On_DeformedShape - CutPlanes - CutLines - Vectors - Plot3D - IsoSurfaces - MeshPresentation - Animation - GaussPoints - StreamLines - SWIG_scripts - Tables - ImportMedField - united - bugs - imps - dump_study +ADD_SUBDIRECTORY( + Util + 2D_viewer + 3D_viewer + ScalarMap + DeformedShape + ScalarMap_On_DeformedShape + CutPlanes + CutLines + Vectors + Plot3D + IsoSurfaces + MeshPresentation + Animation + GaussPoints + StreamLines + SWIG_scripts + Tables + ImportMedField + united + bugs + imps + dump_study ) -- 2.30.2 From 7757c27cd83572b1032fda8315136097b15cc25e Mon Sep 17 00:00:00 2001 From: bruneton Date: Mon, 21 Oct 2013 09:57:37 +0000 Subject: [PATCH 05/16] CMake: porting module to the new CMake procedure. Isolated as much as possible IDL wrapping logic. Introduced flag SALOME_PARAVIS_MINIMAL_CORBA to turn the wrapping off. --- src/ParaView/readme.txt | 3 - src/VTKParser/CMakeLists.txt | 113 ------------------ .../GenerateWrapList.cmake | 0 src/{ => VTKWrapping}/ParaView/lex.yy.c | 0 src/{ => VTKWrapping}/ParaView/vtkParse.tab.c | 0 src/{ => VTKWrapping}/ParaView/vtkParseData.c | 0 src/{ => VTKWrapping}/ParaView/vtkParseData.h | 0 .../ParaView/vtkParseExtras.c | 0 .../ParaView/vtkParseExtras.h | 0 .../ParaView/vtkParseHierarchy.c | 0 .../ParaView/vtkParseHierarchy.h | 0 .../ParaView/vtkParseInternal.h | 0 src/{ => VTKWrapping}/ParaView/vtkParseMain.c | 0 src/{ => VTKWrapping}/ParaView/vtkParseMain.h | 0 .../ParaView/vtkParsePreprocess.c | 0 .../ParaView/vtkParsePreprocess.h | 0 .../ParaView/vtkParseString.c | 0 .../ParaView/vtkParseString.h | 0 src/{ => VTKWrapping}/ParaView/vtkWrap.c | 0 src/{ => VTKWrapping}/ParaView/vtkWrap.h | 0 .../ParaView/vtkWrapHierarchy.c | 0 src/{ => VTKWrapping}/ParaView/vtkWrapText.c | 0 src/{ => VTKWrapping}/ParaView/vtkWrapText.h | 0 .../create_class.py | 0 .../create_class.sh | 0 .../getwrapclasses.py | 0 src/{VTKParser => VTKWrapping}/readme.txt | 0 src/{VTKParser => VTKWrapping}/wrap.cmake | 0 28 files changed, 116 deletions(-) delete mode 100644 src/ParaView/readme.txt delete mode 100644 src/VTKParser/CMakeLists.txt rename src/{VTKParser => VTKWrapping}/GenerateWrapList.cmake (100%) rename src/{ => VTKWrapping}/ParaView/lex.yy.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkParse.tab.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseData.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseData.h (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseExtras.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseExtras.h (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseHierarchy.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseHierarchy.h (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseInternal.h (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseMain.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseMain.h (100%) rename src/{ => VTKWrapping}/ParaView/vtkParsePreprocess.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkParsePreprocess.h (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseString.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkParseString.h (100%) rename src/{ => VTKWrapping}/ParaView/vtkWrap.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkWrap.h (100%) rename src/{ => VTKWrapping}/ParaView/vtkWrapHierarchy.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkWrapText.c (100%) rename src/{ => VTKWrapping}/ParaView/vtkWrapText.h (100%) rename src/{VTKParser => VTKWrapping}/create_class.py (100%) rename src/{VTKParser => VTKWrapping}/create_class.sh (100%) rename src/{VTKParser => VTKWrapping}/getwrapclasses.py (100%) rename src/{VTKParser => VTKWrapping}/readme.txt (100%) rename src/{VTKParser => VTKWrapping}/wrap.cmake (100%) diff --git a/src/ParaView/readme.txt b/src/ParaView/readme.txt deleted file mode 100644 index 40939f71..00000000 --- a/src/ParaView/readme.txt +++ /dev/null @@ -1,3 +0,0 @@ -These files are pure copy from Paraview sources. -They need for extractor building. -Them has to be updated if the corresponded files in paraview will be changed \ No newline at end of file diff --git a/src/VTKParser/CMakeLists.txt b/src/VTKParser/CMakeLists.txt deleted file mode 100644 index ca407da1..00000000 --- a/src/VTKParser/CMakeLists.txt +++ /dev/null @@ -1,113 +0,0 @@ -# Copyright (C) 2010-2013 CEA/DEN, EDF R&D -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 of the License. -# -# This library is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, write to the Free Software -# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -# -# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com -# - - -## Generation of the list of VTK classes (to be wrapped into IDLs) -## ===================================== -IF(NOT SALOME_LIGHT_ONLY) - # TODO: the below requires ParaView in the PYTHONPATH ... not so nice: - MESSAGE(STATUS "Generating list of wrapped VTK classes ...") - LIST(GET PARAVIEW_INCLUDE_DIRS 0 PARAVIEW_INCLUDE_DIR0) - EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/getwrapclasses.py ${PARAVIEW_INCLUDE_DIR0} - RESULT_VARIABLE _res) - IF(NOT _res EQUAL 0) - MESSAGE(FATAL_ERROR "Unable to run the Python script retrieving the list of VTK classes.") - ENDIF() -ENDIF() - -INCLUDE(GenerateWrapList.cmake) - -## Parser for VTK header files -## =========================== -## -## Everything under the ParaView subdirectory is a pure copy of ParaView source -## code. - -INCLUDE_DIRECTORIES( - ${CMAKE_CURRENT_SOURCE_DIR}/ParaView - ${PROJECT_BINARY_DIR}/idl - ${PROJECT_SOURCE_DIR}/src/PVGUI - ) - -# Wrapper executable generating the headers, source files and IDL files -# corresponding to VTK wrapping: -SET(_wrap_PROGRAMS - vtkWrapIDL_HH - vtkWrapIDL_CC - vtkWrapIDL - ) - -SET(vtkWrapIDL_HH_CPPFLAGS -DIDL_I_HH) -SET(vtkWrapIDL_CC_CPPFLAGS -DIDL_I_CC) -SET(vtkWrapIDL_CPPFLAGS) - -#VTN TODO: vtkParseData supports two types of structures for wrapping. -#We use old structures currently, but is is not influent for results of wrapping. -#It may be necessary to port vtkWrapIDL to new approach in future. -#IF(VTK_LEGACY_REMOVE) -# ADD_DEFINITIONS(-DVTK_PARSE_LEGACY_REMOVE) -#ENDIF() - -FOREACH(name ${_wrap_PROGRAMS}) - ADD_EXECUTABLE(${name} - ParaView/vtkParse.tab.c - ParaView/vtkParsePreprocess.c - ParaView/vtkParseHierarchy.c - ParaView/vtkParseExtras.c - ParaView/vtkParseMain.c - ParaView/vtkParseData.c - ParaView/vtkParseString.c - ParaView/vtkWrap.c -# ParaView/vtkWrapText.c - ${PROJECT_SOURCE_DIR}/idl/vtkWrapIDL.c) - ADD_DEPENDENCIES(${name} generate_txt) - - set_property(SOURCE ParaView/vtkParseMain.c PROPERTY COMPILE_DEFINITIONS - VTK_PARSE_VERSION="${VTK_MAJOR_VERSION}.${VTK_MINOR_VERSION}") - - SET(flags) - FOREACH(f ${PARAVIEW_INCLUDES} ${VTK_INCLUDES} ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${${name}_CPPFLAGS}) - SET(flags "${flags} ${f}") - ENDFOREACH(f ${PARAVIEW_INCLUDES} ${VTK_INCLUDES} ${PLATFORM_CPPFLAGS} ${PTHREAD_CFLAGS} ${${name}_CPPFLAGS}) - - SET_TARGET_PROPERTIES(${name} PROPERTIES COMPILE_FLAGS "${flags}") - TARGET_LINK_LIBRARIES(${name} ${PLATFORM_LIBADD}) - - SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${name}) - IF(WINDOWS) - IF(CMAKE_BUILD_TOOL STREQUAL nmake) - SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${name}.exe) - ELSE(CMAKE_BUILD_TOOL STREQUAL nmake) - SET(${name}_EXEFILE ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_BUILD_TYPE}/${name}.exe) - ENDIF(CMAKE_BUILD_TOOL STREQUAL nmake) - ENDIF(WINDOWS) - INSTALL(FILES ${${name}_EXEFILE} DESTINATION bin/salome PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE) -ENDFOREACH(name ${_wrap_PROGRAMS}) - -# Generate headers and sources corresponding to the IDL implementations: -INCLUDE(wrap.cmake) - -## From 2.8.10, we should use: -## SET(CMAKE_POSITION_INDEPENDENT_CODE ON) -SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") -ADD_LIBRARY(VTK_IDL_Impl OBJECT ${WRAP_IDL_I_CC}) - -# Make the list of wrapped files visible from the top directory (will be used in PVGUI and idl): -SET(WRAP_IDL_I_HH "${WRAP_IDL_I_HH}" PARENT_SCOPE) -SET(WRAP_IDL_I_CC "${WRAP_IDL_I_CC}" PARENT_SCOPE) diff --git a/src/VTKParser/GenerateWrapList.cmake b/src/VTKWrapping/GenerateWrapList.cmake similarity index 100% rename from src/VTKParser/GenerateWrapList.cmake rename to src/VTKWrapping/GenerateWrapList.cmake diff --git a/src/ParaView/lex.yy.c b/src/VTKWrapping/ParaView/lex.yy.c similarity index 100% rename from src/ParaView/lex.yy.c rename to src/VTKWrapping/ParaView/lex.yy.c diff --git a/src/ParaView/vtkParse.tab.c b/src/VTKWrapping/ParaView/vtkParse.tab.c similarity index 100% rename from src/ParaView/vtkParse.tab.c rename to src/VTKWrapping/ParaView/vtkParse.tab.c diff --git a/src/ParaView/vtkParseData.c b/src/VTKWrapping/ParaView/vtkParseData.c similarity index 100% rename from src/ParaView/vtkParseData.c rename to src/VTKWrapping/ParaView/vtkParseData.c diff --git a/src/ParaView/vtkParseData.h b/src/VTKWrapping/ParaView/vtkParseData.h similarity index 100% rename from src/ParaView/vtkParseData.h rename to src/VTKWrapping/ParaView/vtkParseData.h diff --git a/src/ParaView/vtkParseExtras.c b/src/VTKWrapping/ParaView/vtkParseExtras.c similarity index 100% rename from src/ParaView/vtkParseExtras.c rename to src/VTKWrapping/ParaView/vtkParseExtras.c diff --git a/src/ParaView/vtkParseExtras.h b/src/VTKWrapping/ParaView/vtkParseExtras.h similarity index 100% rename from src/ParaView/vtkParseExtras.h rename to src/VTKWrapping/ParaView/vtkParseExtras.h diff --git a/src/ParaView/vtkParseHierarchy.c b/src/VTKWrapping/ParaView/vtkParseHierarchy.c similarity index 100% rename from src/ParaView/vtkParseHierarchy.c rename to src/VTKWrapping/ParaView/vtkParseHierarchy.c diff --git a/src/ParaView/vtkParseHierarchy.h b/src/VTKWrapping/ParaView/vtkParseHierarchy.h similarity index 100% rename from src/ParaView/vtkParseHierarchy.h rename to src/VTKWrapping/ParaView/vtkParseHierarchy.h diff --git a/src/ParaView/vtkParseInternal.h b/src/VTKWrapping/ParaView/vtkParseInternal.h similarity index 100% rename from src/ParaView/vtkParseInternal.h rename to src/VTKWrapping/ParaView/vtkParseInternal.h diff --git a/src/ParaView/vtkParseMain.c b/src/VTKWrapping/ParaView/vtkParseMain.c similarity index 100% rename from src/ParaView/vtkParseMain.c rename to src/VTKWrapping/ParaView/vtkParseMain.c diff --git a/src/ParaView/vtkParseMain.h b/src/VTKWrapping/ParaView/vtkParseMain.h similarity index 100% rename from src/ParaView/vtkParseMain.h rename to src/VTKWrapping/ParaView/vtkParseMain.h diff --git a/src/ParaView/vtkParsePreprocess.c b/src/VTKWrapping/ParaView/vtkParsePreprocess.c similarity index 100% rename from src/ParaView/vtkParsePreprocess.c rename to src/VTKWrapping/ParaView/vtkParsePreprocess.c diff --git a/src/ParaView/vtkParsePreprocess.h b/src/VTKWrapping/ParaView/vtkParsePreprocess.h similarity index 100% rename from src/ParaView/vtkParsePreprocess.h rename to src/VTKWrapping/ParaView/vtkParsePreprocess.h diff --git a/src/ParaView/vtkParseString.c b/src/VTKWrapping/ParaView/vtkParseString.c similarity index 100% rename from src/ParaView/vtkParseString.c rename to src/VTKWrapping/ParaView/vtkParseString.c diff --git a/src/ParaView/vtkParseString.h b/src/VTKWrapping/ParaView/vtkParseString.h similarity index 100% rename from src/ParaView/vtkParseString.h rename to src/VTKWrapping/ParaView/vtkParseString.h diff --git a/src/ParaView/vtkWrap.c b/src/VTKWrapping/ParaView/vtkWrap.c similarity index 100% rename from src/ParaView/vtkWrap.c rename to src/VTKWrapping/ParaView/vtkWrap.c diff --git a/src/ParaView/vtkWrap.h b/src/VTKWrapping/ParaView/vtkWrap.h similarity index 100% rename from src/ParaView/vtkWrap.h rename to src/VTKWrapping/ParaView/vtkWrap.h diff --git a/src/ParaView/vtkWrapHierarchy.c b/src/VTKWrapping/ParaView/vtkWrapHierarchy.c similarity index 100% rename from src/ParaView/vtkWrapHierarchy.c rename to src/VTKWrapping/ParaView/vtkWrapHierarchy.c diff --git a/src/ParaView/vtkWrapText.c b/src/VTKWrapping/ParaView/vtkWrapText.c similarity index 100% rename from src/ParaView/vtkWrapText.c rename to src/VTKWrapping/ParaView/vtkWrapText.c diff --git a/src/ParaView/vtkWrapText.h b/src/VTKWrapping/ParaView/vtkWrapText.h similarity index 100% rename from src/ParaView/vtkWrapText.h rename to src/VTKWrapping/ParaView/vtkWrapText.h diff --git a/src/VTKParser/create_class.py b/src/VTKWrapping/create_class.py similarity index 100% rename from src/VTKParser/create_class.py rename to src/VTKWrapping/create_class.py diff --git a/src/VTKParser/create_class.sh b/src/VTKWrapping/create_class.sh similarity index 100% rename from src/VTKParser/create_class.sh rename to src/VTKWrapping/create_class.sh diff --git a/src/VTKParser/getwrapclasses.py b/src/VTKWrapping/getwrapclasses.py similarity index 100% rename from src/VTKParser/getwrapclasses.py rename to src/VTKWrapping/getwrapclasses.py diff --git a/src/VTKParser/readme.txt b/src/VTKWrapping/readme.txt similarity index 100% rename from src/VTKParser/readme.txt rename to src/VTKWrapping/readme.txt diff --git a/src/VTKParser/wrap.cmake b/src/VTKWrapping/wrap.cmake similarity index 100% rename from src/VTKParser/wrap.cmake rename to src/VTKWrapping/wrap.cmake -- 2.30.2 From 2567edf67854ead81d4566672a69f6ea46e27996 Mon Sep 17 00:00:00 2001 From: bruneton Date: Mon, 21 Oct 2013 11:57:52 +0000 Subject: [PATCH 06/16] CMake: BUILD_DOC and BUILD_TESTS set to ON by default --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d7c67868..b4b92a77 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -73,8 +73,8 @@ ENDIF() # User options # (some options have already been defined in KERNEL) # ============ -OPTION(SALOME_BUILD_DOC "Generate SALOME GUI documentation" ${SALOME_BUILD_DOC}) -OPTION(SALOME_BUILD_TESTS "Build SALOME tests" ${SALOME_BUILD_TESTS}) +OPTION(SALOME_BUILD_DOC "Generate SALOME GUI documentation" ON) +OPTION(SALOME_BUILD_TESTS "Build SALOME tests" ON) OPTION(SALOME_PARAVIS_MINIMAL_CORBA "Build PARAVIS with a minimal CORBA interface" OFF) OPTION(SALOME_PARAVIS_BUILD_PLUGINS "Build PARAVIS plugins (MEDReader, etc ...)" ON) -- 2.30.2 From e2c075bb656e4e5b0d8e6fcb7e06b5c25f903dee Mon Sep 17 00:00:00 2001 From: bruneton Date: Mon, 21 Oct 2013 13:16:37 +0000 Subject: [PATCH 07/16] Minimal CORBA mode: adapted PARAVIS' Python API to work in this mode. --- src/PV_SWIG/CMakeLists.txt | 15 +- src/PV_SWIG/VTKWrapping/paravis.py | 97 + src/PV_SWIG/VTKWrapping/paravisSM.py | 3014 +++++++++++++++++ src/PV_SWIG/VTKWrapping/presentations.py | 2647 +++++++++++++++ src/PV_SWIG/VTKWrapping/pvsimple.py | 1171 +++++++ .../{ => VTKWrapping}/servermanager.diff | 0 src/PV_SWIG/{ => VTKWrapping}/simple.diff | 0 src/PV_SWIG/paravis.py | 29 +- src/PV_SWIG/paravisSM.py | 2996 +--------------- src/PV_SWIG/pvsimple.py | 1170 +------ 10 files changed, 6971 insertions(+), 4168 deletions(-) create mode 100644 src/PV_SWIG/VTKWrapping/paravis.py create mode 100644 src/PV_SWIG/VTKWrapping/paravisSM.py create mode 100644 src/PV_SWIG/VTKWrapping/presentations.py create mode 100644 src/PV_SWIG/VTKWrapping/pvsimple.py rename src/PV_SWIG/{ => VTKWrapping}/servermanager.diff (100%) rename src/PV_SWIG/{ => VTKWrapping}/simple.diff (100%) diff --git a/src/PV_SWIG/CMakeLists.txt b/src/PV_SWIG/CMakeLists.txt index 3ab6b0f9..18e33dc4 100644 --- a/src/PV_SWIG/CMakeLists.txt +++ b/src/PV_SWIG/CMakeLists.txt @@ -18,15 +18,20 @@ # IF(SALOME_PARAVIS_MINIMAL_CORBA) - # Use another set of Python files - SET(_PYFILES_TO_INSTALL) - MESSAGE(WARNING "New Python scripts not impl !!!") -ELSE() + # Use another set of Python files redirecting the API directly + # to the original ParaView modules. SET(_PYFILES_TO_INSTALL paravis.py - paravisSM.py pvsimple.py presentations.py + paravisSM.py + ) +ELSE() + SET(_PYFILES_TO_INSTALL + VTKWrapping/paravis.py + VTKWrapping/paravisSM.py + VTKWrapping/pvsimple.py + VTKWrapping/presentations.py ) ENDIF() diff --git a/src/PV_SWIG/VTKWrapping/paravis.py b/src/PV_SWIG/VTKWrapping/paravis.py new file mode 100644 index 00000000..d5c228ed --- /dev/null +++ b/src/PV_SWIG/VTKWrapping/paravis.py @@ -0,0 +1,97 @@ +# Copyright (C) 2010-2013 CEA/DEN, EDF R&D +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# +# File : paravis.py +# Module : PARAVIS +# + +import os, new + +import PARAVIS +import SALOME +import SALOME_Session_idl +import SALOMEDS +import SALOME_ModuleCatalog +from omniORB import CORBA +from time import sleep +from salome import * + +myORB = None +myNamingService = None +myLifeCycleCORBA = None +myNamingService = None +myLocalStudyManager = None +myLocalStudy = None +myLocalParavis = None +myDelay = None +mySession = None + +## Initialization of paravis server +def Initialize(theORB, theNamingService, theLifeCycleCORBA, theStudyManager, theStudy, theDelay) : + global myORB, myNamingService, myLifeCycleCORBA, myLocalStudyManager, myLocalStudy + global mySession, myDelay + myDelay = theDelay + myORB = theORB + myNamingService = theNamingService + myLifeCycleCORBA = theLifeCycleCORBA + myLocalStudyManager = theStudyManager + while mySession == None: + mySession = myNamingService.Resolve("/Kernel/Session") + mySession = mySession._narrow(SALOME.Session) + mySession.GetInterface() + myDelay = theDelay + sleep(myDelay) + myLocalParavis = myLifeCycleCORBA.FindOrLoadComponent("FactoryServer", "PARAVIS") + myLocalStudy = theStudy + myLocalParavis.SetCurrentStudy(myLocalStudy) + myLocalParavis.ActivateModule() + return myLocalParavis + + +def ImportFile(theFileName): + "Import a file of any format supported by ParaView" + myParavis.ImportFile(theFileName) + + +def createFunction(theName): + "Create function - constructor of Paravis object" + def MyFunction(): + return myParavis.CreateClass(theName) + return MyFunction + + +def createConstructors(): + "Create constructor functions according to list of extracted classes" + g = globals() + aClassNames = myParavis.GetClassesList(); + for aName in aClassNames: + g[aName] = createFunction(aName) + +## Initialize of a PARAVIS interface +myParavis = Initialize(orb, naming_service,lcc,myStudyManager,myStudy, 2) + +## Initialize constructor functions +createConstructors() + +## Initialize Paravis static objects +vtkSMObject = vtkSMObject() +vtkProcessModule = vtkProcessModule() +vtkPVPythonModule = vtkPVPythonModule() +vtkSMProxyManager = vtkSMProxyManager() + + diff --git a/src/PV_SWIG/VTKWrapping/paravisSM.py b/src/PV_SWIG/VTKWrapping/paravisSM.py new file mode 100644 index 00000000..8237dfc1 --- /dev/null +++ b/src/PV_SWIG/VTKWrapping/paravisSM.py @@ -0,0 +1,3014 @@ +# Copyright (C) 2010-2013 CEA/DEN, EDF R&D +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +r"""servermanager is a module for using paraview server manager in Python. +One can always use the server manager API directly. However, this module +provides an interface easier to use from Python by wrapping several VTK +classes around Python classes. + +Note that, upon load, this module will create several sub-modules: sources, +filters and rendering. These modules can be used to instantiate specific +proxy types. For a list, try "dir(servermanager.sources)" + +A simple example: + from paraview.servermanager import * + + # Creates a new built-in session and makes it the active session. + Connect() + + # Creates a new render view on the active session. + renModule = CreateRenderView() + + # Create a new sphere proxy on the active session and register it + # in the sources group. + sphere = sources.SphereSource(registrationGroup="sources", ThetaResolution=16, PhiResolution=32) + + # Create a representation for the sphere proxy and adds it to the render + # module. + display = CreateRepresentation(sphere, renModule) + + renModule.StillRender() +""" + + + +import re, os, new, sys +from paravis import * + +# VTN: Avoid paraview.* instructions in this file. +# It leads to problems during execution. + +def _wrap_property(proxy, smproperty): + """ Internal function. + Given a server manager property and its domains, returns the + appropriate python object. + """ + property = None + if smproperty.IsA("vtkSMStringVectorProperty"): + al = smproperty.GetDomain("array_list") + if al and al.IsA("vtkSMArraySelectionDomain") and \ + smproperty.GetRepeatable(): + property = ArrayListProperty(proxy, smproperty) + elif al and al.IsA("vtkSMArrayListDomain") and smproperty.GetNumberOfElements() == 5: + property = ArraySelectionProperty(proxy, smproperty) + else: + iter = smproperty.NewDomainIterator() + isFileName = False + while not iter.IsAtEnd(): + # Refer to BUG #9710 to see why optional domains need to be + # ignored. + if iter.GetDomain().IsA("vtkSMFileListDomain") and \ + iter.GetDomain().GetIsOptional() == 0 : + isFileName = True + break + iter.Next() + iter.UnRegister(None) + if isFileName: + property = FileNameProperty(proxy, smproperty) + elif _make_name_valid(smproperty.GetXMLLabel()) == 'ColorArrayName': + property = ColorArrayProperty(proxy, smproperty) + else: + property = VectorProperty(proxy, smproperty) + elif smproperty.IsA("vtkSMVectorProperty"): + if smproperty.IsA("vtkSMIntVectorProperty") and \ + smproperty.GetDomain("enum"): + property = EnumerationProperty(proxy, smproperty) + else: + property = VectorProperty(proxy, smproperty) + elif smproperty.IsA("vtkSMInputProperty"): + property = InputProperty(proxy, smproperty) + elif smproperty.IsA("vtkSMProxyProperty"): + property = ProxyProperty(proxy, smproperty) + else: + property = Property(proxy, smproperty) + return property + +class Proxy(object): + """Proxy for a server side object. A proxy manages the lifetime of + one or more server manager objects. It also provides an interface + to set and get the properties of the server side objects. These + properties are presented as Python properties. For example, + you can set a property Foo using the following: + proxy.Foo = (1,2) + or + proxy.Foo.SetData((1,2)) + or + proxy.Foo[0:2] = (1,2) + For more information, see the documentation of the property which + you can obtain with + help(proxy.Foo). + + This class also provides an iterator which can be used to iterate + over all properties. + eg: + proxy = Proxy(proxy=smproxy) + for property in proxy: + print property + + For advanced users: + This is a python class that wraps a vtkSMProxy.. Makes it easier to + set/get properties. + Instead of: + proxy.GetProperty("Foo").SetElement(0, 1) + proxy.GetProperty("Foo").SetElement(0, 2) + you can do: + proxy.Foo = (1,2) + or + proxy.Foo.SetData((1,2)) + or + proxy.Foo[0:2] = (1,2) + Instead of: + proxy.GetProperty("Foo").GetElement(0) + you can do: + proxy.Foo.GetData()[0] + or + proxy.Foo[0] + For proxy properties, you can use append: + proxy.GetProperty("Bar").AddProxy(foo) + you can do: + proxy.Bar.append(foo) + Properties support most of the list API. See VectorProperty and + ProxyProperty documentation for details. + + Please note that some of the methods accessible through the Proxy + class are not listed by help() because the Proxy objects forward + unresolved attributes to the underlying object. To get the full list, + see also dir(proxy.SMProxy). See also the doxygen based documentation + of the vtkSMProxy C++ class. + """ + + def __init__(self, **args): + """ Default constructor. It can be used to initialize properties + by passing keyword arguments where the key is the name of the + property. In addition registrationGroup and registrationName (optional) + can be specified (as keyword arguments) to automatically register + the proxy with the proxy manager. """ + self.add_attribute('Observed', None) + self.add_attribute('ObserverTag', -1) + self.add_attribute('_Proxy__Properties', {}) + self.add_attribute('_Proxy__LastAttrName', None) + self.add_attribute('SMProxy', None) + self.add_attribute('Port', 0) + + if 'port' in args: + self.Port = args['port'] + del args['port'] + + update = True + if 'no_update' in args: + if args['no_update']: + update = False + del args['no_update'] + + if 'proxy' in args: + self.InitializeFromProxy(args['proxy']) + del args['proxy'] + else: + self.Initialize(None, update) + if 'registrationGroup' in args: + registrationGroup = args['registrationGroup'] + del args['registrationGroup'] + registrationName = self.SMProxy.GetGlobalIDAsString() + if 'registrationName' in args: + registrationName = args['registrationName'] + del args['registrationName'] + pxm = ProxyManager() + pxm.RegisterProxy(registrationGroup, registrationName, self.SMProxy) + if update: + self.UpdateVTKObjects() + for key in args.keys(): + setattr(self, key, args[key]) + # Visit all properties so that they are created + for prop in self: + pass + + def __setattr__(self, name, value): + try: + setter = getattr(self.__class__, name) + setter = setter.__set__ + except AttributeError: + if not hasattr(self, name): + raise AttributeError("Attribute %s does not exist. " % name + + " This class does not allow addition of new attributes to avoid " + + "mistakes due to typos. Use add_attribute() if you really want " + + "to add this attribute.") + self.__dict__[name] = value + else: + setter(self, value) + + def add_attribute(self, name, value): + self.__dict__[name] = value + + def __del__(self): + """Destructor. Cleans up all observers as well as remove + the proxy from the _pyproxies dictionary""" + # Make sure that we remove observers we added + if self.Observed: + observed = self.Observed + tag = self.ObserverTag + self.Observed = None + self.ObserverTag = -1 + observed.RemoveObserver(tag) + if _pyproxies and self.SMProxy and (self.SMProxy, self.Port) in _pyproxies: + del _pyproxies[(self.SMProxy, self.Port)] + + def InitializeFromProxy(self, aProxy, update=True): + """Constructor. Assigns proxy to self.SMProxy, updates the server + object as well as register the proxy in _pyproxies dictionary.""" + import weakref + self.SMProxy = aProxy + if update: + self.SMProxy.UpdateVTKObjects() + _pyproxies[(self.SMProxy, self.Port)] = weakref.ref(self) + + def Initialize(self): + "Overridden by the subclass created automatically" + pass + + def __eq__(self, other): + "Returns true if the underlying SMProxies are the same." + if isinstance(other, Proxy): + try: + if self.Port != other.Port: + return False + except: + pass + ## VSV using IsSame instead == + return self.SMProxy.IsSame(other.SMProxy) + return self.SMProxy.IsSame(other) + + def __ne__(self, other): + "Returns false if the underlying SMProxies are the same." + return not self.__eq__(other) + + def __iter__(self): + "Creates an iterator for the properties." + return PropertyIterator(self) + + def SetPropertyWithName(self, pname, arg): + """Generic method for setting the value of a property.""" + prop = self.GetProperty(pname) + if prop is None: + raise RuntimeError, "Property %s does not exist. Please check the property name for typos." % pname + prop.SetData(arg) + + def GetPropertyValue(self, name): + """Returns a scalar for properties with 1 elements, the property + itself for vectors.""" + p = self.GetProperty(name) + if isinstance(p, VectorProperty): + if p.GetNumberOfElements() == 1 and not p.GetRepeatable(): + if p.SMProperty.IsA("vtkSMStringVectorProperty") or not p.GetArgumentIsArray(): + return p[0] + elif isinstance(p, InputProperty): + if not p.GetMultipleInput(): + if len(p) > 0: + return p[0] + else: + return None + elif isinstance(p, ProxyProperty): + if not p.GetRepeatable(): + if len(p) > 0: + return p[0] + else: + return None + return p + + def GetProperty(self, name): + """Given a property name, returns the property object.""" + if name in self.__Properties and self.__Properties[name](): + return self.__Properties[name]() + smproperty = self.SMProxy.GetProperty(name) + # Maybe they are looking by the label. Try to match that. + if not smproperty: + iter = PropertyIterator(self) + for prop in iter: + if name == _make_name_valid(iter.PropertyLabel): + smproperty = prop.SMProperty + break + if smproperty: + property = _wrap_property(self, smproperty) + if property is not None: + import weakref + self.__Properties[name] = weakref.ref(property) + return property + return None + + def ListProperties(self): + """Returns a list of all property names on this proxy.""" + property_list = [] + iter = self.__iter__() + for property in iter: + name = _make_name_valid(iter.PropertyLabel) + if name: + property_list.append(name) + return property_list + + def __ConvertArgumentsAndCall(self, *args): + """ Internal function. + Used to call a function on SMProxy. Converts input and + output values as appropriate. + """ + newArgs = [] + for arg in args: + if issubclass(type(arg), Proxy) or isinstance(arg, Proxy): + newArgs.append(arg.SMProxy) + else: + newArgs.append(arg) + func = getattr(self.SMProxy, self.__LastAttrName) + retVal = func(*newArgs) + if type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProxy"): + return _getPyProxy(retVal) + elif type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProperty"): + return _wrap_property(self, retVal) + else: + return retVal + + def __GetActiveCamera(self): + """ This method handles GetActiveCamera specially. It adds + an observer to the camera such that everytime it is modified + the render view updated""" + import weakref + c = self.SMProxy.GetActiveCamera() + # VSV: Observers are not supported +## if not c.HasObserver("ModifiedEvent"): +## self.ObserverTag =c.AddObserver("ModifiedEvent", _makeUpdateCameraMethod(weakref.ref(self))) +## self.Observed = c + return c + + def __getattr__(self, name): + """With the exception of a few overloaded methods, + returns the SMProxy method""" + if not self.SMProxy: + raise AttributeError("class %s has no attribute %s" % ("None", name)) + return None + # Handle GetActiveCamera specially. + if name == "GetActiveCamera" and \ + hasattr(self.SMProxy, "GetActiveCamera"): + return self.__GetActiveCamera + if name == "SaveDefinition" and hasattr(self.SMProxy, "SaveDefinition"): + return self.__SaveDefinition + # If not a property, see if SMProxy has the method + try: + proxyAttr = getattr(self.SMProxy, name) + self.__LastAttrName = name + return self.__ConvertArgumentsAndCall + except: + pass + return getattr(self.SMProxy, name) + +class SourceProxy(Proxy): + """Proxy for a source object. This class adds a few methods to Proxy + that are specific to sources. It also provides access to the output + ports. Output ports can be accessed by name or index: + > op = source[0] + or + > op = source['some name']. + """ + def UpdatePipeline(self, time=None): + """This method updates the server-side VTK pipeline and the associated + data information. Make sure to update a source to validate the output + meta-data.""" + if time != None: + self.SMProxy.UpdatePipeline(time) + else: + self.SMProxy.UpdatePipeline() + # This is here to cause a receive + # on the client side so that progress works properly. + if ActiveConnection and ActiveConnection.IsRemote(): + self.SMProxy.GetDataInformation() + + def FileNameChanged(self): + "Called when the filename of a source proxy is changed." + self.UpdatePipelineInformation() + + def UpdatePipelineInformation(self): + """This method updates the meta-data of the server-side VTK pipeline and + the associated information properties""" + self.SMProxy.UpdatePipelineInformation() + + def GetDataInformation(self, idx=None): + """This method returns a DataInformation wrapper around a + vtkPVDataInformation""" + if idx == None: + idx = self.Port + if self.SMProxy: + return DataInformation( \ + self.SMProxy.GetDataInformation(idx), \ + self.SMProxy, idx) + + def __getitem__(self, idx): + """Given a slice, int or string, returns the corresponding + output port""" + if isinstance(idx, slice): + indices = idx.indices(self.SMProxy.GetNumberOfOutputPorts()) + retVal = [] + for i in range(*indices): + retVal.append(OutputPort(self, i)) + return retVal + elif isinstance(idx, int): + if idx >= self.SMProxy.GetNumberOfOutputPorts() or idx < 0: + raise IndexError + return OutputPort(self, idx) + else: + return OutputPort(self, self.SMProxy.GetOutputPortIndex(idx)) + + def GetPointDataInformation(self): + """Returns the associated point data information.""" + self.UpdatePipeline() + return FieldDataInformation(self.SMProxy, self.Port, "PointData") + + def GetCellDataInformation(self): + """Returns the associated cell data information.""" + self.UpdatePipeline() + return FieldDataInformation(self.SMProxy, self.Port, "CellData") + + def GetFieldDataInformation(self): + """Returns the associated cell data information.""" + self.UpdatePipeline() + return FieldDataInformation(self.SMProxy, self.Port, "FieldData") + + PointData = property(GetPointDataInformation, None, None, "Returns point data information") + CellData = property(GetCellDataInformation, None, None, "Returns cell data information") + FieldData = property(GetFieldDataInformation, None, None, "Returns field data information") + + +class ExodusIIReaderProxy(SourceProxy): + """Special class to define convenience functions for array + selection.""" + + def FileNameChanged(self): + "Called when the filename changes. Selects all variables." + SourceProxy.FileNameChanged(self) + self.SelectAllVariables() + + def SelectAllVariables(self): + "Select all available variables for reading." + for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables', + 'ElementVariables', 'GlobalVariables'): + f = getattr(self, prop) + f.SelectAll() + + def DeselectAllVariables(self): + "Deselects all variables." + for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables', + 'ElementVariables', 'GlobalVariables'): + f = getattr(self, prop) + f.DeselectAll() + +class ViewLayoutProxy(Proxy): + """Special class to define convenience methods for View Layout""" + + def SplitViewHorizontal(self, view, fraction=0.5): + """Split the cell containing the specified view horizontally. + If no fraction is specified, the frame is split into equal parts. + On success returns a positve number that identifying the new cell + location that can be used to assign view to, or split further. + Return -1 on failure.""" + location = self.GetViewLocation(view) + if location == -1: + raise RuntimeError, "View is not present in this layout." + if fraction < 0.0 or fraction > 1.0: + raise RuntimeError, "'fraction' must be in the range [0.0, 1.0]" + return self.SMProxy.SplitHorizontal(location, fraction) + + def SplitViewVertical(self, view=None, fraction=0.5): + """Split the cell containing the specified view horizontally. + If no view is specified, active view is used. + If no fraction is specified, the frame is split into equal parts. + On success returns a positve number that identifying the new cell + location that can be used to assign view to, or split further. + Return -1 on failure.""" + location = self.GetViewLocation(view) + if location == -1: + raise RuntimeError, "View is not present in this layout." + if fraction < 0.0 or fraction > 1.0: + raise RuntimeError, "'fraction' must be in the range [0.0, 1.0]" + return self.SMProxy.SplitVertical(location, fraction) + + def AssignView(self, location, view): + """Assign a view at a particular location. Note that the view's position may + be changed by subsequent Split() calls. Returns true on success.""" + viewproxy = None + if isinstance(view, Proxy): + view = view.SMProxy + return self.SMProxy.AssignView(location, view) + + def GetViewLocation(self, view): + if isinstance(view, Proxy): + view = view.SMProxy + return self.SMProxy.GetViewLocation(view) + +class Property(object): + """Generic property object that provides access to one of the properties of + a server object. This class does not allow setting/getting any values but + provides an interface to update a property using __call__. This can be used + for command properties that correspond to function calls without arguments. + For example, + > proxy.Foo() + would push a Foo property which may cause the proxy to call a Foo method + on the actual VTK object. + + For advanced users: + Python wrapper around a vtkSMProperty with a simple interface. + In addition to all method provided by vtkSMProperty (obtained by + forwarding unknown attributes requests to the underlying SMProxy), + Property and sub-class provide a list API. + + Please note that some of the methods accessible through the Property + class are not listed by help() because the Property objects forward + unresolved attributes to the underlying object. To get the full list, + see also dir(proxy.SMProperty). See also the doxygen based documentation + of the vtkSMProperty C++ class. + """ + def __init__(self, proxy, smproperty): + """Default constructor. Stores a reference to the proxy.""" + import weakref + self.SMProperty = smproperty + self.Proxy = proxy + + def __repr__(self): + """Returns a string representation containing property name + and value""" + if not type(self) is Property: + if self.GetData() is not None: + repr = self.GetData().__repr__() + else: + repr = "None" + else: + repr = "Property name= " + name = self.Proxy.GetPropertyName(self.SMProperty) + if name: + repr += name + else: + repr += "Unknown" + + return repr + + def __call__(self): + """Forces a property update using InvokeCommand.""" + if type(self) is Property: + self.Proxy.SMProxy.InvokeCommand(self._FindPropertyName()) + else: + raise RuntimeError, "Cannot invoke this property" + + def _FindPropertyName(self): + "Returns the name of this property." + return self.Proxy.GetPropertyName(self.SMProperty) + + def _UpdateProperty(self): + "Pushes the value of this property to the server." + # For now, we are updating all properties. This is due to an + # issue with the representations. Their VTK objects are not + # created until Input is set therefore, updating a property + # has no effect. Updating all properties everytime one is + # updated has the effect of pushing values set before Input + # when Input is updated. + # self.Proxy.SMProxy.UpdateProperty(self._FindPropertyName()) + self.Proxy.SMProxy.UpdateVTKObjects() + + def __getattr__(self, name): + "Unknown attribute requests get forwarded to SMProperty." + return getattr(self.SMProperty, name) + + Name = property(_FindPropertyName, None, None, + "Returns the name for the property") + +class GenericIterator(object): + """Iterator for container type objects""" + + def __init__(self, obj): + self.Object = obj + self.index = 0 + + def __iter__(self): + return self + + def next(self): + if self.index >= len(self.Object): + raise StopIteration + + idx = self.index + self.index += 1 + return self.Object[idx] + +class VectorProperty(Property): + """A VectorProperty provides access to one or more values. You can use + a slice to get one or more property values: + > val = property[2] + or + > vals = property[0:5:2] + You can use a slice to set one or more property values: + > property[2] = val + or + > property[1:3] = (1,2) + """ + def ConvertValue(self, value): + return value + + def __len__(self): + """Returns the number of elements.""" + return self.SMProperty.GetNumberOfElements() + + def __iter__(self): + """Implementation of the sequence API""" + return GenericIterator(self) + + def __setitem__(self, idx, value): + """Given a list or tuple of values, sets a slice of values [min, max)""" + if isinstance(idx, slice): + indices = idx.indices(len(self)) + for i, j in zip(range(*indices), value): + self.SMProperty.SetElement(i, self.ConvertValue(j)) + self._UpdateProperty() + elif idx >= len(self) or idx < 0: + raise IndexError + else: + self.SMProperty.SetElement(idx, self.ConvertValue(value)) + self._UpdateProperty() + + def GetElement(self, index): + return self.SMProperty.GetElement(index) + + def __getitem__(self, idx): + """Returns the range [min, max) of elements. Raises an IndexError + exception if an argument is out of bounds.""" + ls = len(self) + if isinstance(idx, slice): + indices = idx.indices(ls) + retVal = [] + for i in range(*indices): + retVal.append(self.GetElement(i)) + return retVal + elif idx >= ls: + raise IndexError + elif idx < 0: + idx = ls + idx + if idx < 0: + raise IndexError + + return self.GetElement(idx) + + def GetData(self): + "Returns all elements as either a list or a single value." + property = self.SMProperty + if property.GetRepeatable() or \ + property.GetNumberOfElements() > 1: + return self[0:len(self)] + elif property.GetNumberOfElements() == 1: + return self.GetElement(0) + + def SetData(self, values): + """Allows setting of all values at once. Requires a single value or + a iterable object.""" + if not hasattr(values, "__iter__"): + values = (values,) + if not self.GetRepeatable() and len(values) != self.GetNumberOfElements(): + raise RuntimeError("This property requires %d values." % self.GetNumberOfElements()) + if self.GetRepeatable(): + # Clean up first + self.SMProperty.SetNumberOfElements(0) + idx = 0 + for val in values: + self.SMProperty.SetElement(idx, self.ConvertValue(val)) + idx += 1 + self._UpdateProperty() + + def Clear(self): + "Removes all elements." + self.SMProperty().SetNumberOfElements(0) + self._UpdateProperty() + +class ColorArrayProperty(VectorProperty): + """This subclass of VectorProperty handles setting of the array to + color by. It handles attribute type as well as well array name.""" + + def GetAvailable(self): + """Returns the list of available arrays as (attribute type, array name + tuples.""" + arrays = [] + for a in self.Proxy.Input.PointData: + arrays.append(('POINT_DATA', a.GetName())) + for a in self.Proxy.Input.CellData: + arrays.append(('CELL_DATA', a.GetName())) + return arrays + + def SetData(self, value): + """Overwritten to enable setting attribute type (the ColorAttributeType + property and the array name. The argument should be the array name + (in which case the first appropriate attribute type is picked) or + a tuple of attribute type and array name.""" + if isinstance(value, tuple) and len(value) == 2: + att = value[0] + arr = value[1] + elif isinstance(value, str): + att = None + arr = value + else: + raise ValueError("Expected a tuple of 2 values or a string.") + + if not arr: + self.SMProperty.SetElement(0, '') + self._UpdateProperty() + return + + found = False + for a in self.Available: + if a[1] == arr and (not att or att == a[0]): + att = a[0] + found = True + break + + if not found: + pvoptions = vtkProcessModule.GetProcessModule().GetOptions() + # if this process is from a parallel batch run in symmetric mpi mode + # then we may not have any points or cells on some processes in which + # case we'll probably be missing the point and cell data too. the + # check below makes sure that we avoid this situation. + if pvoptions.GetProcessType() != 0x40 or pvoptions.GetSymmetricMPIMode() == False \ + or len(self.Available) != 0: + raise ValueError("Could not locate array %s in the input." % arr) + + catt = self.Proxy.GetProperty("ColorAttributeType") + if att != None: + catt.SetData(att) + self.SMProperty.SetElement(0, arr) + self._UpdateProperty() + + Available = property(GetAvailable, None, None, \ + "This read-only property returns the list of arrays that can be colored by.") + + +class EnumerationProperty(VectorProperty): + """Subclass of VectorProperty that is applicable for enumeration type + properties.""" + + def GetElement(self, index): + """Returns the text for the given element if available. Returns + the numerical values otherwise.""" + val = self.SMProperty.GetElement(index) + domain = self.SMProperty.GetDomain("enum") + for i in range(domain.GetNumberOfEntries()): + if domain.GetEntryValue(i) == val: + return domain.GetEntryText(i) + return val + + def ConvertValue(self, value): + """Converts value to type suitable for vtSMProperty::SetElement()""" + if type(value) == str: + domain = self.SMProperty.GetDomain("enum") + if domain.HasEntryText(value): + return domain.GetEntryValueForText(value) + else: + raise ValueError("%s is not a valid value." % value) + return VectorProperty.ConvertValue(self, value) + + def GetAvailable(self): + "Returns the list of available values for the property." + retVal = [] + domain = self.SMProperty.GetDomain("enum") + for i in range(domain.GetNumberOfEntries()): + retVal.append(domain.GetEntryText(i)) + return retVal + + Available = property(GetAvailable, None, None, \ + "This read-only property contains the list of values that can be applied to this property.") + + +class FileNameProperty(VectorProperty): + """Property to set/get one or more file names. + This property updates the pipeline information everytime its value changes. + This is used to keep the array lists up to date.""" + + def _UpdateProperty(self): + "Pushes the value of this property to the server." + VectorProperty._UpdateProperty(self) + self.Proxy.FileNameChanged() + +class ArraySelectionProperty(VectorProperty): + "Property to select an array to be processed by a filter." + + def GetAssociation(self): + val = self.GetElement(3) + if val == "": + return None + for key, value in ASSOCIATIONS.iteritems(): + if value == int(val): + return key + + return None + + def GetArrayName(self): + return self.GetElement(4) + + def __len__(self): + """Returns the number of elements.""" + return 2 + + def __setitem__(self, idx, value): + raise RuntimeError, "This property cannot be accessed using __setitem__" + + def __getitem__(self, idx): + """Returns attribute type for index 0, array name for index 1""" + if isinstance(idx, slice): + indices = idx.indices(len(self)) + retVal = [] + for i in range(*indices): + if i >= 2 or i < 0: + raise IndexError + if i == 0: + retVal.append(self.GetAssociation()) + else: + retVal.append(self.GetArrayName()) + return retVal + elif idx >= 2 or idx < 0: + raise IndexError + + if i == 0: + return self.GetAssociation() + else: + return self.GetArrayName() + + def SetData(self, values): + """Allows setting of all values at once. Requires a single value, + a tuple or list.""" + if not isinstance(values, tuple) and \ + not isinstance(values, list): + values = (values,) + if len(values) == 1: + self.SMProperty.SetElement(4, values[0]) + elif len(values) == 2: + if isinstance(values[0], str): + val = str(ASSOCIATIONS[values[0]]) + else: + # In case user didn't specify valid association, + # just pick POINTS. + val = str(ASSOCIATIONS['POINTS']) + self.SMProperty.SetElement(3, str(val)) + self.SMProperty.SetElement(4, values[1]) + else: + raise RuntimeError, "Expected 1 or 2 values." + self._UpdateProperty() + + def UpdateDefault(self): + "Helper method to set default values." + if self.SMProperty.GetNumberOfElements() != 5: + return + if self.GetElement(4) != '' or \ + self.GetElement(3) != '': + return + + for i in range(0,3): + if self.GetElement(i) == '': + self.SMProperty.SetElement(i, '0') + al = self.SMProperty.GetDomain("array_list") + al.Update(self.SMProperty) + al.SetDefaultValues(self.SMProperty) + +class ArrayListProperty(VectorProperty): + """This property provides a simpler interface for selecting arrays. + Simply assign a list of arrays that should be loaded by the reader. + Use the Available property to get a list of available arrays.""" + + def __init__(self, proxy, smproperty): + VectorProperty.__init__(self, proxy, smproperty) + self.__arrays = [] + + def GetAvailable(self): + "Returns the list of available arrays" + dm = self.GetDomain("array_list") + retVal = [] + for i in range(dm.GetNumberOfStrings()): + retVal.append(dm.GetString(i)) + return retVal + + Available = property(GetAvailable, None, None, \ + "This read-only property contains the list of items that can be read by a reader.") + + def SelectAll(self): + "Selects all arrays." + self.SetData(self.Available) + + def DeselectAll(self): + "Deselects all arrays." + self.SetData([]) + + def __iter__(self): + """Implementation of the sequence API""" + return GenericIterator(self) + + def __len__(self): + """Returns the number of elements.""" + return len(self.GetData()) + + def __setitem__(self, idx, value): + """Given a list or tuple of values, sets a slice of values [min, max)""" + self.GetData() + if isinstance(idx, slice): + indices = idx.indices(len(self)) + for i, j in zip(range(*indices), value): + self.__arrays[i] = j + self.SetData(self.__arrays) + elif idx >= len(self) or idx < 0: + raise IndexError + else: + self.__arrays[idx] = self.ConvertValue(value) + self.SetData(self.__arrays) + + def __getitem__(self, idx): + """Returns the range [min, max) of elements. Raises an IndexError + exception if an argument is out of bounds.""" + self.GetData() + if isinstance(idx, slice): + indices = idx.indices(len(self)) + retVal = [] + for i in range(*indices): + retVal.append(self.__arrays[i]) + return retVal + elif idx >= len(self) or idx < 0: + raise IndexError + return self.__arrays[idx] + + def SetData(self, values): + """Allows setting of all values at once. Requires a single value, + a tuple or list.""" + # Clean up first + iup = self.SMProperty.GetImmediateUpdate() + self.SMProperty.SetImmediateUpdate(False) + # Clean up first + self.SMProperty.SetNumberOfElements(0) + if not isinstance(values, tuple) and \ + not isinstance(values, list): + values = (values,) + fullvalues = [] + + # WARNING: + # The order of the two loops below are delibrately set in this way + # so that values passed in will take precedence. + # This is needed for backward compatibility of the + # property ElementBlocks for vtkExodusIIReader. + # If you attemp to change this, please verify that + # python state files for opening old .ex2 file (<=3.14) still works. + for array in self.Available: + if not values.__contains__(array): + fullvalues.append(array) + fullvalues.append('0') + + for i in range(len(values)): + val = self.ConvertValue(values[i]) + fullvalues.append(val) + fullvalues.append('1') + + + i = 0 + for value in fullvalues: + self.SMProperty.SetElement(i, value) + i += 1 + + self._UpdateProperty() + self.SMProperty.SetImmediateUpdate(iup) + + def GetData(self): + "Returns all elements as a list." + property = self.SMProperty + nElems = property.GetNumberOfElements() + if nElems%2 != 0: + raise ValueError, "The SMProperty with XML label '%s' has a size that is not a multiple of 2." % property.GetXMLLabel() + self.__arrays = [] + for i in range(0, nElems, 2): + if self.GetElement(i+1) != '0': + self.__arrays.append(self.GetElement(i)) + return list(self.__arrays) + +class ProxyProperty(Property): + """A ProxyProperty provides access to one or more proxies. You can use + a slice to get one or more property values: + > proxy = property[2] + or + > proxies = property[0:5:2] + You can use a slice to set one or more property values: + > property[2] = proxy + or + > property[1:3] = (proxy1, proxy2) + You can also append and delete: + > property.append(proxy) + and + > del property[1:2] + + You can also remove all elements with Clear(). + + Note that some properties expect only 1 proxy and will complain if + you set the number of values to be something else. + """ + def __init__(self, proxy, smproperty): + """Default constructor. Stores a reference to the proxy. Also looks + at domains to find valid values.""" + Property.__init__(self, proxy, smproperty) + # Check to see if there is a proxy list domain and, if so, + # initialize ourself. (Should this go in ProxyProperty?) + listdomain = self.GetDomain('proxy_list') + if listdomain: + if listdomain.GetClassName() != 'vtkSMProxyListDomain': + raise ValueError, "Found a 'proxy_list' domain on an InputProperty that is not a ProxyListDomain." + pm = ProxyManager() + group = "pq_helper_proxies." + proxy.GetGlobalIDAsString() + if listdomain.GetNumberOfProxies() == 0: + for i in xrange(listdomain.GetNumberOfProxyTypes()): + igroup = listdomain.GetProxyGroup(i) + name = listdomain.GetProxyName(i) + iproxy = CreateProxy(igroup, name) + listdomain.AddProxy(iproxy) + pm.RegisterProxy(group, proxy.GetPropertyName(smproperty), iproxy) + listdomain.SetDefaultValues(self.SMProperty) + + def GetAvailable(self): + """If this proxy has a list domain, then this function returns the + strings you can use to select from the domain. If there is no such + list domain, the returned list is empty.""" + listdomain = self.GetDomain('proxy_list') + retval = [] + if listdomain: + for i in xrange(listdomain.GetNumberOfProxies()): + proxy = listdomain.GetProxy(i) + retval.append(proxy.GetXMLLabel()) + return retval + + Available = property(GetAvailable, None, None, + """This read only property is a list of strings you can + use to select from the list domain. If there is no + such list domain, the array is empty.""") + + def __iter__(self): + """Implementation of the sequence API""" + return GenericIterator(self) + + def __len__(self): + """Returns the number of elements.""" + return self.SMProperty.GetNumberOfProxies() + + def remove(self, proxy): + """Removes the first occurence of the proxy from the property.""" + self.SMProperty.RemoveProxy(proxy.SMProxy) + self._UpdateProperty() + + def __setitem__(self, idx, value): + """Given a list or tuple of values, sets a slice of values [min, max)""" + if isinstance(idx, slice): + indices = idx.indices(len(self)) + for i, j in zip(range(*indices), value): + self.SMProperty.SetProxy(i, j.SMProxy) + self._UpdateProperty() + elif idx >= len(self) or idx < 0: + raise IndexError + else: + self.SMProperty.SetProxy(idx, value.SMProxy) + self._UpdateProperty() + + def __delitem__(self,idx): + """Removes the element idx""" + if isinstance(idx, slice): + indices = idx.indices(len(self)) + # Collect the elements to delete to a new list first. + # Otherwise indices are screwed up during the actual + # remove loop. + toremove = [] + for i in range(*indices): + toremove.append(self[i]) + for i in toremove: + self.SMProperty.RemoveProxy(i.SMProxy) + self._UpdateProperty() + elif idx >= len(self) or idx < 0: + raise IndexError + else: + self.SMProperty.RemoveProxy(self[idx].SMProxy) + self._UpdateProperty() + + def __getitem__(self, idx): + """Returns the range [min, max) of elements. Raises an IndexError + exception if an argument is out of bounds.""" + if isinstance(idx, slice): + indices = idx.indices(len(self)) + retVal = [] + for i in range(*indices): + retVal.append(_getPyProxy(self.SMProperty.GetProxy(i))) + return retVal + elif idx >= len(self) or idx < 0: + raise IndexError + return _getPyProxy(self.SMProperty.GetProxy(idx)) + + def __getattr__(self, name): + "Unknown attribute requests get forwarded to SMProperty." + return getattr(self.SMProperty, name) + + def index(self, proxy): + idx = 0 + for px in self: + ## VSV: == + if proxy.IsSame(px): + return idx + idx += 1 + raise ValueError("proxy is not in the list.") + + def append(self, proxy): + "Appends the given proxy to the property values." + self.SMProperty.AddProxy(proxy.SMProxy) + self._UpdateProperty() + + def GetData(self): + "Returns all elements as either a list or a single value." + property = self.SMProperty + if property.GetRepeatable() or property.GetNumberOfProxies() > 1: + return self[0:len(self)] + else: + if property.GetNumberOfProxies() > 0: + return _getPyProxy(property.GetProxy(0)) + return None + + def SetData(self, values): + """Allows setting of all values at once. Requires a single value, + a tuple or list.""" + if isinstance(values, str): + position = -1 + try: + position = self.Available.index(values) + except: + raise ValueError, values + " is not a valid object in the domain." + values = self.GetDomain('proxy_list').GetProxy(position) + if not isinstance(values, tuple) and \ + not isinstance(values, list): + values = (values,) + self.SMProperty.RemoveAllProxies() + for value in values: + if isinstance(value, Proxy): + value_proxy = value.SMProxy + else: + value_proxy = value + self.SMProperty.AddProxy(value_proxy) + self._UpdateProperty() + + def Clear(self): + "Removes all elements." + self.SMProperty.RemoveAllProxies() + self._UpdateProperty() + +class InputProperty(ProxyProperty): + """An InputProperty allows making pipeline connections. You can set either + a source proxy or an OutputProperty to an input property: + + > property[0] = proxy + or + > property[0] = OuputPort(proxy, 1) + + > property.append(proxy) + or + > property.append(OutputPort(proxy, 0)) + """ + def __setitem__(self, idx, value): + """Given a list or tuple of values, sets a slice of values [min, max)""" + if isinstance(idx, slice): + indices = idx.indices(len(self)) + for i, j in zip(range(*indices), value): + op = value[i-min] + self.SMProperty.SetInputConnection(i, op.SMProxy, op.Port) + self._UpdateProperty() + elif idx >= len(self) or idx < 0: + raise IndexError + else: + self.SMProperty.SetInputConnection(idx, value.SMProxy, value.Port) + self._UpdateProperty() + + def __getitem__(self, idx): + """Returns the range [min, max) of elements. Raises an IndexError + exception if an argument is out of bounds.""" + if isinstance(idx, slice): + indices = idx.indices(len(self)) + retVal = [] + for i in range(*indices): + port = None + if self.SMProperty.GetProxy(i): + port = OutputPort(_getPyProxy(self.SMProperty.GetProxy(i)),\ + self.SMProperty.GetOutputPortForConnection(i)) + retVal.append(port) + return retVal + elif idx >= len(self) or idx < 0: + raise IndexError + return OutputPort(_getPyProxy(self.SMProperty.GetProxy(idx)),\ + self.SMProperty.GetOutputPortForConnection(idx)) + + def append(self, value): + """Appends the given proxy to the property values. + Accepts Proxy or OutputPort objects.""" + self.SMProperty.AddInputConnection(value.SMProxy, value.Port) + self._UpdateProperty() + + def GetData(self): + """Returns all elements as either a list of OutputPort objects or + a single OutputPort object.""" + property = self.SMProperty + if property.GetRepeatable() or property.GetNumberOfProxies() > 1: + return self[0:len(self)] + else: + if property.GetNumberOfProxies() > 0: + return OutputPort(_getPyProxy(property.GetProxy(0)),\ + self.SMProperty.GetOutputPortForConnection(0)) + return None + + def SetData(self, values): + """Allows setting of all values at once. Requires a single value, + a tuple or list. Accepts Proxy or OutputPort objects.""" + if isinstance(values, str): + ProxyProperty.SetData(self, values) + return + if not isinstance(values, tuple) and \ + not isinstance(values, list): + values = (values,) + self.SMProperty.RemoveAllProxies() + for value in values: + if value: + self.SMProperty.AddInputConnection(value.SMProxy, value.Port) + self._UpdateProperty() + + def _UpdateProperty(self): + "Pushes the value of this property to the server." + ProxyProperty._UpdateProperty(self) + iter = PropertyIterator(self.Proxy) + for prop in iter: + if isinstance(prop, ArraySelectionProperty): + prop.UpdateDefault() + + +class DataInformation(object): + """DataInformation is a contained for meta-data associated with an + output data. + + DataInformation is a python wrapper around a vtkPVDataInformation. + In addition to proving all methods of a vtkPVDataInformation, it provides + a few convenience methods. + + Please note that some of the methods accessible through the DataInformation + class are not listed by help() because the DataInformation objects forward + unresolved attributes to the underlying object. To get the full list, + see also dir(proxy.DataInformation). + See also the doxygen based documentation of the vtkPVDataInformation C++ + class. + """ + def __init__(self, dataInformation, proxy, idx): + """Default constructor. Requires a vtkPVDataInformation, a source proxy + and an output port id.""" + self.DataInformation = dataInformation + self.Proxy = proxy + self.Idx = idx + + def Update(self): + """****Deprecated**** There is no reason anymore to use this method + explicitly, it is called automatically when one gets any value from the + data information object. + Update the data information if necessary. Note that this + does not cause execution of the underlying object. In certain + cases, you may have to call UpdatePipeline() on the proxy.""" + if self.Proxy: + self.Proxy.GetDataInformation(self.Idx) + + def GetDataSetType(self): + """Returns the dataset type as defined in vtkDataObjectTypes.""" + self.Update() + if not self.DataInformation: + raise RuntimeError, "No data information is available" + if self.DataInformation.GetCompositeDataSetType() > -1: + return self.DataInformation.GetCompositeDataSetType() + return self.DataInformation.GetDataSetType() + + def GetDataSetTypeAsString(self): + """Returns the dataset type as a user-friendly string. This is + not the same as the enumaration used by VTK""" + return vtk.vtkDataObjectTypes.GetClassNameFromTypeId(self.GetDataSetType()) + + def __getattr__(self, name): + """Forwards unknown attribute requests to the underlying + vtkPVInformation.""" + if not self.DataInformation: + raise AttributeError("class has no attribute %s" % name) + return None + self.Update() + return getattr(self.DataInformation, name) + +class ArrayInformation(object): + """Meta-information associated with an array. Use the Name + attribute to get the array name. + + Please note that some of the methods accessible through the ArrayInformation + class are not listed by help() because the ArrayInformation objects forward + unresolved attributes to the underlying object. + See the doxygen based documentation of the vtkPVArrayInformation C++ + class for a full list. + """ + def __init__(self, proxy, field, name): + self.Proxy = proxy + self.FieldData = field + self.Name = name + + def __getattr__(self, name): + """Forward unknown methods to vtkPVArrayInformation""" + array = self.FieldData.GetFieldData().GetArrayInformation(self.Name) + if not array: return None + return getattr(array, name) + + def __repr__(self): + """Returns a user-friendly representation string.""" + return "Array: " + self.Name + + def GetRange(self, component=0): + """Given a component, returns its value range as a tuple of 2 values.""" + array = self.FieldData.GetFieldData().GetArrayInformation(self.Name) + range = array.GetComponentRange(component) + return (range[0], range[1]) + +class FieldDataInformationIterator(object): + """Iterator for FieldDataInformation""" + + def __init__(self, info, items=False): + self.FieldDataInformation = info + self.index = 0 + self.items = items + + def __iter__(self): + return self + + def next(self): + if self.index >= self.FieldDataInformation.GetNumberOfArrays(): + raise StopIteration + + self.index += 1 + ai = self.FieldDataInformation[self.index-1] + if self.items: + return (ai.GetName(), ai) + else: + return ai + + +class FieldDataInformation(object): + """Meta-data for a field of an output object (point data, cell data etc...). + Provides easy access to the arrays using the slice interface: + > narrays = len(field_info) + > for i in range(narrays): + > array_info = field_info[i] + + Full slice interface is supported: + > arrays = field_info[0:5:3] + where arrays is a list. + + Array access by name is also possible: + > array_info = field_info['Temperature'] + + The number of arrays can also be accessed using the NumberOfArrays + property. + """ + def __init__(self, proxy, idx, field): + self.Proxy = proxy + self.OutputPort = idx + self.FieldData = field + + def GetFieldData(self): + """Convenience method to get the underlying + vtkPVDataSetAttributesInformation""" + return getattr(self.Proxy.GetDataInformation(self.OutputPort), "Get%sInformation" % self.FieldData)() + + def GetNumberOfArrays(self): + """Returns the number of arrays.""" + self.Proxy.UpdatePipeline() + return self.GetFieldData().GetNumberOfArrays() + + def GetArray(self, idx): + """Given an index or a string, returns an array information. + Raises IndexError if the index is out of bounds.""" + self.Proxy.UpdatePipeline() + if not self.GetFieldData().GetArrayInformation(idx): + return None + if isinstance(idx, str): + return ArrayInformation(self.Proxy, self, idx) + elif idx >= len(self) or idx < 0: + raise IndexError + return ArrayInformation(self.Proxy, self, self.GetFieldData().GetArrayInformation(idx).GetName()) + + def __len__(self): + """Returns the number of arrays.""" + return self.GetNumberOfArrays() + + def __getitem__(self, idx): + """Implements the [] operator. Accepts an array name.""" + if isinstance(idx, slice): + indices = idx.indices(self.GetNumberOfArrays()) + retVal = [] + for i in range(*indices): + retVal.append(self.GetArray(i)) + return retVal + return self.GetArray(idx) + + def keys(self): + """Implementation of the dictionary API""" + kys = [] + narrays = self.GetNumberOfArrays() + for i in range(narrays): + kys.append(self.GetArray(i).GetName()) + return kys + + def values(self): + """Implementation of the dictionary API""" + vals = [] + narrays = self.GetNumberOfArrays() + for i in range(narrays): + vals.append(self.GetArray(i)) + return vals + + def iteritems(self): + """Implementation of the dictionary API""" + return FieldDataInformationIterator(self, True) + + def items(self): + """Implementation of the dictionary API""" + itms = [] + narrays = self.GetNumberOfArrays() + for i in range(narrays): + ai = self.GetArray(i) + itms.append((ai.GetName(), ai)) + return itms + + def has_key(self, key): + """Implementation of the dictionary API""" + if self.GetArray(key): + return True + return False + + def __iter__(self): + """Implementation of the dictionary API""" + return FieldDataInformationIterator(self) + + def __getattr__(self, name): + """Forwards unknown attributes to the underlying + vtkPVDataSetAttributesInformation""" + array = self.GetArray(name) + if array: return array + raise AttributeError("class has no attribute %s" % name) + return None + + NumberOfArrays = property(GetNumberOfArrays, None, None, "Returns the number of arrays.") + +def OutputPort(proxy, outputPort=0): + if not Proxy: + return None + if isinstance(outputPort, str): + outputPort = proxy.GetOutputPortIndex(outputPort) + if outputPort >= proxy.GetNumberOfOutputPorts(): + return None + if proxy.Port == outputPort: + return proxy + newinstance = _getPyProxy(proxy.SMProxy, outputPort) + newinstance.Port = outputPort + newinstance._Proxy__Properties = proxy._Proxy__Properties + return newinstance + +class ProxyManager(object): + """When running scripts from the python shell in the ParaView application, + registering proxies with the proxy manager is the only mechanism to + notify the graphical user interface (GUI) that a proxy + exists. Therefore, unless a proxy is registered, it will not show up in + the user interface. Also, the proxy manager is the only way to get + access to proxies created using the GUI. Proxies created using the GUI + are automatically registered under an appropriate group (sources, + filters, representations and views). To get access to these objects, + you can use proxyManager.GetProxy(group, name). The name is the same + as the name shown in the pipeline browser. + + This class is a python wrapper for vtkSMProxyManager. Note that the + underlying vtkSMProxyManager is a singleton. All instances of this + class will refer to the same object. In addition to all methods provided by + vtkSMProxyManager (all unknown attribute requests are forwarded + to the vtkSMProxyManager), this class provides several convenience + methods. + + Please note that some of the methods accessible through the ProxyManager + class are not listed by help() because the ProxyManager objects forwards + unresolved attributes to the underlying object. To get the full list, + see also dir(proxy.SMProxyManager). See also the doxygen based documentation + of the vtkSMProxyManager C++ class. + """ + + def __init__(self, session=None): + """Constructor. Assigned self.SMProxyManager to + vtkSMProxyManager.GetProxyManager().""" + global ActiveConnection + if not session: + session = ActiveConnection.Session + self.SMProxyManager = session.GetSessionProxyManager() + + def RegisterProxy(self, group, name, aProxy): + """Registers a proxy (either SMProxy or proxy) with the + server manager""" + if isinstance(aProxy, Proxy): + self.SMProxyManager.RegisterProxy(group, name, aProxy.SMProxy) + else: + self.SMProxyManager.RegisterProxy(group, name, aProxy) + + def NewProxy(self, group, name): + """Creates a new proxy of given group and name and returns an SMProxy. + Note that this is a server manager object. You should normally create + proxies using the class objects. For example: + obj = servermanager.sources.SphereSource()""" + if not self.SMProxyManager: + return None + aProxy = self.SMProxyManager.NewProxy(group, name, "NULL") + if not aProxy: + return None + aProxy.UnRegister(None) + return aProxy + + def GetProxy(self, group, name): + """Returns a Proxy registered under a group and name""" + if not self.SMProxyManager: + return None + aProxy = self.SMProxyManager.GetProxy(group, name) + if not aProxy: + return None + return _getPyProxy(aProxy) + + def GetPrototypeProxy(self, group, name): + """Returns a prototype proxy given a group and name. This is an + SMProxy. This is a low-level method. You should not normally + have to call it.""" + if not self.SMProxyManager: + return None + aProxy = self.SMProxyManager.GetPrototypeProxy(group, name) + if not aProxy: + return None + return aProxy + + def GetProxiesInGroup(self, groupname): + """Returns a map of proxies in a particular group.""" + proxies = {} + iter = self.NewGroupIterator(groupname) + for aProxy in iter: + proxies[(iter.GetKey(), aProxy.GetGlobalIDAsString())] = aProxy + return proxies + + def UnRegisterProxy(self, groupname, proxyname, aProxy): + """Unregisters a proxy.""" + if not self.SMProxyManager: + return + if aProxy != None and isinstance(aProxy,Proxy): + aProxy = aProxy.SMProxy + if aProxy: + self.SMProxyManager.UnRegisterProxy(groupname, proxyname, aProxy) + + def GetProxies(self, groupname, proxyname): + """Returns all proxies registered under the given group with the + given name. Note that it is possible to register more than one + proxy with the same name in the same group. Because the proxies + are different, there is no conflict. Use this method instead of + GetProxy() if you know that there are more than one proxy registered + with this name.""" + if not self.SMProxyManager: + return [] + collection = vtk.vtkCollection() + result = [] + self.SMProxyManager.GetProxies(groupname, proxyname, collection) + for i in range(0, collection.GetNumberOfItems()): + aProxy = _getPyProxy(collection.GetItemAsObject(i)) + if aProxy: + result.append(aProxy) + + return result + + def __iter__(self): + """Returns a new ProxyIterator.""" + iter = ProxyIterator() + iter.Begin() + return iter + + def NewGroupIterator(self, group_name): + """Returns a ProxyIterator for a group. The resulting object + can be used to traverse the proxies that are in the given + group.""" + iter = self.__iter__() + iter.SetModeToOneGroup() + iter.Begin(group_name) + return iter + + def NewDefinitionIterator(self, groupname=None): + """Returns an iterator that can be used to iterate over + all groups and types of proxies that the proxy manager + can create.""" + iter = None + if groupname != None: + iter = ProxyDefinitionIterator(self.GetProxyDefinitionManager().NewSingleGroupIterator(groupname,0)) + else: + iter = ProxyDefinitionIterator(self.GetProxyDefinitionManager().NewIterator(0)) + + return iter + + def __ConvertArgumentsAndCall(self, *args): + newArgs = [] + for arg in args: + if issubclass(type(arg), Proxy) or isinstance(arg, Proxy): + newArgs.append(arg.SMProxy) + else: + newArgs.append(arg) + func = getattr(self.SMProxyManager, self.__LastAttrName) + retVal = func(*newArgs) + if type(retVal) is type(self.SMProxyManager) and retVal.IsA("vtkSMProxy"): + return _getPyProxy(retVal) + else: + return retVal + + def __getattr__(self, name): + """Returns attribute from the ProxyManager""" + try: + pmAttr = getattr(self.SMProxyManager, name) + self.__LastAttrName = name + return self.__ConvertArgumentsAndCall + except: + pass + return getattr(self.SMProxyManager, name) + + def LoadState(self, filename, loader = None): + self.SMProxyManager.LoadXMLState(filename, loader) + + def SaveState(self, filename): + self.SMProxyManager.SaveXMLState(filename) + +class PropertyIterator(object): + """Wrapper for a vtkSMPropertyIterator class to satisfy + the python iterator protocol. Note that the list of + properties can also be obtained from the class object's + dictionary. + See the doxygen documentation for vtkSMPropertyIterator C++ + class for details. + """ + + def __init__(self, aProxy): + self.SMIterator = aProxy.NewPropertyIterator() + if self.SMIterator: + self.SMIterator.UnRegister(None) + self.SMIterator.Begin() + self.Key = None + self.PropertyLabel = None + self.Proxy = aProxy + + def __iter__(self): + return self + + def next(self): + if not self.SMIterator: + raise StopIteration + + if self.SMIterator.IsAtEnd(): + self.Key = None + raise StopIteration + self.Key = self.SMIterator.GetKey() + self.PropertyLabel = self.SMIterator.GetPropertyLabel() + self.SMIterator.Next() + return self.Proxy.GetProperty(self.Key) + + def GetProxy(self): + """Returns the proxy for the property last returned by the call to + 'next()'""" + return self.Proxy + + def GetKey(self): + """Returns the key for the property last returned by the call to + 'next()' """ + return self.Key + + def GetProperty(self): + """Returns the property last returned by the call to 'next()' """ + return self.Proxy.GetProperty(self.Key) + + def __getattr__(self, name): + """returns attributes from the vtkSMPropertyIterator.""" + return getattr(self.SMIterator, name) + +class ProxyDefinitionIterator(object): + """Wrapper for a vtkPVProxyDefinitionIterator class to satisfy + the python iterator protocol. + See the doxygen documentation of the vtkPVProxyDefinitionIterator + C++ class for more information.""" + def __init__(self, iter): + self.SMIterator = iter + if self.SMIterator: + self.SMIterator.UnRegister(None) + self.SMIterator.InitTraversal() + self.Group = None + self.Key = None + + def __iter__(self): + return self + + def next(self): + if self.SMIterator.IsDoneWithTraversal(): + self.Group = None + self.Key = None + raise StopIteration + self.Group = self.SMIterator.GetGroupName() + self.Key = self.SMIterator.GetProxyName() + self.SMIterator.GoToNextItem() + return {"group": self.Group, "key":self.Key } + + def GetProxyName(self): + """Returns the key for the proxy definition last returned by the call + to 'next()' """ + return self.Key + + def GetGroup(self): + """Returns the group for the proxy definition last returned by the + call to 'next()' """ + return self.Group + + def __getattr__(self, name): + """returns attributes from the vtkPVProxyDefinitionIterator.""" + return getattr(self.SMIterator, name) + + +class ProxyIterator(object): + """Wrapper for a vtkSMProxyIterator class to satisfy the + python iterator protocol. + See the doxygen documentation of vtkSMProxyIterator C++ class for + more information. + """ + def __init__(self): + self.SMIterator = vtkSMProxyIterator() + self.SMIterator.SetSession(ActiveConnection.Session) + self.SMIterator.Begin() + self.AProxy = None + self.Group = None + self.Key = None + + def __iter__(self): + return self + + def next(self): + if self.SMIterator.IsAtEnd(): + self.AProxy = None + self.Group = None + self.Key = None + raise StopIteration + return None + self.AProxy = _getPyProxy(self.SMIterator.GetProxy()) + self.Group = self.SMIterator.GetGroup() + self.Key = self.SMIterator.GetKey() + self.SMIterator.Next() + return self.AProxy + + def GetProxy(self): + """Returns the proxy last returned by the call to 'next()'""" + return self.AProxy + + def GetKey(self): + """Returns the key for the proxy last returned by the call to + 'next()' """ + return self.Key + + def GetGroup(self): + """Returns the group for the proxy last returned by the call to + 'next()' """ + return self.Group + + def __getattr__(self, name): + """returns attributes from the vtkSMProxyIterator.""" + return getattr(self.SMIterator, name) + +# Caution: Observers must be global methods otherwise we run into memory +# leak when the interpreter get reset from the C++ layer. +def _update_definitions(caller, event): + updateModules(ActiveConnection.Modules) + +class Connection(object): + """ + This is a python representation for a session/connection. + """ + def __init__(self, connectionId, session): + """Default constructor. Creates a Connection with the given + ID, all other data members initialized to None.""" + global MultiServerConnections + global ActiveConnection + self.ID = connectionId + self.Session = session + self.Modules = PVModule() + self.Alive = True + self.DefinitionObserverTag = 0 + self.CustomDefinitionObserverTag = 0 + if MultiServerConnections == None and ActiveConnection: + raise RuntimeError, "Concurrent connections not supported!" + if MultiServerConnections != None and not self in MultiServerConnections: + MultiServerConnections.append(self) + ActiveConnection = self + __InitAfterConnect__(self) + __exposeActiveModules__() + + def __eq__(self, other): + "Returns true if the connection ids are the same." + return (self.ID == other.ID) + + def __repr__(self): + """User friendly string representation""" + return "Connection (%s) [%d]" % (self.Session.GetURI(), self.ID) + + def GetURI(self): + """Get URI of the connection""" + return self.Session.GetURI() + + def IsRemote(self): + """Returns True if the connection to a remote server, False if + it is local (built-in)""" + if self.Session.IsA("vtkSMSessionClient"): + return True + return False + + def GetNumberOfDataPartitions(self): + """Returns the number of partitions on the data server for this + connection""" + return self.Session.GetServerInformation().GetNumberOfProcesses() + + def AttachDefinitionUpdater(self): + """Attach observer to automatically update modules when needed.""" + # VTN: Observers are not supported + # ProxyDefinitionsUpdated = 2000 +## self.DefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2000, _update_definitions) + # CompoundProxyDefinitionsUpdated = 2001 +## self.CustomDefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2001, _update_definitions) + pass + + def close(self): + if self.DefinitionObserverTag: + self.Session.GetProxyDefinitionManager().RemoveObserver(self.DefinitionObserverTag) + self.Session.GetProxyDefinitionManager().RemoveObserver(self.CustomDefinitionObserverTag) + self.Session = None + self.Modules = None + self.Alive = False + + def __del__(self): + if self.Alive: + self.close() + +def SaveState(filename): + """Given a state filename, saves the state of objects registered + with the proxy manager.""" + pm = ProxyManager() + pm.SaveState(filename) + +def LoadState(filename, connection=None): + """Given a state filename and an optional connection, loads the server + manager state.""" + if not connection: + connection = ActiveConnection + if not connection: + raise RuntimeError, "Cannot load state without a connection" + pm = ProxyManager() + pm.LoadState(filename, None) + views = GetRenderViews() + for view in views: + # Make sure that the client window size matches the + # ViewSize property. In paraview, the GUI takes care + # of this. + if view.GetClassName() == "vtkSMIceTDesktopRenderViewProxy": + view.GetRenderWindow().SetSize(view.ViewSize[0], \ + view.ViewSize[1]) + +def InitFromGUI(): + """ + Method used to initialize the Python Shell from the ParaView GUI. + """ + global fromGUI, ActiveConnection + if not fromGUI: + print "from paraview.simple import *" + fromGUI = True + # ToggleProgressPrinting() ### FIXME COLLABORATION + enableMultiServer(vtkProcessModule.GetProcessModule().GetMultipleSessionsSupport()) + iter = vtkProcessModule.GetProcessModule().NewSessionIterator(); + iter.InitTraversal() + ActiveConnection = None + activeSession = vtkSMProxyManager.GetProxyManager().GetActiveSession() + tmpActiveConnection = None + while not iter.IsDoneWithTraversal(): + c = Connection(iter.GetCurrentSessionId(), iter.GetCurrentSession()) + if c.Session == activeSession: + tmpActiveConnection = c + iter.GoToNextItem() + iter.UnRegister(None) + if tmpActiveConnection: + ActiveConnection = tmpActiveConnection + +def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=22221): + """ + Use this function call to create a new session. On success, + it returns a vtkSMSession object that abstracts the connection. + Otherwise, it returns None. + There are several ways in which this function can be called: + * When called with no arguments, it creates a new session + to the built-in server on the client itself. + * When called with ds_host and ds_port arguments, it + attempts to connect to a server(data and render server on the same server) + on the indicated host:port. + * When called with ds_host, ds_port, rs_host, rs_port, it + creates a new connection to the data server on ds_host:ds_port and to the + render server on rs_host: rs_port. + """ + if ds_host == None: + session = vtkSMSession() + elif rs_host == None: + session = vtkSMSessionClient() + session.Connect("cs://%s:%d" % (ds_host, ds_port)) + else: + session = vtkSMSessionClient() + session.Connect("cdsrs://%s:%d/%s:%d" % (ds_host, ds_port, rs_host, rs_port)) + id = vtkProcessModule.GetProcessModule().RegisterSession(session) + connection = Connection(id, session) + return connection + +def ReverseConnect(port=11111): + """ + Use this function call to create a new session. On success, + it returns a Session object that abstracts the connection. + Otherwise, it returns None. + In reverse connection mode, the client waits for a connection + from the server (client has to be started first). The server + then connects to the client (run pvserver with -rc and -ch + option). + The optional port specified the port to listen to. + """ + session = vtkSMSessionClient() + session.Connect("csrc://hostname:" + port) + id = vtkProcessModule.GetProcessModule().RegisterSession(session) + connection = Connection(id, session) + return connection + +def Disconnect(session=None): + """Disconnects the connection. Make sure to clear the proxy manager + first.""" + global ActiveConnection + global MultiServerConnections + global fromGUI + if fromGUI: + # Let the UI know that we want to disconnect + ActiveConnection.Session.InvokeEvent('ExitEvent') + return + if ActiveConnection and (not session or session == ActiveConnection.Session): + session = ActiveConnection.Session + if MultiServerConnections: + MultiServerConnections.remove(ActiveConnection) + ActiveConnection.close() + ActiveConnection = None + switchActiveConnection() + else: + ActiveConnection.close() + ActiveConnection = None + elif MultiServerConnections: + for connection in MultiServerConnections: + if connection.Session == session: + connection.close() + MultiServerConnections.remove(connection) + if session: + vtkProcessModule.GetProcessModule().UnRegisterSession(session) + return + +def CreateProxy(xml_group, xml_name, session=None): + """Creates a proxy. If session is set, the proxy's session is + set accordingly. If session is None, the current Session is used, if + present. You should not have to use method normally. Instantiate the + appropriate class from the appropriate module, for example: + sph = servermanager.sources.SphereSource()""" + global ActiveConnection + if not session: + session = ActiveConnection.Session + if not session: + raise RuntimeError, "Cannot create objects without a session." + pxm = ProxyManager(session) + return pxm.NewProxy(xml_group, xml_name) + +def GetRenderView(connection=None): + """Return the render view in use. If more than one render view is in + use, return the first one.""" + + render_module = None + for aProxy in ProxyManager(): + if aProxy.IsA("vtkSMRenderViewProxy"): + render_module = aProxy + break + return render_module + +def GetRenderViews(connection=None): + """Returns the set of all render views.""" + render_modules = [] + for aProxy in ProxyManager(): + if aProxy.IsA("vtkSMRenderViewProxy"): + render_modules.append(aProxy) + return render_modules + +def GetContextViews(connection=None): + """Returns the set of all context views.""" + context_modules = [] + for aProxy in ProxyManager(): + if aProxy.IsA("vtkSMContextViewProxy"): + context_modules.append(aProxy) + return context_modules + +def CreateRenderView(session=None, **extraArgs): + """Creates a render window on the particular session. If session + is not specified, then the active session is used, if available. + + This method can also be used to initialize properties by passing + keyword arguments where the key is the name of the property. In addition + registrationGroup and registrationName (optional) can be specified (as + keyword arguments) to automatically register the proxy with the proxy + manager.""" + return _create_view("RenderView", session, **extraArgs) + +def _create_view(view_xml_name, session=None, **extraArgs): + """Creates a view on the particular session. If session + is not specified, then the active session is used, if available. + This method can also be used to initialize properties by passing + keyword arguments where the key is the name of the property.""" + if not session: + session = ActiveConnection.Session + if not session: + raise RuntimeError, "Cannot create view without session." + pxm = ProxyManager() + view_module = None + if view_xml_name: + view_module = CreateProxy("views", view_xml_name, session) + if not view_module: + return None + extraArgs['proxy'] = view_module + python_proxy_name = _make_name_valid(view_module.GetXMLName()) + proxy = rendering.__dict__[python_proxy_name](**extraArgs) + return proxy + +def GetRepresentation(aProxy, view): + for rep in view.Representations: + #VSV: == + try: isRep = rep.Input.IsSame(aProxy) + except: isRep = False + if isRep: return rep + return None + +def CreateRepresentation(aProxy, view, **extraArgs): + """Creates a representation for the proxy and adds it to the render + module. + + This method can also be used to initialize properties by passing + keyword arguments where the key is the name of the property.In addition + registrationGroup and registrationName (optional) can be specified (as + keyword arguments) to automatically register the proxy with the proxy + manager. + + This method tries to create the best possible representation for the given + proxy in the given view. Additionally, the user can specify proxyName + (optional) to create a representation of a particular type.""" + + global rendering + if not aProxy: + raise RuntimeError, "proxy argument cannot be None." + if not view: + raise RuntimeError, "view argument cannot be None." + if "proxyName" in extraArgs: + display = CreateProxy("representations", extraArgs['proxyName'], None) + del extraArgs['proxyName'] + else: + display = view.SMProxy.CreateDefaultRepresentation(aProxy.SMProxy, 0) + if display: + display.UnRegister(None) + if not display: + return None + extraArgs['proxy'] = display + proxy = rendering.__dict__[display.GetXMLName()](**extraArgs) + proxy.Input = aProxy + proxy.UpdateVTKObjects() + view.Representations.append(proxy) + return proxy + +class _ModuleLoader(object): + def find_module(self, fullname, path=None): + if vtkPVPythonModule.HasModule(fullname): + return self + else: + return None + def load_module(self, fullname): + import imp + moduleInfo = vtkPVPythonModule.GetModule(fullname) + if not moduleInfo: + raise ImportError + module = sys.modules.setdefault(fullname, imp.new_module(fullname)) + module.__file__ = "<%s>" % moduleInfo.GetFullName() + module.__loader__ = self + if moduleInfo.GetIsPackage: + module.__path__ = moduleInfo.GetFullName() + code = compile(moduleInfo.GetSource(), module.__file__, 'exec') + exec code in module.__dict__ + return module + +def LoadXML(xmlstring): + """DEPRECATED. Given a server manager XML as a string, parse and process it.""" + raise RuntimeError, "Deprecated. Use LoadPlugin(...) instead." + + +def LoadPlugin(filename, remote=True, connection=None): + """ Given a filename and a session (optional, otherwise uses + ActiveConnection), loads a plugin. It then updates the sources, + filters and rendering modules.""" + + if not connection: + connection = ActiveConnection + if not connection: + raise RuntimeError, "Cannot load a plugin without a connection." + plm = vtkSMProxyManager.GetProxyManager().GetPluginManager() + + if remote: + status = plm.LoadRemotePlugin(filename, connection.Session) + else: + status = plm.LoadLocalPlugin(filename) + + # shouldn't the extension check happend before attempting to load the plugin? + if not status: + raise RuntimeError, "Problem loading plugin %s" % (filename) + else: + # we should never have to call this. The modules should update automatically. + updateModules(connection.Modules) + + +def Fetch(input, arg1=None, arg2=None, idx=0): + """ + A convenience method that moves data from the server to the client, + optionally performing some operation on the data as it moves. + The input argument is the name of the (proxy for a) source or filter + whose output is needed on the client. + + You can use Fetch to do three things: + + If arg1 is None (the default) then all of the data is brought to the client. + In parallel runs an appropriate append Filter merges the + data on each processor into one data object. The filter chosen will be + vtkAppendPolyData for vtkPolyData, vtkAppendRectilinearGrid for + vtkRectilinearGrid, vtkMultiBlockDataGroupFilter for vtkCompositeData, + and vtkAppendFilter for anything else. + + If arg1 is an integer then one particular processor's output is brought to + the client. In serial runs the arg is ignored. If you have a filter that + computes results in parallel and brings them to the root node, then set + arg to be 0. + + If arg1 and arg2 are a algorithms, for example vtkMinMax, the algorithm + will be applied to the data to obtain some result. Here arg1 will be + applied pre-gather and arg2 will be applied post-gather. In parallel + runs the algorithm will be run on each processor to make intermediate + results and then again on the root processor over all of the + intermediate results to create a global result. + + Optional argument idx is used to specify the output port number to fetch the + data from. Default is port 0. + """ + + import types + + reducer = filters.ReductionFilter(Input=OutputPort(input,idx)) + + #create the pipeline that reduces and transmits the data + if arg1 == None: + cdinfo = input.GetDataInformation(idx).GetCompositeDataInformation() + if cdinfo.GetDataIsComposite(): + print "use composite data append" + reducer.PostGatherHelperName = "vtkMultiBlockDataGroupFilter" + + elif input.GetDataInformation(idx).GetDataClassName() == "vtkPolyData": + print "use append poly data filter" + reducer.PostGatherHelperName = "vtkAppendPolyData" + + elif input.GetDataInformation(idx).GetDataClassName() == "vtkRectilinearGrid": + print "use append rectilinear grid filter" + reducer.PostGatherHelperName = "vtkAppendRectilinearGrid" + + elif input.GetDataInformation(idx).IsA("vtkDataSet"): + print "use unstructured append filter" + reducer.PostGatherHelperName = "vtkAppendFilter" + + elif type(arg1) is types.IntType: + reducer.PassThrough = arg1 + + else: + reducer.PreGatherHelper = arg1 + reducer.PostGatherHelper = arg2 + + # reduce + reducer.UpdatePipeline() + dataInfo = reducer.GetDataInformation(0) + dataType = dataInfo.GetDataSetType() + if dataInfo.GetCompositeDataSetType() > 0: + dataType = dataInfo.GetCompositeDataSetType() + + fetcher = filters.ClientServerMoveData(Input=reducer) + fetcher.OutputDataType = dataType + fetcher.WholeExtent = dataInfo.GetExtent()[:] + #fetch + fetcher.UpdatePipeline() + + op = fetcher.GetClientSideObject().GetOutputDataObject(0) + opc = op.NewInstance() + opc.ShallowCopy(op) + opc.UnRegister(None) + return opc + +def AnimateReader(reader, view, filename=None): + """This is a utility function that, given a reader and a view + animates over all time steps of the reader. If the optional + filename is provided, a movie is created (type depends on the + extension of the filename.""" + if not reader: + raise RuntimeError, "No reader was specified, cannot animate." + if not view: + raise RuntimeError, "No view was specified, cannot animate." + # Create an animation scene + scene = animation.AnimationScene() + + # We need to have the reader and the view registered with + # the time keeper. This is how the scene gets its time values. + try: + tk = ProxyManager().GetProxiesInGroup("timekeeper").values()[0] + scene.TimeKeeper = tk + except IndexError: + tk = misc.TimeKeeper() + scene.TimeKeeper = tk + + if not reader in tk.TimeSources: + tk.TimeSources.append(reader) + if not view in tk.Views: + tk.Views.append(view) + + + # with 1 view + scene.ViewModules = [view] + # Update the reader to get the time information + reader.UpdatePipelineInformation() + # Animate from 1st time step to last + scene.StartTime = reader.TimestepValues.GetData()[0] + scene.EndTime = reader.TimestepValues.GetData()[-1] + + # Each frame will correspond to a time step + scene.PlayMode = 2 #Snap To Timesteps + + # Create a special animation cue for time. + cue = animation.TimeAnimationCue() + cue.AnimatedProxy = view + cue.AnimatedPropertyName = "ViewTime" + scene.Cues = [cue] + + if filename: + writer = vtkSMAnimationSceneImageWriter() + writer.SetFileName(filename) + writer.SetFrameRate(1) + writer.SetAnimationScene(scene.SMProxy) + + # Now save the animation. + if not writer.Save(): + raise RuntimeError, "Saving of animation failed!" + else: + scene.Play() + return scene + +def GetProgressPrintingIsEnabled(): + return progressObserverTag is not None + +def SetProgressPrintingEnabled(value): + """Is not supported because of not supported observers""" + pass + +def ToggleProgressPrinting(): + """Turn on/off printing of progress. See SetProgressPrintingEnabled.""" + SetProgressPrintingEnabled(not GetProgressPrintingIsEnabled()) + +def Finalize(): + """Although not required, this can be called at exit to cleanup.""" + global progressObserverTag + # Make sure to remove the observer + if progressObserverTag: + ToggleProgressPrinting() + vtkInitializationHelper.Finalize() + +# Internal methods + +def _getPyProxy(smproxy, outputPort=0): + """Returns a python wrapper for a server manager proxy. This method + first checks if there is already such an object by looking in the + _pyproxies group and returns it if found. Otherwise, it creates a + new one. Proxies register themselves in _pyproxies upon creation.""" + if not smproxy: + return None + if (smproxy, outputPort) in _pyproxies: + return _pyproxies[(smproxy, outputPort)]() + + xmlName = smproxy.GetXMLName() + if smproxy.GetXMLLabel(): + xmlName = smproxy.GetXMLLabel() + classForProxy = _findClassForProxy(_make_name_valid(xmlName), smproxy.GetXMLGroup()) + if classForProxy: + retVal = classForProxy(proxy=smproxy, port=outputPort) + else: + retVal = Proxy(proxy=smproxy, port=outputPort) + return retVal + +def _makeUpdateCameraMethod(rv): + """ This internal method is used to create observer methods """ + if not hasattr(rv(), "BlockUpdateCamera"): + rv().add_attribute("BlockUpdateCamera", False) + def UpdateCamera(obj, string): + if not rv().BlockUpdateCamera: + # used to avoid some nasty recursion that occurs when interacting in + # the GUI. + rv().BlockUpdateCamera = True + rv().SynchronizeCameraProperties() + rv().BlockUpdateCamera = False + return UpdateCamera + +def _createInitialize(group, name): + """Internal method to create an Initialize() method for the sub-classes + of Proxy""" + pgroup = group + pname = name + def aInitialize(self, connection=None, update=True): + if not connection: + connection = ActiveConnection + if not connection: + raise RuntimeError,\ + 'Cannot create a proxy without a session.' + if not connection.Session.GetProxyDefinitionManager().HasDefinition(pgroup, pname): + error_msg = "The connection does not provide any definition for %s." % pname + raise RuntimeError, error_msg + self.InitializeFromProxy(\ + CreateProxy(pgroup, pname, connection.Session), update) + return aInitialize + +def _createGetProperty(pName): + """Internal method to create a GetXXX() method where XXX == pName.""" + propName = pName + def getProperty(self): + return self.GetPropertyValue(propName) + return getProperty + +def _createSetProperty(pName): + """Internal method to create a SetXXX() method where XXX == pName.""" + propName = pName + def setProperty(self, value): + return self.SetPropertyWithName(propName, value) + return setProperty + +def _findClassForProxy(xmlName, xmlGroup): + """Given the xmlName for a proxy, returns a Proxy class. Note + that if there are duplicates, the first one is returned.""" + global sources, filters, writers, rendering, animation, implicit_functions,\ + piecewise_functions, extended_sources, misc + if not xmlName: + return None + if xmlGroup == "sources": + return sources.__dict__[xmlName] + elif xmlGroup == "filters": + return filters.__dict__[xmlName] + elif xmlGroup == "implicit_functions": + return implicit_functions.__dict__[xmlName] + elif xmlGroup == "piecewise_functions": + return piecewise_functions.__dict__[xmlName] + elif xmlGroup == "writers": + return writers.__dict__[xmlName] + elif xmlGroup == "extended_sources": + return extended_sources.__dict__[xmlName] + elif xmlName in rendering.__dict__: + return rendering.__dict__[xmlName] + elif xmlName in animation.__dict__: + return animation.__dict__[xmlName] + elif xmlName in misc.__dict__: + return misc.__dict__[xmlName] + else: + return None + +def _printProgress(caller, event): + """The default event handler for progress. Prints algorithm + name and 1 '.' per 10% progress.""" + global currentAlgorithm, currentProgress + + pm = vtkProcessModule.GetProcessModule() + progress = pm.GetLastProgress() / 10 + # If we got a 100% as the first thing, ignore + # This is to get around the fact that some vtk + # algorithms report 100% more than once (which is + # a bug) + if not currentAlgorithm and progress == 10: + return + alg = pm.GetLastProgressName() + if alg != currentAlgorithm and alg: + if currentAlgorithm: + while currentProgress <= 10: + import sys + sys.stdout.write(".") + currentProgress += 1 + print "]" + currentProgress = 0 + print alg, ": [ ", + currentAlgorithm = alg + while currentProgress <= progress: + import sys + sys.stdout.write(".") + #sys.stdout.write("%d " % pm.GetLastProgress()) + currentProgress += 1 + if progress == 10: + print "]" + currentAlgorithm = None + currentProgress = 0 + +def updateModules(m): + """Called when a plugin is loaded, this method updates + the proxy class object in all known modules.""" + + createModule("sources", m.sources) + createModule("filters", m.filters) + createModule("writers", m.writers) + createModule("representations", m.rendering) + createModule("views", m.rendering) + createModule("lookup_tables", m.rendering) + createModule("textures", m.rendering) + createModule('cameramanipulators', m.rendering) + createModule("animation", m.animation) + createModule("misc", m.misc) + createModule('animation_keyframes', m.animation) + createModule('implicit_functions', m.implicit_functions) + createModule('piecewise_functions', m.piecewise_functions) + createModule("extended_sources", m.extended_sources) + createModule("incremental_point_locators", m.misc) + +def _createModules(m): + """Called when the module is loaded, this creates sub- + modules for all know proxy groups.""" + + m.sources = createModule('sources') + m.filters = createModule('filters') + m.writers = createModule('writers') + m.rendering = createModule('representations') + createModule('views', m.rendering) + createModule("lookup_tables", m.rendering) + createModule("textures", m.rendering) + createModule('cameramanipulators', m.rendering) + m.animation = createModule('animation') + createModule('animation_keyframes', m.animation) + m.implicit_functions = createModule('implicit_functions') + m.piecewise_functions = createModule('piecewise_functions') + m.extended_sources = createModule("extended_sources") + m.misc = createModule("misc") + createModule("incremental_point_locators", m.misc) + +class PVModule(object): + pass + +def _make_name_valid(name): + """Make a string into a valid Python variable name.""" + if not name: + return None + import string + valid_chars = "_%s%s" % (string.ascii_letters, string.digits) + name = str().join([c for c in name if c in valid_chars]) + if not name[0].isalpha(): + name = 'a' + name + return name + +def createModule(groupName, mdl=None): + """Populates a module with proxy classes defined in the given group. + If mdl is not specified, it also creates the module""" + global ActiveConnection + + if not ActiveConnection: + raise RuntimeError, "Please connect to a server using \"Connect\"" + + pxm = ProxyManager() + # Use prototypes to find all proxy types. + pxm.InstantiateGroupPrototypes(groupName) + + debug = False + if not mdl: + debug = True + mdl = PVModule() + definitionIter = pxm.NewDefinitionIterator(groupName) + for i in definitionIter: + proxyName = i['key'] + proto = pxm.GetPrototypeProxy(groupName, proxyName) + if not proto: + print "Error while loading %s/%s %s"%(groupName, i['group'], proxyName) + continue + pname = proxyName + if proto.GetXMLLabel(): + pname = proto.GetXMLLabel() + pname = _make_name_valid(pname) + if not pname: + continue + if pname in mdl.__dict__: + if debug: + print "Warning: %s is being overwritten. This may point to an issue in the ParaView configuration files" % pname + cdict = {} + # Create an Initialize() method for this sub-class. + cdict['Initialize'] = _createInitialize(groupName, proxyName) + iter = PropertyIterator(proto) + # Add all properties as python properties. + for prop in iter: + propName = iter.GetKey() + if (prop.GetInformationOnly() and propName != "TimestepValues" ) \ + or prop.GetIsInternal(): + continue + names = [propName] + names = [iter.PropertyLabel] + + propDoc = None + if prop.GetDocumentation(): + propDoc = prop.GetDocumentation().GetDescription() + for name in names: + name = _make_name_valid(name) + if name: + cdict[name] = property(_createGetProperty(propName), + _createSetProperty(propName), + None, + propDoc) + # Add the documentation as the class __doc__ + if proto.GetDocumentation() and \ + proto.GetDocumentation().GetDescription(): + doc = proto.GetDocumentation().GetDescription() + else: + doc = Proxy.__doc__ + cdict['__doc__'] = doc + # Create the new type + if proto.GetXMLName() == "ExodusIIReader": + superclasses = (ExodusIIReaderProxy,) + elif proto.IsA("vtkSMSourceProxy"): + superclasses = (SourceProxy,) + elif proto.IsA("vtkSMViewLayoutProxy"): + superclasses = (ViewLayoutProxy,) + else: + superclasses = (Proxy,) + + cobj = type(pname, superclasses, cdict) + # Add it to the modules dictionary + mdl.__dict__[pname] = cobj + return mdl + + +def __determineGroup(proxy): + """Internal method""" + if not proxy: + return None + xmlgroup = proxy.GetXMLGroup() + xmlname = proxy.GetXMLName() + if xmlgroup == "sources": + if xmlname in ["BlockSelectionSource", + "FrustumSelectionSource", + "GlobalIDSelectionSource", + "PedigreeIDSelectionSource", + "IDSelectionSource", + "CompositeDataIDSelectionSource", + "HierarchicalDataIDSelectionSource", + "ThresholdSelectionSource", + "LocationSelectionSource"]: + return "selection_sources" + return "sources" + elif xmlgroup == "filters": + return "sources" + elif xmlgroup == "representations": + if xmlname == "ScalarBarWidgetRepresentation": + return "scalar_bars" + return "representations" + elif xmlgroup == "animation_keyframes": + return "animation" + return xmlgroup + +__nameCounter = {} +def __determineName(proxy, group): + global __nameCounter + name = _make_name_valid(proxy.GetXMLLabel()) + if not name: + return None + if not __nameCounter.has_key(name): + __nameCounter[name] = 1 + val = 1 + else: + __nameCounter[name] += 1 + val = __nameCounter[name] + return "%s%d" % (name, val) + +def __getName(proxy, group): + pxm = ProxyManager(proxy.GetSession()) + if isinstance(proxy, Proxy): + proxy = proxy.SMProxy + return pxm.GetProxyName(group, proxy) + +class MissingRegistrationInformation(Exception): + """Exception for missing registration information. Raised when a name or group + is not specified or when a group cannot be deduced.""" + pass + +class MissingProxy(Exception): + """Exception fired when the requested proxy is missing.""" + pass + +def Register(proxy, **extraArgs): + """Registers a proxy with the proxy manager. If no 'registrationGroup' is + specified, then the group is inferred from the type of the proxy. + 'registrationName' may be specified to register with a particular name + otherwise a default name will be created.""" + # TODO: handle duplicate registration + if "registrationGroup" in extraArgs: + registrationGroup = extraArgs["registrationGroup"] + else: + registrationGroup = __determineGroup(proxy) + + if "registrationName" in extraArgs: + registrationName = extraArgs["registrationName"] + else: + registrationName = __determineName(proxy, registrationGroup) + if registrationGroup and registrationName: + pxm = ProxyManager() + pxm.RegisterProxy(registrationGroup, registrationName, proxy) + else: + raise MissingRegistrationInformation, "Registration error %s %s." % (registrationGroup, registrationName) + return (registrationGroup, registrationName) + +def UnRegister(proxy, **extraArgs): + """UnRegisters proxies registered using Register().""" + if "registrationGroup" in extraArgs: + registrationGroup = extraArgs["registrationGroup"] + else: + registrationGroup = __determineGroup(proxy) + + if "registrationName" in extraArgs: + registrationName = extraArgs["registrationName"] + else: + registrationName = __getName(proxy, registrationGroup) + + if registrationGroup and registrationName: + pxm = ProxyManager() + pxm.UnRegisterProxy(registrationGroup, registrationName, proxy) + else: + raise RuntimeError, "UnRegistration error." + return (registrationGroup, registrationName) + +def demo1(): + """This simple demonstration creates a sphere, renders it and delivers + it to the client using Fetch. It returns a tuple of (data, render + view)""" + if not ActiveConnection: + Connect() + ss = sources.Sphere(Radius=2, ThetaResolution=32) + shr = filters.Shrink(Input=OutputPort(ss,0)) + cs = sources.Cone() + app = filters.AppendDatasets() + app.Input = [shr, cs] + rv = CreateRenderView() + rep = CreateRepresentation(app, rv) + rv.ResetCamera() + rv.StillRender() + data = Fetch(ss) + + return (data, rv) + +def demo2(fname="/Users/berk/Work/ParaViewData/Data/disk_out_ref.ex2"): + """This method demonstrates the user of a reader, representation and + view. It also demonstrates how meta-data can be obtained using proxies. + Make sure to pass the full path to an exodus file. Also note that certain + parameters are hard-coded for disk_out_ref.ex2 which can be found + in ParaViewData. This method returns the render view.""" + if not ActiveConnection: + Connect() + # Create the exodus reader and specify a file name + reader = sources.ExodusIIReader(FileName=fname) + # Get the list of point arrays. + arraySelection = reader.PointVariables + print arraySelection.Available + # Select all arrays + arraySelection.SetData(arraySelection.Available) + + # Next create a default render view appropriate for the session type. + rv = CreateRenderView() + # Create the matching representation + rep = CreateRepresentation(reader, rv) + rep.Representation = 1 # Wireframe + # Black background is not pretty + rv.Background = [0.4, 0.4, 0.6] + rv.StillRender() + # Reset the camera to include the whole thing + rv.ResetCamera() + rv.StillRender() + # Change the elevation of the camera. See VTK documentation of vtkCamera + # for camera parameters. + c = rv.GetActiveCamera() + c.Elevation(45) + rv.StillRender() + # Now that the reader execute, let's get some information about it's + # output. + pdi = reader[0].PointData + # This prints a list of all read point data arrays as well as their + # value ranges. + print 'Number of point arrays:', len(pdi) + for i in range(len(pdi)): + ai = pdi[i] + print "----------------" + print "Array:", i, ai.Name, ":" + numComps = ai.GetNumberOfComponents() + print "Number of components:", numComps + for j in range(numComps): + print "Range:", ai.GetRange(j) + # White is boring. Let's color the geometry using a variable. + # First create a lookup table. This object controls how scalar + # values are mapped to colors. See VTK documentation for + # details. + lt = rendering.PVLookupTable() + # Assign it to the representation + rep.LookupTable = lt + # Color by point array called Pres + rep.ColorAttributeType = 0 # point data + rep.ColorArrayName = "Pres" + # Add to RGB points. These are tuples of 4 values. First one is + # the scalar values, the other 3 the RGB values. This list has + # 2 points: Pres: 0.00678, color: blue, Pres: 0.0288, color: red + lt.RGBPoints = [0.00678, 0, 0, 1, 0.0288, 1, 0, 0] + lt.ColorSpace = 1 # HSV + rv.StillRender() + return rv + +def demo3(): + """This method demonstrates the use of servermanager with numpy as + well as pylab for plotting. It creates an artificial data sources, + probes it with a line, delivers the result to the client using Fetch + and plots it using pylab. This demo requires numpy and pylab installed. + It returns a tuple of (data, render view).""" + import paraview.numpy_support + import pylab + + if not ActiveConnection: + Connect() + # Create a synthetic data source + source = sources.Wavelet() + # Let's get some information about the data. First, for the + # source to execute + source.UpdatePipeline() + + di = source.GetDataInformation() + print "Data type:", di.GetPrettyDataTypeString() + print "Extent:", di.GetExtent() + print "Array name:", \ + source[0].PointData[0].Name + + rv = CreateRenderView() + + rep1 = CreateRepresentation(source, rv) + rep1.Representation = 3 # outline + + # Let's apply a contour filter + cf = filters.Contour(Input=source, ContourValues=[200]) + + # Select the array to contour by + #cf.SelectInputScalars = 'RTData' + + rep2 = CreateRepresentation(cf, rv) + + rv.Background = (0.4, 0.4, 0.6) + # Reset the camera to include the whole thing + rv.StillRender() + rv.ResetCamera() + rv.StillRender() + + # Now, let's probe the data + probe = filters.ResampleWithDataset(Input=source) + # with a line + line = sources.Line(Resolution=60) + # that spans the dataset + bounds = di.GetBounds() + print "Bounds: ", bounds + line.Point1 = bounds[0:6:2] + line.Point2 = bounds[1:6:2] + + probe.Source = line + + # Render with the line + rep3 = CreateRepresentation(line, rv) + rv.StillRender() + + # Now deliver it to the client. Remember, this is for small data. + data = Fetch(probe) + # Convert it to a numpy array + data = paraview.numpy_support.vtk_to_numpy( + data.GetPointData().GetArray("RTData")) + # Plot it using matplotlib + pylab.plot(data) + pylab.show() + + return (data, rv, probe) + +def demo4(fname="/Users/berk/Work/ParaViewData/Data/can.ex2"): + """This method demonstrates the user of AnimateReader for + creating animations.""" + if not ActiveConnection: + Connect() + reader = sources.ExodusIIReader(FileName=fname) + view = CreateRenderView() + repr = CreateRepresentation(reader, view) + view.StillRender() + view.ResetCamera() + view.StillRender() + c = view.GetActiveCamera() + c.Elevation(95) + return AnimateReader(reader, view) + + +def demo5(): + """ Simple sphere animation""" + if not ActiveConnection: + Connect() + sphere = sources.Sphere() + view = CreateRenderView() + repr = CreateRepresentation(sphere, view) + + view.StillRender() + view.ResetCamera() + view.StillRender() + + # Create an animation scene + scene = animation.AnimationScene() + # Add 1 view + scene.ViewModules = [view] + + # Create a cue to animate the StartTheta property + cue = animation.KeyFrameAnimationCue() + cue.AnimatedProxy = sphere + cue.AnimatedPropertyName = "StartTheta" + # Add it to the scene's cues + scene.Cues = [cue] + + # Create 2 keyframes for the StartTheta track + keyf0 = animation.CompositeKeyFrame() + keyf0.Type = 2 # Set keyframe interpolation type to Ramp. + # At time = 0, value = 0 + keyf0.KeyTime = 0 + keyf0.KeyValues= [0] + + keyf1 = animation.CompositeKeyFrame() + # At time = 1.0, value = 200 + keyf1.KeyTime = 1.0 + keyf1.KeyValues= [200] + + # Add keyframes. + cue.KeyFrames = [keyf0, keyf1] + + scene.Play() + return scene + +ASSOCIATIONS = { 'POINTS' : 0, 'CELLS' : 1, 'VERTICES' : 4, 'EDGES' : 5, 'ROWS' : 6} + +# Users can set the active connection which will be used by API +# to create proxies etc when no connection argument is passed. +# Connect() automatically sets this if it is not already set. +ActiveConnection = None + +# Fields for multi-server support +MultiServerConnections = None + +# API for multi-server support +def enableMultiServer(multiServer=True): + """This method enable the current servermanager to support several + connections. Once we enable the multi-server support, the user can create + as many connection as he want and switch from one to another in order to + create and manage proxy.""" + global MultiServerConnections, ActiveConnection + if not multiServer and MultiServerConnections: + raise RuntimeError, "Once we enable Multi-Server support we can not get back" + MultiServerConnections = [] + if ActiveConnection: + MultiServerConnections.append(ActiveConnection) + +def switchActiveConnection(newActiveConnection=None): + """Switch active connection to be the provided one or if none just pick the + other one""" + global MultiServerConnections, ActiveConnection + if MultiServerConnections == None: + raise RuntimeError, "enableMultiServer() must be called before" + + # Manage the case when no connection is provided + if newActiveConnection: + ActiveConnection = newActiveConnection + __exposeActiveModules__() + # Update active session for ParaView + if vtkSMProxyManager.GetProxyManager().GetActiveSession() != ActiveConnection.Session: + vtkSMProxyManager.GetProxyManager().SetActiveSession(ActiveConnection.Session) + return ActiveConnection + else: + for connection in MultiServerConnections: + if connection != ActiveConnection: + ActiveConnection = connection + __exposeActiveModules__() + # Update active session for ParaView + if vtkSMProxyManager.GetProxyManager().GetActiveSession() != ActiveConnection.Session: + vtkSMProxyManager.GetProxyManager().SetActiveSession(ActiveConnection.Session) + return ActiveConnection + return None + +# Needs to be called when paraview module is loaded from python instead +# of pvpython, pvbatch or GUI. +if not vtkProcessModule.GetProcessModule(): +# pvoptions = None Not applicable for SALOME Python console +# if paraview.options.batch: +# pvoptions = vtkPVOptions(); +# pvoptions.SetProcessType(0x40) +# if paraview.options.symmetric: +# pvoptions.SetSymmetricMPIMode(True) + vtkInitializationHelper.Initialize(sys.executable, + vtkProcessModule.PROCESS_CLIENT, pvoptions) + +# Initialize progress printing. Can be turned off by calling +# ToggleProgressPrinting() again. +progressObserverTag = None +currentAlgorithm = False +currentProgress = 0 +fromGUI = False +ToggleProgressPrinting() + +_pyproxies = {} + +# Create needed sub-modules +# We can no longer create modules, unless we have connected to a server. +# _createModules() + +# Set up our custom importer (if possible) +loader = _ModuleLoader() +sys.meta_path.append(loader) + +def __InitAfterConnect__(connection): + """ + This function is called everytime after a server connection is made. + Since the ProxyManager and all proxy definitions are changed every time a + new connection is made, we re-create all the modules + """ + _createModules(connection.Modules) + ## VSV fromFilter is alwais False for SALOME because it can't be changed from ParaView code + #if not paraview.fromFilter: + # fromFilter is set when this module is imported from the programmable + # filter +# global _defUpdater +# _defUpdater = __DefinitionUpdater() + connection.AttachDefinitionUpdater() + pass + +def __exposeActiveModules__(): + """Update servermanager submodules to point to the current + ActiveConnection.Modules.*""" + # Expose all active module to the current servermanager module + if ActiveConnection: + for m in [mName for mName in dir(ActiveConnection.Modules) if mName[0] != '_' ]: + exec "global %s;%s = ActiveConnection.Modules.%s" % (m,m,m) + +# Definitions for working in SALOME GUI mode +#aParams = myParavis.GetConnectionParameters() +#ActiveConnection = Connect() +##Connection(aParams[0]) +#ActiveConnection.SetHost(aParams[1], aParams[2], aParams[3], aParams[4], aParams[5]) +#ToggleProgressPrinting() +#fromGUI = True + +InitFromGUI() + +if hasattr(sys, "ps1"): + # session is interactive. + print vtkSMProxyManager.GetParaViewSourceVersion(); + +def GetConnectionFromId(id): + for connection in MultiServerConnections: + if connection.ID == id: + return connection + return None + +def GetConnectionFromSession(session): + for connection in MultiServerConnections: + if connection.Session == session: + return connection + return None + +def GetConnectionAt(index): + return MultiServerConnections[index] + +def GetNumberOfConnections(): + return len(MultiServerConnections) + +#VTN: Problem during execution +#atexit.register(vtkPythonProgrammableFilter.DeleteGlobalPythonInterpretor) diff --git a/src/PV_SWIG/VTKWrapping/presentations.py b/src/PV_SWIG/VTKWrapping/presentations.py new file mode 100644 index 00000000..05b78de4 --- /dev/null +++ b/src/PV_SWIG/VTKWrapping/presentations.py @@ -0,0 +1,2647 @@ +# Copyright (C) 2010-2013 CEA/DEN, EDF R&D +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +""" +This module is intended to provide Python API for building presentations +typical for Post-Pro module (Scalar Map, Deformed Shape, Vectors, etc.) +""" + + +from __future__ import division +##from __future__ import print_function + +import os +import re +import warnings +from math import sqrt, sin, cos, radians +from string import upper + +import pvsimple as pv +#try: +# # TODO(MZN): to be removed (issue with Point Sprite texture) +# #import paravisSM as sm +#except: +# import paraview.simple as pv +# import paraview.servermanager as sm + + +# Constants +EPS = 1E-3 +FLT_MIN = 1E-37 +VTK_LARGE_FLOAT = 1E+38 +GAP_COEFFICIENT = 0.0001 + + +# Globals +_current_bar = None + + +# Enumerations +class PrsTypeEnum: + """ + Post-Pro presentation types. + """ + MESH = 0 + SCALARMAP = 1 + ISOSURFACES = 2 + CUTPLANES = 3 + CUTLINES = 4 + DEFORMEDSHAPE = 5 + DEFORMEDSHAPESCALARMAP = 6 + VECTORS = 7 + PLOT3D = 8 + STREAMLINES = 9 + GAUSSPOINTS = 10 + + _type2name = {MESH: 'Mesh', + SCALARMAP: 'Scalar Map', + ISOSURFACES: 'Iso Surfaces', + CUTPLANES: 'Cut Planes', + CUTLINES: 'Cut Lines', + DEFORMEDSHAPE: 'Deformed Shape', + DEFORMEDSHAPESCALARMAP: 'Deformed Shape And Scalar Map', + VECTORS: 'Vectors', + PLOT3D: 'Plot3D', + STREAMLINES: 'Stream Lines', + GAUSSPOINTS: 'Gauss Points'} + + @classmethod + def get_name(cls, type): + """Return presentaion name by its type.""" + return cls._type2name[type] + + +class EntityType: + """ + Entity types. + """ + NODE = 0 + CELL = 1 + + _type2name = {NODE: 'OnPoint', + CELL: 'OnCell'} + + _name2type = {'OnPoint': NODE, + 'OnCell': CELL} + + _type2pvtype = {NODE: 'POINT_DATA', + CELL: 'CELL_DATA'} + + @classmethod + def get_name(cls, type): + """Return entity name (used in full group names) by its type.""" + return cls._type2name[type] + + @classmethod + def get_type(cls, name): + """Return entity type by its name (used in full group names).""" + return cls._name2type[name] + + @classmethod + def get_pvtype(cls, type): + """Return entity type from ['CELL_DATA', 'POINT_DATA']""" + return cls._type2pvtype[type] + + +class Orientation: + """Orientation types. + + Defines a set of plane orientation possibilities: + AUTO: plane orientation should be calculated. + XY: plane formed by X and Y axis. + YZ: plane formed by Y and Z axis. + ZX: plane formed by Z and X axis + + """ + AUTO = 0 + XY = 1 + YZ = 2 + ZX = 3 + + +class GlyphPos: + """Glyph positions. + + Set of elements defining the position of the vector head: + CENTER: in the center of the vector + TAIL: in the tail of the vector + HEAD: in the head of the vector + + """ + CENTER = 0 + TAIL = 1 + HEAD = 2 + + +class GaussType: + """ + Gauss Points primitive types. + """ + SPRITE = 0 + POINT = 1 + SPHERE = 2 + + _type2mode = {SPRITE: 'Texture', + POINT: 'SimplePoint', + SPHERE: 'Sphere (Texture)'} + + @classmethod + def get_mode(cls, type): + """Return paraview point sprite mode by the primitive type.""" + return cls._type2mode[type] + + +# Auxiliary functions +def process_prs_for_test(prs, view, picture_name, show_bar=True): + """Show presentation and record snapshot image. + + Arguments: + prs: the presentation to show + view: the render view + picture_name: the full name of the graphics file to save + show_bar: to show scalar bar or not + + """ + # Show the presentation only + display_only(prs, view) + + # Show scalar bar + if show_bar and _current_bar: + _current_bar.Visibility = 1 + + # Reset the view + reset_view(view) + + # Create a directory for screenshot if necessary + file_name = re.sub("\s+", "_", picture_name) + pic_dir = os.path.dirname(picture_name) + if not os.path.exists(pic_dir): + os.makedirs(pic_dir) + + # Save picture + pv.WriteImage(file_name, view=view, Magnification=1) + + +def reset_view(view=None): + """Reset the view. + + Set predefined (taken from Post-Pro) camera settings. + If the view is not passed, the active view is used. + + """ + if not view: + view = pv.GetRenderView() + + # Camera preferences + view.CameraFocalPoint = [0.0, 0.0, 0.0] + view.CameraViewUp = [0.0, 0.0, 1.0] + view.CameraPosition = [738.946, -738.946, 738.946] + + # Turn on the headligth + view.LightSwitch = 1 + view.LightIntensity = 0.5 + + # Use parallel projection + view.CameraParallelProjection = 1 + + view.ResetCamera() + pv.Render(view=view) + + +def hide_all(view, to_remove=False): + """Hide all representations in the view.""" + if not view: + view = pv.GetRenderView() + + rep_list = view.Representations + for rep in rep_list: + if hasattr(rep, 'Visibility') and rep.Visibility != 0: + rep.Visibility = 0 + if to_remove: + view.Representations.remove(rep) + pv.Render(view=view) + + +def display_only(prs, view=None): + """Display only the given presentation in the view.""" + hide_all(view) + if (hasattr(prs, 'Visibility') and prs.Visibility != 1): + prs.Visibility = 1 + pv.Render(view=view) + + +def set_visible_lines(xy_prs, lines): + """Set visible only the given lines for XYChartRepresentation.""" + sv = xy_prs.GetProperty("SeriesVisibilityInfo").GetData() + visible = '0' + + for i in xrange(0, len(sv)): + if i % 2 == 0: + line_name = sv[i] + if line_name in lines: + visible = '1' + else: + visible = '0' + else: + sv[i] = visible + + xy_prs.SeriesVisibility = sv + + +def check_vector_mode(vector_mode, nb_components): + """Check vector mode. + + Check if vector mode is correct for the data array with the + given number of components. + + Arguments: + vector_mode: 'Magnitude', 'X', 'Y' or 'Z' + nb_components: number of component in the data array + + Raises: + ValueError: in case of the vector mode is unexistent + or nonapplicable. + + """ + if vector_mode not in ('Magnitude', 'X', 'Y', 'Z'): + raise ValueError("Unexistent vector mode: " + vector_mode) + + if ((nb_components == 1 and (vector_mode == 'Y' or vector_mode == 'Z')) or + (nb_components == 2 and vector_mode == 'Z')): + raise ValueError("Incorrect vector mode " + vector_mode + " for " + + nb_components + "-component field") + + +def get_vector_component(vector_mode): + """Get vector component as ineger. + + Translate vector component notation from string + to integer: + 'Magnitude': -1 + 'X': 0 + 'Y': 1 + 'Z': 2 + + """ + vcomponent = -1 + + if vector_mode == 'X': + vcomponent = 0 + elif vector_mode == 'Y': + vcomponent = 1 + elif vector_mode == 'Z': + vcomponent = 2 + + return vcomponent + + +def get_data_range(proxy, entity, field_name, vector_mode='Magnitude', + cut_off=False): + """Get data range for the field. + + Arguments: + proxy: the pipeline object, containig data array for the field + entity: the field entity + field_name: the field name + vector_mode: the vector mode ('Magnitude', 'X', 'Y' or 'Z') + + Returns: + Data range as [min, max] + + """ + entity_data_info = None + field_data = proxy.GetFieldDataInformation() + + if field_name in field_data.keys(): + entity_data_info = field_data + elif entity == EntityType.CELL: + entity_data_info = proxy.GetCellDataInformation() + elif entity == EntityType.NODE: + entity_data_info = proxy.GetPointDataInformation() + + data_range = [] + + if field_name in entity_data_info.keys(): + vcomp = get_vector_component(vector_mode) + data_range = entity_data_info[field_name].GetComponentRange(vcomp) + else: + pv_entity = EntityType.get_pvtype(entity) + warnings.warn("Field " + field_name + + " is unknown for " + pv_entity + "!") + + # Cut off the range + if cut_off and (data_range[0] <= data_range[1]): + data_range = list(data_range) + delta = abs(data_range[1] - data_range[0]) * GAP_COEFFICIENT + data_range[0] += delta + data_range[1] -= delta + + return data_range + + +def get_bounds(proxy): + """Get bounds of the proxy in 3D.""" + dataInfo = proxy.GetDataInformation() + bounds_info = dataInfo.GetBounds() + return bounds_info + + +def get_x_range(proxy): + """Get X range of the proxy bounds in 3D.""" + bounds_info = get_bounds(proxy) + return bounds_info[0:2] + + +def get_y_range(proxy): + """Get Y range of the proxy bounds in 3D.""" + bounds_info = get_bounds(proxy) + return bounds_info[2:4] + + +def get_z_range(proxy): + """Get Z range of the proxy bounds in 3D.""" + bounds_info = get_bounds(proxy) + return bounds_info[4:6] + + +def is_planar_input(proxy): + """Check if the given input is planar.""" + bounds_info = get_bounds(proxy) + + if (abs(bounds_info[0] - bounds_info[1]) <= FLT_MIN or + abs(bounds_info[2] - bounds_info[3]) <= FLT_MIN or + abs(bounds_info[4] - bounds_info[5]) <= FLT_MIN): + return True + + return False + + +def is_data_on_cells(proxy, field_name): + """Check the existence of a field on cells with the given name.""" + cell_data_info = proxy.GetCellDataInformation() + return (field_name in cell_data_info.keys()) + + +def is_empty(proxy): + """Check if the object contains any points or cells. + + Returns: + True: if the given proxy doesn't contain any points or cells + False: otherwise + + """ + data_info = proxy.GetDataInformation() + + nb_cells = data_info.GetNumberOfCells() + nb_points = data_info.GetNumberOfPoints() + + return not(nb_cells + nb_points) + + +def get_orientation(proxy): + """Get the optimum cutting plane orientation for Plot 3D.""" + orientation = Orientation.XY + + bounds = get_bounds(proxy) + delta = [bounds[1] - bounds[0], + bounds[3] - bounds[2], + bounds[5] - bounds[4]] + + if (delta[0] >= delta[1] and delta[0] >= delta[2]): + if (delta[1] >= delta[2]): + orientation = Orientation.XY + else: + orientation = Orientation.ZX + elif (delta[1] >= delta[0] and delta[1] >= delta[2]): + if (delta[0] >= delta[2]): + orientation = Orientation.XY + else: + orientation = Orientation.YZ + elif (delta[2] >= delta[0] and delta[2] >= delta[1]): + if (delta[0] >= delta[1]): + orientation = Orientation.ZX + else: + orientation = Orientation.YZ + + return orientation + + +def dot_product(a, b): + """Dot product of two 3-vectors.""" + dot = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + return dot + + +def multiply3x3(a, b): + """Mutltiply one 3x3 matrix by another.""" + c = [[0, 0, 0], + [0, 0, 0], + [0, 0, 0]] + + for i in xrange(3): + c[0][i] = a[0][0] * b[0][i] + a[0][1] * b[1][i] + a[0][2] * b[2][i] + c[1][i] = a[1][0] * b[0][i] + a[1][1] * b[1][i] + a[1][2] * b[2][i] + c[2][i] = a[2][0] * b[0][i] + a[2][1] * b[1][i] + a[2][2] * b[2][i] + + return c + + +def get_rx(ang): + """Get X rotation matrix by angle.""" + rx = [[1.0, 0.0, 0.0], + [0.0, cos(ang), -sin(ang)], + [0.0, sin(ang), cos(ang)]] + + return rx + + +def get_ry(ang): + """Get Y rotation matrix by angle.""" + ry = [[cos(ang), 0.0, sin(ang)], + [0.0, 1.0, 0.0], + [-sin(ang), 0.0, cos(ang)]] + + return ry + + +def get_rz(ang): + """Get Z rotation matrix by angle.""" + rz = [[cos(ang), -sin(ang), 0.0], + [sin(ang), cos(ang), 0.0], + [0.0, 0.0, 1.0]] + + return rz + + +def get_normal_by_orientation(orientation, ang1=0, ang2=0): + """Get normal for the plane by its orientation.""" + i_plane = 0 + rotation = [[], [], []] + rx = ry = rz = [[1.0, 0.0, 0.0], + [0.0, 1.0, 0.0], + [0.0, 0.0, 1.0]] + + normal = [0.0, 0.0, 0.0] + if orientation == Orientation.XY: + if abs(ang1) > EPS: + rx = get_rx(ang1) + if abs(ang2) > EPS: + ry = get_ry(ang2) + rotation = multiply3x3(rx, ry) + i_plane = 2 + elif orientation == Orientation.ZX: + if abs(ang1) > EPS: + rz = get_rz(ang1) + if abs(ang2) > EPS: + rx = get_rx(ang2) + rotation = multiply3x3(rz, rx) + i_plane = 1 + elif orientation == Orientation.YZ: + if abs(ang1) > EPS: + ry = get_ry(ang1) + if abs(ang2) > EPS: + rz = get_rz(ang2) + rotation = multiply3x3(ry, rz) + i_plane = 0 + + for i in xrange(0, 3): + normal[i] = rotation[i][i_plane] + + return normal + + +def get_bound_project(bound_box, dir): + """Get bounds projection""" + bound_points = [[bound_box[0], bound_box[2], bound_box[4]], + [bound_box[1], bound_box[2], bound_box[4]], + [bound_box[0], bound_box[3], bound_box[4]], + [bound_box[1], bound_box[3], bound_box[4]], + [bound_box[0], bound_box[2], bound_box[5]], + [bound_box[1], bound_box[2], bound_box[5]], + [bound_box[0], bound_box[3], bound_box[5]], + [bound_box[1], bound_box[3], bound_box[5]]] + + bound_prj = [0, 0, 0] + bound_prj[0] = dot_product(dir, bound_points[0]) + bound_prj[1] = bound_prj[0] + + for i in xrange(1, 8): + tmp = dot_product(dir, bound_points[i]) + if bound_prj[1] < tmp: + bound_prj[1] = tmp + if bound_prj[0] > tmp: + bound_prj[0] = tmp + + bound_prj[2] = bound_prj[1] - bound_prj[0] + bound_prj[1] = bound_prj[0] + (1.0 - EPS) * bound_prj[2] + bound_prj[0] = bound_prj[0] + EPS * bound_prj[2] + bound_prj[2] = bound_prj[1] - bound_prj[0] + + return bound_prj + + +def get_positions(nb_planes, dir, bounds, displacement): + """Compute plane positions.""" + positions = [] + bound_prj = get_bound_project(bounds, dir) + if nb_planes > 1: + step = bound_prj[2] / (nb_planes - 1) + abs_displacement = step * displacement + start_pos = bound_prj[0] - 0.5 * step + abs_displacement + for i in xrange(nb_planes): + pos = start_pos + i * step + positions.append(pos) + else: + pos = bound_prj[0] + bound_prj[2] * displacement + positions.append(pos) + + return positions + + +def get_contours(scalar_range, nb_contours): + """Generate contour values.""" + contours = [] + for i in xrange(nb_contours): + pos = scalar_range[0] + i * ( + scalar_range[1] - scalar_range[0]) / (nb_contours - 1) + contours.append(pos) + + return contours + + +def get_nb_components(proxy, entity, field_name): + """Return number of components for the field.""" + entity_data_info = None + field_data = proxy.GetFieldDataInformation() + + if field_name in field_data.keys(): + entity_data_info = field_data + elif entity == EntityType.CELL: + entity_data_info = proxy.GetCellDataInformation() + elif entity == EntityType.NODE: + entity_data_info = proxy.GetPointDataInformation() + + nb_comp = None + if field_name in entity_data_info.keys(): + nb_comp = entity_data_info[field_name].GetNumberOfComponents() + else: + pv_entity = EntityType.get_pvtype(entity) + raise ValueError("Field " + field_name + + " is unknown for " + pv_entity + "!") + + return nb_comp + + +def get_scale_factor(proxy): + """Compute scale factor.""" + if not proxy: + return 0.0 + + proxy.UpdatePipeline() + data_info = proxy.GetDataInformation() + + nb_cells = data_info.GetNumberOfCells() + nb_points = data_info.GetNumberOfPoints() + nb_elements = nb_cells if nb_cells > 0 else nb_points + bounds = get_bounds(proxy) + + volume = 1 + vol = dim = 0 + + for i in xrange(0, 6, 2): + vol = abs(bounds[i + 1] - bounds[i]) + if vol > 0: + dim += 1 + volume *= vol + + if nb_elements == 0 or dim < 1 / VTK_LARGE_FLOAT: + return 0 + + volume /= nb_elements + + return pow(volume, 1 / dim) + + +def get_default_scale(prs_type, proxy, entity, field_name): + """Get default scale factor.""" + data_range = get_data_range(proxy, entity, field_name) + + if prs_type == PrsTypeEnum.DEFORMEDSHAPE: + EPS = 1.0 / VTK_LARGE_FLOAT + if abs(data_range[1]) > EPS: + scale_factor = get_scale_factor(proxy) + return scale_factor / data_range[1] + elif prs_type == PrsTypeEnum.PLOT3D: + bounds = get_bounds(proxy) + length = sqrt((bounds[1] - bounds[0]) ** 2 + + (bounds[3] - bounds[2]) ** 2 + + (bounds[5] - bounds[4]) ** 2) + + EPS = 0.3 + if data_range[1] > 0: + return length / data_range[1] * EPS + + return 0 + + +def get_calc_magnitude(proxy, array_entity, array_name): + """Compute magnitude for the given vector array via Calculator. + + Returns: + the calculator object. + + """ + calculator = None + + # Transform vector array to scalar array if possible + nb_components = get_nb_components(proxy, array_entity, array_name) + if (nb_components > 1): + calculator = pv.Calculator(proxy) + attribute_mode = "Point Data" + if array_entity != EntityType.NODE: + attribute_mode = "Cell Data" + calculator.AttributeMode = attribute_mode + if (nb_components == 2): + # Workaroud: calculator unable to compute magnitude + # if number of components equal to 2 + func = "sqrt(" + array_name + "_X^2+" + array_name + "_Y^2)" + calculator.Function = func + else: + calculator.Function = "mag(" + array_name + ")" + calculator.ResultArrayName = array_name + "_magnitude" + calculator.UpdatePipeline() + + return calculator + + +def get_add_component_calc(proxy, array_entity, array_name): + """Creates 3-component array from 2-component. + + The first two components is from the original array. The 3rd component + is zero. + If the number of components is not equal to 2 - return original array name. + + Returns: + the calculator object. + + """ + calculator = None + + nb_components = get_nb_components(proxy, array_entity, array_name) + if nb_components == 2: + calculator = pv.Calculator(proxy) + attribute_mode = "Point Data" + if array_entity != EntityType.NODE: + attribute_mode = "Cell Data" + calculator.AttributeMode = attribute_mode + expression = "iHat * " + array_name + "_X + jHat * " + array_name + "_Y + kHat * 0" + calculator.Function = expression + calculator.ResultArrayName = array_name + "_3c" + calculator.UpdatePipeline() + + return calculator + + +def select_all_cells(proxy): + """Select all cell types. + + Used in creation of mesh/submesh presentation. + + """ + ### Old API all_cell_types = proxy.CellTypes.Available + all_cell_types = proxy.Entity.Available + ### Old API proxy.CellTypes = all_cell_types + proxy.Entity = all_cell_types + proxy.UpdatePipeline() + + +def select_cells_with_data(proxy, on_points=None, on_cells=None): + """Select cell types with data. + + Only cell types with data for the given fields will be selected. + If no fields defined (neither on points nor on cells) only cell + types with data for even one field (from available) will be selected. + + """ + if not hasattr(proxy, 'Entity'): + return + + #all_cell_types = proxy.CellTypes.Available + all_cell_types = proxy.Entity.Available + all_arrays = list(proxy.CellArrays.GetData()) + all_arrays.extend(proxy.PointArrays.GetData()) + + if not all_arrays: + file_name = proxy.FileName.split(os.sep)[-1] + print "Warning: " + file_name + " doesn't contain any data array." + + # List of cell types to be selected + cell_types_on = [] + + for cell_type in all_cell_types: + #proxy.CellTypes = [cell_type] + proxy.Entity = [cell_type] + proxy.UpdatePipeline() + + cell_arrays = proxy.GetCellDataInformation().keys() + point_arrays = proxy.GetPointDataInformation().keys() + + if on_points or on_cells: + if on_points is None: + on_points = [] + if on_cells is None: + on_cells = [] + + if (all(array in cell_arrays for array in on_cells) and + all(array in point_arrays for array in on_points)): + # Add cell type to the list + cell_types_on.append(cell_type) + else: + in_arrays = lambda array: ((array in cell_arrays) or + (array in point_arrays)) + if any(in_arrays(array) for array in all_arrays): + cell_types_on.append(cell_type) + + # Select cell types + #proxy.CellTypes = cell_types_on + proxy.Entity = cell_types_on + proxy.UpdatePipeline() + + +def extract_groups_for_field(proxy, field_name, field_entity, force=False): + """Exctract only groups which have the field. + + Arguments: + proxy: the pipeline object, containig data + field_name: the field name + field_entity: the field entity + force: if True - ExtractGroup object will be created in any case + + Returns: + ExtractGroup object: if not all groups have the field or + the force argument is true + The initial proxy: if no groups had been filtered. + + """ + source = proxy + + # Remember the state + initial_groups = list(proxy.Groups) + + # Get data information for the field entity + entity_data_info = None + field_data = proxy.GetFieldDataInformation() + + if field_name in field_data.keys(): + entity_data_info = field_data + elif field_entity == EntityType.CELL: + entity_data_info = proxy.GetCellDataInformation() + elif field_entity == EntityType.NODE: + entity_data_info = proxy.GetPointDataInformation() + + # Collect groups for extraction + groups_to_extract = [] + + for group in initial_groups: + proxy.Groups = [group] + proxy.UpdatePipeline() + if field_name in entity_data_info.keys(): + groups_to_extract.append(group) + + # Restore state + proxy.Groups = initial_groups + proxy.UpdatePipeline() + + # Extract groups if necessary + if force or (len(groups_to_extract) < len(initial_groups)): + extract_group = pv.ExtractGroup(proxy) + extract_group.Groups = groups_to_extract + extract_group.UpdatePipeline() + source = extract_group + + return source + + +def if_possible(proxy, field_name, entity, prs_type): + """Check if the presentation creation is possible on the given field.""" + result = True + if (prs_type == PrsTypeEnum.DEFORMEDSHAPE or + prs_type == PrsTypeEnum.DEFORMEDSHAPESCALARMAP or + prs_type == PrsTypeEnum.VECTORS or + prs_type == PrsTypeEnum.STREAMLINES): + nb_comp = get_nb_components(proxy, entity, field_name) + result = (nb_comp > 1) + elif (prs_type == PrsTypeEnum.GAUSSPOINTS): + result = (entity == EntityType.CELL or + field_name in proxy.QuadraturePointArrays.Available) + elif (prs_type == PrsTypeEnum.MESH): + result = len(get_group_names(proxy, field_name, entity)) > 0 + + return result + + +def add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value): + """Add scalar bar with predefined properties.""" + global _current_bar + + # Construct bar title + title = "\n".join([field_name, str(time_value)]) + if nb_components > 1: + title = "\n".join([title, vector_mode]) + + # Create scalar bar + scalar_bar = pv.CreateScalarBar(Enabled=1) + scalar_bar.Orientation = 'Vertical' + scalar_bar.Title = title + scalar_bar.LookupTable = lookup_table + + # Set default properties same as in Post-Pro + scalar_bar.NumberOfLabels = 5 + scalar_bar.AutomaticLabelFormat = 0 + scalar_bar.LabelFormat = '%-#6.6g' + # Title + scalar_bar.TitleFontFamily = 'Arial' + scalar_bar.TitleFontSize = 8 + scalar_bar.TitleBold = 1 + scalar_bar.TitleItalic = 1 + scalar_bar.TitleShadow = 1 + # Labels + scalar_bar.LabelFontFamily = 'Arial' + scalar_bar.LabelFontSize = 8 + scalar_bar.LabelBold = 1 + scalar_bar.LabelItalic = 1 + scalar_bar.LabelShadow = 1 + + # Add the scalar bar to the view + pv.GetRenderView().Representations.append(scalar_bar) + + # Reassign the current bar + _current_bar = scalar_bar + + return scalar_bar + + +def get_bar(): + """Get current scalar bar.""" + global _current_bar + + return _current_bar + + +def get_lookup_table(field_name, nb_components, vector_mode='Magnitude'): + """Get lookup table for the given field.""" + lookup_table = pv.GetLookupTableForArray(field_name, nb_components) + + if vector_mode == 'Magnitude': + lookup_table.VectorMode = vector_mode + elif vector_mode == 'X': + lookup_table.VectorMode = 'Component' + lookup_table.VectorComponent = 0 + elif vector_mode == 'Y': + lookup_table.VectorMode = 'Component' + lookup_table.VectorComponent = 1 + elif vector_mode == 'Z': + lookup_table.VectorMode = 'Component' + lookup_table.VectorComponent = 2 + else: + raise ValueError("Incorrect vector mode: " + vector_mode) + + lookup_table.Discretize = 0 + lookup_table.ColorSpace = 'HSV' + lookup_table.LockScalarRange = 0 + + return lookup_table + + +def get_group_mesh_name(full_group_name): + """Return mesh name of the group by its full name.""" + aList = full_group_name.split('/') + if len(aList) >= 2 : + group_name = full_group_name.split('/')[1] + return group_name + + +def get_group_entity(full_group_name): + """Return entity type of the group by its full name.""" + aList = full_group_name.split('/') + if len(aList) >= 3 : + entity_name = full_group_name.split('/')[2] + entity = EntityType.get_type(entity_name) + return entity + + +def get_group_short_name(full_group_name): + """Return short name of the group by its full name.""" + aList = full_group_name.split('/') + if len(aList) >= 4 : + short_name = full_group_name.split('/')[3] + return short_name + + +def get_mesh_names(proxy): + """Return all mesh names in the given proxy as a set.""" + groups = proxy.Groups.Available + mesh_names = set([get_group_mesh_name(item) for item in groups]) + + return mesh_names + + +def get_group_names(proxy, mesh_name, entity, wo_nogroups=False): + """Return full names of all groups of the given entity type + from the mesh with the given name as a list. + """ + groups = proxy.Groups.Available + + condition = lambda item: (get_group_mesh_name(item) == mesh_name and + get_group_entity(item) == entity) + group_names = [item for item in groups if condition(item)] + + if wo_nogroups: + # Remove "No_Group" group + not_no_group = lambda item: get_group_short_name(item) != "No_Group" + group_names = filter(not_no_group, group_names) + + return group_names + + +def get_time(proxy, timestamp_nb): + """Get time value by timestamp number.""" + # Check timestamp number + timestamps = [] + + if (hasattr(proxy, 'TimestepValues')): + timestamps = proxy.TimestepValues.GetData() + elif (hasattr(proxy.Input, 'TimestepValues')): + timestamps = proxy.Input.TimestepValues.GetData() + + if ((timestamp_nb - 1) not in xrange(len(timestamps))): + raise ValueError("Timestamp number is out of range: " + str(timestamp_nb)) + + # Return time value + return timestamps[timestamp_nb - 1] + + +def create_prs(prs_type, proxy, field_entity, field_name, timestamp_nb): + """Auxiliary function. + + Build presentation of the given type on the given field and + timestamp number. + Set the presentation properties like visu.CreatePrsForResult() do. + + """ + prs = None + + if prs_type == PrsTypeEnum.SCALARMAP: + prs = ScalarMapOnField(proxy, field_entity, field_name, timestamp_nb) + elif prs_type == PrsTypeEnum.CUTPLANES: + prs = CutPlanesOnField(proxy, field_entity, field_name, timestamp_nb, + orientation=Orientation.ZX) + elif prs_type == PrsTypeEnum.CUTLINES: + prs = CutLinesOnField(proxy, field_entity, field_name, timestamp_nb, + orientation1=Orientation.XY, + orientation2=Orientation.ZX) + elif prs_type == PrsTypeEnum.DEFORMEDSHAPE: + prs = DeformedShapeOnField(proxy, field_entity, + field_name, timestamp_nb) + elif prs_type == PrsTypeEnum.DEFORMEDSHAPESCALARMAP: + prs = DeformedShapeAndScalarMapOnField(proxy, field_entity, + field_name, timestamp_nb) + elif prs_type == PrsTypeEnum.VECTORS: + prs = VectorsOnField(proxy, field_entity, field_name, timestamp_nb) + elif prs_type == PrsTypeEnum.PLOT3D: + prs = Plot3DOnField(proxy, field_entity, field_name, timestamp_nb) + elif prs_type == PrsTypeEnum.ISOSURFACES: + prs = IsoSurfacesOnField(proxy, field_entity, field_name, timestamp_nb) + elif prs_type == PrsTypeEnum.GAUSSPOINTS: + prs = GaussPointsOnField(proxy, field_entity, field_name, timestamp_nb) + elif prs_type == PrsTypeEnum.STREAMLINES: + prs = StreamLinesOnField(proxy, field_entity, field_name, timestamp_nb) + else: + raise ValueError("Unexistent presentation type.") + + return prs + + +# Functions for building Post-Pro presentations +def ScalarMapOnField(proxy, entity, field_name, timestamp_nb, + vector_mode='Magnitude'): + """Creates Scalar Map presentation on the given field. + + Arguments: + proxy: the pipeline object, containig data + entity: the entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + vector_mode: the mode of transformation of vector values + into scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude', 'X', 'Y' or 'Z'. + + Returns: + Scalar Map as representation object. + + """ + # We don't need mesh parts with no data on them + if entity == EntityType.NODE: + select_cells_with_data(proxy, on_points=[field_name]) + else: + select_cells_with_data(proxy, on_cells=[field_name]) + + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + pv.UpdatePipeline(time_value, proxy) + + # Extract only groups with data for the field + new_proxy = extract_groups_for_field(proxy, field_name, entity, + force=True) + + # Get Scalar Map representation object + scalarmap = pv.GetRepresentation(new_proxy) + + # Get lookup table + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + # Set properties + scalarmap.ColorAttributeType = EntityType.get_pvtype(entity) + scalarmap.ColorArrayName = field_name + scalarmap.LookupTable = lookup_table + + # Add scalar bar + bar_title = field_name + ", " + str(time_value) + if (nb_components > 1): + bar_title += "\n" + vector_mode + add_scalar_bar(field_name, nb_components, vector_mode, + lookup_table, time_value) + + return scalarmap + + +def CutPlanesOnField(proxy, entity, field_name, timestamp_nb, + nb_planes=10, orientation=Orientation.YZ, + angle1=0, angle2=0, + displacement=0.5, vector_mode='Magnitude'): + """Creates Cut Planes presentation on the given field. + + Arguments: + proxy: the pipeline object, containig data + entity: the entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + nb_planes: number of cutting planes + orientation: cutting planes orientation in 3D space + angle1: rotation of the planes in 3d space around the first axis of the + selected orientation (X axis for XY, Y axis for YZ, Z axis for ZX). + The angle of rotation is set in degrees. Acceptable range: [-45, 45]. + angle2: rotation of the planes in 3d space around the second axis of the + selected orientation. Acceptable range: [-45, 45]. + displacement: the displacement of the planes into one or another side + vector_mode: the mode of transformation of vector values + into scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude', 'X', 'Y' or 'Z'. + + Returns: + Cut Planes as representation object. + + """ + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + pv.UpdatePipeline(time_value, proxy) + + # Create slice filter + slice_filter = pv.Slice(proxy) + slice_filter.SliceType = "Plane" + + # Set cut planes normal + normal = get_normal_by_orientation(orientation, + radians(angle1), radians(angle2)) + slice_filter.SliceType.Normal = normal + + # Set cut planes positions + positions = get_positions(nb_planes, normal, + get_bounds(proxy), displacement) + slice_filter.SliceOffsetValues = positions + + # Get Cut Planes representation object + cut_planes = pv.GetRepresentation(slice_filter) + + # Get lookup table + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set properties + cut_planes.ColorAttributeType = EntityType.get_pvtype(entity) + cut_planes.ColorArrayName = field_name + cut_planes.LookupTable = lookup_table + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + return cut_planes + + +def CutLinesOnField(proxy, entity, field_name, timestamp_nb, + nb_lines=10, + orientation1=Orientation.XY, + base_angle1=0, base_angle2=0, + orientation2=Orientation.YZ, + cut_angle1=0, cut_angle2=0, + displacement1=0.5, displacement2=0.5, + generate_curves=False, + vector_mode='Magnitude'): + """Creates Cut Lines presentation on the given field. + + Arguments: + proxy: the pipeline object, containig data + entity: the entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + nb_lines: number of lines + orientation1: base plane orientation in 3D space + base_angle1: rotation of the base plane in 3d space around the first + axis of the orientation1 (X axis for XY, Y axis for YZ, Z axis for ZX). + The angle of rotation is set in degrees. Acceptable range: [-45, 45]. + base_angle2: rotation of the base plane in 3d space around the second + axis of the orientation1. Acceptable range: [-45, 45]. + orientation2: cutting planes orientation in 3D space + cut_angle1: rotation of the cut planes in 3d space around the first + axis of the orientation2. Acceptable range: [-45, 45]. + cut_angle2: rotation of the cuting planes in 3d space around the second + axis of the orientation2. Acceptable range: [-45, 45]. + displacement1: base plane displacement + displacement2: cutting planes displacement + generate_curves: if true, 'PlotOverLine' filter will be created + for each cut line + vector_mode: the mode of transformation of vector values + into scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude', 'X', 'Y' or 'Z'. + + Returns: + Cut Lines as representation object if generate_curves == False, + (Cut Lines as representation object, list of 'PlotOverLine') otherwise + + """ + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + pv.UpdatePipeline(time_value, proxy) + + # Create base plane + base_plane = pv.Slice(proxy) + base_plane.SliceType = "Plane" + + # Set base plane normal + base_normal = get_normal_by_orientation(orientation1, + radians(base_angle1), + radians(base_angle2)) + base_plane.SliceType.Normal = base_normal + + # Set base plane position + base_position = get_positions(1, base_normal, + get_bounds(proxy), displacement1) + base_plane.SliceOffsetValues = base_position + + # Check base plane + base_plane.UpdatePipeline() + if (base_plane.GetDataInformation().GetNumberOfCells() == 0): + base_plane = proxy + + # Create cutting planes + cut_planes = pv.Slice(base_plane) + cut_planes.SliceType = "Plane" + + # Set cutting planes normal and get positions + cut_normal = get_normal_by_orientation(orientation2, + radians(cut_angle1), + radians(cut_angle2)) + cut_planes.SliceType.Normal = cut_normal + + # Set cutting planes position + cut_positions = get_positions(nb_lines, cut_normal, + get_bounds(base_plane), displacement2) + + # Generate curves + curves = [] + if generate_curves: + index = 0 + for pos in cut_positions: + # Get points for plot over line objects + cut_planes.SliceOffsetValues = pos + cut_planes.UpdatePipeline() + bounds = get_bounds(cut_planes) + point1 = [bounds[0], bounds[2], bounds[4]] + point2 = [bounds[1], bounds[3], bounds[5]] + + # Create plot over line filter + pol = pv.PlotOverLine(cut_planes, + Source="High Resolution Line Source") + pv.RenameSource('Y' + str(index), pol) + pol.Source.Point1 = point1 + pol.Source.Point2 = point2 + pol.UpdatePipeline() + curves.append(pol) + + index += 1 + + cut_planes.SliceOffsetValues = cut_positions + cut_planes.UpdatePipeline() + + # Get Cut Lines representation object + cut_lines = pv.GetRepresentation(cut_planes) + + # Get lookup table + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set properties + cut_lines.ColorAttributeType = EntityType.get_pvtype(entity) + cut_lines.ColorArrayName = field_name + cut_lines.LookupTable = lookup_table + + # Set wireframe represenatation mode + cut_lines.Representation = 'Wireframe' + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + result = cut_lines + # If curves were generated return tuple (cut lines, list of curves) + if curves: + result = cut_lines, curves + + return result + + +def CutSegmentOnField(proxy, entity, field_name, timestamp_nb, + point1, point2, vector_mode='Magnitude'): + """Creates Cut Segment presentation on the given field. + + Arguments: + proxy: the pipeline object, containig data + entity: the entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + point1: set the first point of the segment (as [x, y, z]) + point1: set the second point of the segment (as [x, y, z]) + vector_mode: the mode of transformation of vector values + into scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude', 'X', 'Y' or 'Z'. + + Returns: + Cut Segment as 3D representation object. + + """ + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + pv.UpdatePipeline(time_value, proxy) + + # Create plot over line filter + pol = pv.PlotOverLine(proxy, Source="High Resolution Line Source") + pol.Source.Point1 = point1 + pol.Source.Point2 = point2 + pol.UpdatePipeline() + + # Get Cut Segment representation object + cut_segment = pv.GetRepresentation(pol) + + # Get lookup table + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set properties + cut_segment.ColorAttributeType = EntityType.get_pvtype(entity) + cut_segment.ColorArrayName = field_name + cut_segment.LookupTable = lookup_table + + # Set wireframe represenatation mode + cut_segment.Representation = 'Wireframe' + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + return cut_segment + + +def VectorsOnField(proxy, entity, field_name, timestamp_nb, + scale_factor=None, + glyph_pos=GlyphPos.TAIL, glyph_type='2D Glyph', + is_colored=False, vector_mode='Magnitude'): + """Creates Vectors presentation on the given field. + + Arguments: + proxy: the pipeline object, containig data + entity: the entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + scale_factor: scale factor + glyph_pos: the position of glyphs + glyph_type: the type of glyphs + is_colored: this option allows to color the presentation according to + the corresponding data array values + vector_mode: the mode of transformation of vector values + into scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude', 'X', 'Y' or 'Z'. + + Returns: + Vectors as representation object. + + """ + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + pv.UpdatePipeline(time_value, proxy) + + # Extract only groups with data for the field + new_proxy = extract_groups_for_field(proxy, field_name, entity) + source = new_proxy + + # Cell centers + if is_data_on_cells(proxy, field_name): + cell_centers = pv.CellCenters(source) + cell_centers.VertexCells = 1 + source = cell_centers + + vector_array = field_name + # If the given vector array has only 2 components, add the third one + if nb_components == 2: + calc = get_add_component_calc(source, EntityType.NODE, field_name) + vector_array = calc.ResultArrayName + source = calc + + # Glyph + glyph = pv.Glyph(source) + glyph.Vectors = vector_array + glyph.ScaleMode = 'vector' + glyph.MaskPoints = 0 + + # Set glyph type + glyph.GlyphType = glyph_type + if glyph_type == '2D Glyph': + glyph.GlyphType.GlyphType = 'Arrow' + elif glyph_type == 'Cone': + glyph.GlyphType.Resolution = 7 + glyph.GlyphType.Height = 2 + glyph.GlyphType.Radius = 0.2 + + # Set glyph position if possible + if glyph.GlyphType.GetProperty("Center"): + if (glyph_pos == GlyphPos.TAIL): + glyph.GlyphType.Center = [0.5, 0.0, 0.0] + elif (glyph_pos == GlyphPos.HEAD): + glyph.GlyphType.Center = [-0.5, 0.0, 0.0] + elif (glyph_pos == GlyphPos.CENTER): + glyph.GlyphType.Center = [0.0, 0.0, 0.0] + + if scale_factor is not None: + glyph.SetScaleFactor = scale_factor + else: + def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE, + new_proxy, entity, field_name) + glyph.SetScaleFactor = def_scale + + glyph.UpdatePipeline() + + # Get Vectors representation object + vectors = pv.GetRepresentation(glyph) + + # Get lookup table + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set properties + if (is_colored): + vectors.ColorArrayName = 'GlyphVector' + else: + vectors.ColorArrayName = '' + vectors.LookupTable = lookup_table + + vectors.LineWidth = 1.0 + + # Set wireframe represenatation mode + vectors.Representation = 'Wireframe' + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + return vectors + + +def DeformedShapeOnField(proxy, entity, field_name, + timestamp_nb, + scale_factor=None, is_colored=False, + vector_mode='Magnitude'): + """Creates Defromed Shape presentation on the given field. + + Arguments: + proxy: the pipeline object, containig data + entity: the entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + scale_factor: scale factor of the deformation + is_colored: this option allows to color the presentation according to + the corresponding data array values + vector_mode: the mode of transformation of vector values + into scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude', 'X', 'Y' or 'Z'. + + Returns: + Defromed Shape as representation object. + + """ + # We don't need mesh parts with no data on them + if entity == EntityType.NODE: + select_cells_with_data(proxy, on_points=[field_name]) + else: + select_cells_with_data(proxy, on_cells=[field_name]) + + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + pv.UpdatePipeline(time_value, proxy) + + # Extract only groups with data for the field + new_proxy = extract_groups_for_field(proxy, field_name, entity) + + # Do merge + source = pv.MergeBlocks(new_proxy) + + # Cell data to point data + if is_data_on_cells(proxy, field_name): + cell_to_point = pv.CellDatatoPointData() + cell_to_point.PassCellData = 1 + source = cell_to_point + + vector_array = field_name + # If the given vector array has only 2 components, add the third one + if nb_components == 2: + calc = get_add_component_calc(source, EntityType.NODE, field_name) + vector_array = calc.ResultArrayName + source = calc + + # Warp by vector + warp_vector = pv.WarpByVector(source) + warp_vector.Vectors = [vector_array] + if scale_factor is not None: + warp_vector.ScaleFactor = scale_factor + else: + def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE, + proxy, entity, field_name) + warp_vector.ScaleFactor = def_scale + + # Get Deformed Shape representation object + defshape = pv.GetRepresentation(warp_vector) + + # Get lookup table + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set properties + if is_colored: + defshape.ColorAttributeType = EntityType.get_pvtype(entity) + defshape.ColorArrayName = field_name + else: + defshape.ColorArrayName = '' + defshape.LookupTable = lookup_table + + # Set wireframe represenatation mode + defshape.Representation = 'Wireframe' + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + return defshape + + +def DeformedShapeAndScalarMapOnField(proxy, entity, field_name, + timestamp_nb, + scale_factor=None, + scalar_entity=None, + scalar_field_name=None, + vector_mode='Magnitude'): + """Creates Defromed Shape And Scalar Map presentation on the given field. + + Arguments: + proxy: the pipeline object, containig data + entity: the entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + scale_factor: scale factor of the deformation + scalar_entity: scalar field entity + scalar_field_name: scalar field, i.e. the field for coloring + vector_mode: the mode of transformation of vector values + into scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude', 'X', 'Y' or 'Z'. + + Returns: + Defromed Shape And Scalar Map as representation object. + + """ + # We don't need mesh parts with no data on them + on_points = [] + on_cells = [] + + if entity == EntityType.NODE: + on_points.append(field_name) + else: + on_cells.append(field_name) + + if scalar_entity and scalar_field_name: + if scalar_entity == EntityType.NODE: + on_points.append(scalar_field_name) + else: + on_cells.append(scalar_field_name) + + select_cells_with_data(proxy, on_points, on_cells) + + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + pv.UpdatePipeline(time_value, proxy) + + # Set scalar field by default + scalar_field_entity = scalar_entity + scalar_field = scalar_field_name + if (scalar_field_entity is None) or (scalar_field is None): + scalar_field_entity = entity + scalar_field = field_name + + # Extract only groups with data for the field + new_proxy = extract_groups_for_field(proxy, field_name, entity) + + # Do merge + source = pv.MergeBlocks(new_proxy) + + # Cell data to point data + if is_data_on_cells(proxy, field_name): + cell_to_point = pv.CellDatatoPointData(source) + cell_to_point.PassCellData = 1 + source = cell_to_point + + vector_array = field_name + # If the given vector array has only 2 components, add the third one + if nb_components == 2: + calc = get_add_component_calc(source, EntityType.NODE, field_name) + vector_array = calc.ResultArrayName + source = calc + + # Warp by vector + warp_vector = pv.WarpByVector(source) + warp_vector.Vectors = [vector_array] + if scale_factor is not None: + warp_vector.ScaleFactor = scale_factor + else: + def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE, + new_proxy, entity, field_name) + warp_vector.ScaleFactor = def_scale + + # Get Defromed Shape And Scalar Map representation object + defshapemap = pv.GetRepresentation(warp_vector) + + # Get lookup table + lookup_table = get_lookup_table(scalar_field, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, scalar_field_entity, + scalar_field, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set properties + defshapemap.ColorArrayName = scalar_field + defshapemap.LookupTable = lookup_table + defshapemap.ColorAttributeType = EntityType.get_pvtype(scalar_field_entity) + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + return defshapemap + + +def Plot3DOnField(proxy, entity, field_name, timestamp_nb, + orientation=Orientation.AUTO, + angle1=0, angle2=0, + position=0.5, is_relative=True, + scale_factor=None, + is_contour=False, nb_contours=32, + vector_mode='Magnitude'): + """Creates Plot 3D presentation on the given field. + + Arguments: + proxy: the pipeline object, containig data + entity: the entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + orientation: the cut plane plane orientation in 3D space, if + the input is planar - will not be taken into account + angle1: rotation of the cut plane in 3d space around the first axis + of the selected orientation (X axis for XY, Y axis for YZ, + Z axis for ZX). + The angle of rotation is set in degrees. Acceptable range: [-45, 45]. + angle2: rotation of the cut plane in 3d space around the second axis + of the selected orientation. Acceptable range: [-45, 45]. + position: position of the cut plane in the object (ranging from 0 to 1). + The value 0.5 corresponds to cutting by halves. + is_relative: defines if the cut plane position is relative or absolute + scale_factor: deformation scale factor + is_contour: if True - Plot 3D will be represented with a set of contours, + otherwise - Plot 3D will be represented with a smooth surface + nb_contours: number of contours, applied if is_contour is True + vector_mode: the mode of transformation of vector values + into scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude', 'X', 'Y' or 'Z'. + + Returns: + Plot 3D as representation object. + + """ + # We don't need mesh parts with no data on them + if entity == EntityType.NODE: + select_cells_with_data(proxy, on_points=[field_name]) + else: + select_cells_with_data(proxy, on_cells=[field_name]) + + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + pv.UpdatePipeline(time_value, proxy) + + # Extract only groups with data for the field + new_proxy = extract_groups_for_field(proxy, field_name, entity) + + # Do merge + merge_blocks = pv.MergeBlocks(new_proxy) + merge_blocks.UpdatePipeline() + + poly_data = None + + # Cutting plane + + # Define orientation if necessary (auto mode) + plane_orientation = orientation + if (orientation == Orientation.AUTO): + plane_orientation = get_orientation(proxy) + + # Get cutting plane normal + normal = None + + if (not is_planar_input(proxy)): + normal = get_normal_by_orientation(plane_orientation, + radians(angle1), radians(angle2)) + + # Create slice filter + slice_filter = pv.Slice(merge_blocks) + slice_filter.SliceType = "Plane" + + # Set cutting plane normal + slice_filter.SliceType.Normal = normal + + # Set cutting plane position + if (is_relative): + base_position = get_positions(1, normal, + get_bounds(proxy), position) + slice_filter.SliceOffsetValues = base_position + else: + slice_filter.SliceOffsetValues = position + + slice_filter.UpdatePipeline() + poly_data = slice_filter + else: + normal = get_normal_by_orientation(plane_orientation, 0, 0) + + use_normal = 0 + # Geometry filter + if not poly_data or poly_data.GetDataInformation().GetNumberOfCells() == 0: + geometry_filter = pv.GeometryFilter(merge_blocks) + poly_data = geometry_filter + use_normal = 1 # TODO(MZN): workaround + + warp_scalar = None + plot3d = None + source = poly_data + + if is_data_on_cells(poly_data, field_name): + # Cell data to point data + cell_to_point = pv.CellDatatoPointData(poly_data) + cell_to_point.PassCellData = 1 + source = cell_to_point + + scalars = ['POINTS', field_name] + + # Transform vector array to scalar array if necessary + if (nb_components > 1): + calc = get_calc_magnitude(source, EntityType.NODE, field_name) + scalars = ['POINTS', calc.ResultArrayName] + source = calc + + # Warp by scalar + warp_scalar = pv.WarpByScalar(source) + warp_scalar.Scalars = scalars + warp_scalar.Normal = normal + warp_scalar.UseNormal = use_normal + if scale_factor is not None: + warp_scalar.ScaleFactor = scale_factor + else: + def_scale = get_default_scale(PrsTypeEnum.PLOT3D, + proxy, entity, field_name) + warp_scalar.ScaleFactor = def_scale + + warp_scalar.UpdatePipeline() + source = warp_scalar + + if (is_contour): + # Contours + contour = pv.Contour(warp_scalar) + contour.PointMergeMethod = "Uniform Binning" + contour.ContourBy = ['POINTS', field_name] + scalar_range = get_data_range(proxy, entity, + field_name, vector_mode) + contour.Isosurfaces = get_contours(scalar_range, nb_contours) + contour.UpdatePipeline() + source = contour + + # Get Plot 3D representation object + plot3d = pv.GetRepresentation(source) + + # Get lookup table + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set properties + plot3d.ColorAttributeType = EntityType.get_pvtype(entity) + plot3d.ColorArrayName = field_name + plot3d.LookupTable = lookup_table + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + return plot3d + + +def IsoSurfacesOnField(proxy, entity, field_name, timestamp_nb, + custom_range=None, nb_surfaces=10, + is_colored=True, color=None, vector_mode='Magnitude'): + """Creates Iso Surfaces presentation on the given field. + + Arguments: + proxy: the pipeline object, containig data + entity: the entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + custom_range: scalar range, if undefined the source range will be applied + nb_surfaces: number of surfaces, which will be generated + is_colored: this option allows to color the presentation according to + the corresponding data array values. If False - the presentation will + be one-coloured. + color: defines the presentation color as [R, G, B] triple. Taken into + account only if is_colored is False. + vector_mode: the mode of transformation of vector values + into scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude', 'X', 'Y' or 'Z'. + + Returns: + Iso Surfaces as representation object. + + """ + # We don't need mesh parts with no data on them + if entity == EntityType.NODE: + select_cells_with_data(proxy, on_points=[field_name]) + else: + select_cells_with_data(proxy, on_cells=[field_name]) + + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + pv.UpdatePipeline(time_value, proxy) + + # Extract only groups with data for the field + new_proxy = extract_groups_for_field(proxy, field_name, entity) + + # Do merge + source = pv.MergeBlocks(new_proxy) + + # Transform cell data into point data if necessary + if is_data_on_cells(proxy, field_name): + cell_to_point = pv.CellDatatoPointData(source) + cell_to_point.PassCellData = 1 + source = cell_to_point + + contour_by = ['POINTS', field_name] + + # Transform vector array to scalar array if necessary + if (nb_components > 1): + calc = get_calc_magnitude(source, EntityType.NODE, field_name) + contour_by = ['POINTS', calc.ResultArrayName] + source = calc + + # Contour filter settings + contour = pv.Contour(source) + contour.ComputeScalars = 1 + contour.ContourBy = contour_by + + # Specify the range + scalar_range = custom_range + if (scalar_range is None): + scalar_range = get_data_range(proxy, entity, + field_name, cut_off=True) + + # Get contour values for the range + surfaces = get_contours(scalar_range, nb_surfaces) + + # Set contour values + contour.Isosurfaces = surfaces + + # Get Iso Surfaces representation object + isosurfaces = pv.GetRepresentation(contour) + + # Get lookup table + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set display properties + if (is_colored): + isosurfaces.ColorAttributeType = EntityType.get_pvtype(entity) + isosurfaces.ColorArrayName = field_name + else: + isosurfaces.ColorArrayName = '' + if color: + isosurfaces.DiffuseColor = color + isosurfaces.LookupTable = lookup_table + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + return isosurfaces + + +def GaussPointsOnField(proxy, entity, field_name, + timestamp_nb, + is_deformed=True, scale_factor=None, + is_colored=True, color=None, + primitive=GaussType.SPRITE, + is_proportional=True, + max_pixel_size=256, + multiplier=None, vector_mode='Magnitude'): + """Creates Gauss Points on the given field. + + Arguments: + + proxy: the pipeline object, containig data + entity: the field entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + is_deformed: defines whether the Gauss Points will be deformed or not + scale_factor -- the scale factor for deformation. Will be taken into + account only if is_deformed is True. + If not passed by user, default scale will be computed. + is_colored -- defines whether the Gauss Points will be multicolored, + using the corresponding data values + color: defines the presentation color as [R, G, B] triple. Taken into + account only if is_colored is False. + primitive: primitive type from GaussType + is_proportional: if True, the size of primitives will depends on + the gauss point value + max_pixel_size: the maximum sizr of the Gauss Points primitive in pixels + multiplier: coefficient between data values and the size of primitives + If not passed by user, default scale will be computed. + vector_mode: the mode of transformation of vector values into + scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude' - vector module; + 'X', 'Y', 'Z' - vector components. + + Returns: + Gauss Points as representation object. + + """ + # We don't need mesh parts with no data on them + if entity == EntityType.NODE: + select_cells_with_data(proxy, on_points=[field_name]) + else: + select_cells_with_data(proxy, on_cells=[field_name]) + + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + proxy.UpdatePipeline(time=time_value) + + # Extract only groups with data for the field + source = extract_groups_for_field(proxy, field_name, entity) + + # Quadrature point arrays + qp_arrays = proxy.QuadraturePointArrays.Available + + # If no quadrature point array is passed, use cell centers + if field_name in qp_arrays: + generate_qp = pv.GenerateQuadraturePoints(source) + generate_qp.SelectSourceArray = ['CELLS', 'ELGA_Offset'] + source = generate_qp + else: + # Cell centers + cell_centers = pv.CellCenters(source) + cell_centers.VertexCells = 1 + source = cell_centers + + source.UpdatePipeline() + + # Check if deformation enabled + if is_deformed and nb_components > 1: + vector_array = field_name + # If the given vector array has only 2 components, add the third one + if nb_components == 2: + calc = get_add_component_calc(source, + EntityType.NODE, field_name) + vector_array = calc.ResultArrayName + source = calc + + # Warp by vector + warp_vector = pv.WarpByVector(source) + warp_vector.Vectors = [vector_array] + if scale_factor is not None: + warp_vector.ScaleFactor = scale_factor + else: + def_scale = get_default_scale(PrsTypeEnum.DEFORMEDSHAPE, proxy, + entity, field_name) + warp_vector.ScaleFactor = def_scale + warp_vector.UpdatePipeline() + source = warp_vector + + # Get Gauss Points representation object + gausspnt = pv.GetRepresentation(source) + + # Get lookup table + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set display properties + if is_colored: + gausspnt.ColorAttributeType = EntityType.get_pvtype(entity) + gausspnt.ColorArrayName = field_name + else: + gausspnt.ColorArrayName = '' + if color: + gausspnt.DiffuseColor = color + + gausspnt.LookupTable = lookup_table + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + # Set point sprite representation + gausspnt.Representation = 'Point Sprite' + + # Point sprite settings + gausspnt.InterpolateScalarsBeforeMapping = 0 + gausspnt.MaxPixelSize = max_pixel_size + + # Render mode + gausspnt.RenderMode = GaussType.get_mode(primitive) + + #if primitive == GaussType.SPRITE: + # Set texture + # TODO(MZN): replace with pvsimple high-level interface + # texture = sm.CreateProxy("textures", "SpriteTexture") + # alphamprop = texture.GetProperty("AlphaMethod") + # alphamprop.SetElement(0, 2) # Clamp + # alphatprop = texture.GetProperty("AlphaThreshold") + # alphatprop.SetElement(0, 63) + # maxprop = texture.GetProperty("Maximum") + # maxprop.SetElement(0, 255) + # texture.UpdateVTKObjects() + + # gausspnt.Texture = texture + #gausspnt.Texture.AlphaMethod = 'Clamp' + #gausspnt.Texture.AlphaThreshold = 63 + #gausspnt.Texture.Maximum= 255 + + # Proportional radius + gausspnt.RadiusUseScalarRange = 0 + gausspnt.RadiusIsProportional = 0 + + if is_proportional: + mult = multiplier + if mult is None: + mult = abs(0.1 / data_range[1]) + + gausspnt.RadiusScalarRange = data_range + gausspnt.RadiusTransferFunctionEnabled = 1 + gausspnt.RadiusMode = 'Scalar' + gausspnt.RadiusArray = ['POINTS', field_name] + if nb_components > 1: + v_comp = get_vector_component(vector_mode) + gausspnt.RadiusVectorComponent = v_comp + gausspnt.RadiusTransferFunctionMode = 'Table' + gausspnt.RadiusScalarRange = data_range + gausspnt.RadiusUseScalarRange = 1 + gausspnt.RadiusIsProportional = 1 + gausspnt.RadiusProportionalFactor = mult + else: + gausspnt.RadiusTransferFunctionEnabled = 0 + gausspnt.RadiusMode = 'Constant' + gausspnt.RadiusArray = ['POINTS', 'Constant Radius'] + + return gausspnt + +def GaussPointsOnField1(proxy, entity, field_name, + timestamp_nb, + is_colored=True, color=None, + primitive=GaussType.SPHERE, + is_proportional=True, + max_pixel_size=256, + multiplier=None, + vector_mode='Magnitude'): + """Creates Gauss Points on the given field. Use GaussPoints() Paraview interface. + + Arguments: + proxy: the pipeline object, containig data + entity: the field entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + is_colored -- defines whether the Gauss Points will be multicolored, + using the corresponding data values + color: defines the presentation color as [R, G, B] triple. Taken into + account only if is_colored is False. + primitive: primitive type from GaussType + is_proportional: if True, the size of primitives will depends on + the gauss point value + max_pixel_size: the maximum sizr of the Gauss Points primitive in pixels + multiplier: coefficient between data values and the size of primitives + If not passed by user, default scale will be computed. + vector_mode: the mode of transformation of vector values into + scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude' - vector module; + 'X', 'Y', 'Z' - vector components. + + Returns: + Gauss Points as representation object. + + """ + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + proxy.UpdatePipeline(time=time_value) + + # Create Gauss Points object + source = pv.GaussPoints(proxy) + source.UpdatePipeline() + + # Get Gauss Points representation object + gausspnt = pv.GetRepresentation(source) + + # Get lookup table + entity_data_info = None + point_data_info = source.GetPointDataInformation() + if field_name in point_data_info.keys(): + entity_data_info = point_data_info + else: + entity_data_info = source.GetCellDataInformation() + nb_components = entity_data_info[field_name].GetNumberOfComponents() + + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set display properties + if is_colored: + gausspnt.ColorAttributeType = EntityType.get_pvtype(entity) + gausspnt.ColorArrayName = field_name + else: + gausspnt.ColorArrayName = '' + if color: + gausspnt.DiffuseColor = color + + gausspnt.LookupTable = lookup_table + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + # Set point sprite representation + gausspnt.Representation = 'Point Sprite' + + # Point sprite settings + gausspnt.InterpolateScalarsBeforeMapping = 0 + gausspnt.MaxPixelSize = max_pixel_size + + # Render mode + gausspnt.RenderMode = GaussType.get_mode(primitive) + + #if primitive == GaussType.SPRITE: + # Set texture + # TODO(MZN): replace with pvsimple high-level interface + # texture = sm.CreateProxy("textures", "SpriteTexture") + # alphamprop = texture.GetProperty("AlphaMethod") + # alphamprop.SetElement(0, 2) # Clamp + # alphatprop = texture.GetProperty("AlphaThreshold") + # alphatprop.SetElement(0, 63) + # maxprop = texture.GetProperty("Maximum") + # maxprop.SetElement(0, 255) + # texture.UpdateVTKObjects() + + # gausspnt.Texture = texture + #gausspnt.Texture.AlphaMethod = 'Clamp' + #gausspnt.Texture.AlphaThreshold = 63 + #gausspnt.Texture.Maximum= 255 + + # Proportional radius + gausspnt.RadiusUseScalarRange = 0 + gausspnt.RadiusIsProportional = 0 + + if is_proportional: + mult = multiplier + if mult is None: + mult = abs(0.1 / data_range[1]) + + gausspnt.RadiusScalarRange = data_range + gausspnt.RadiusTransferFunctionEnabled = 1 + gausspnt.RadiusMode = 'Scalar' + gausspnt.RadiusArray = ['POINTS', field_name] + if nb_components > 1: + v_comp = get_vector_component(vector_mode) + gausspnt.RadiusVectorComponent = v_comp + gausspnt.RadiusTransferFunctionMode = 'Table' + gausspnt.RadiusScalarRange = data_range + gausspnt.RadiusUseScalarRange = 1 + gausspnt.RadiusIsProportional = 1 + gausspnt.RadiusProportionalFactor = mult + else: + gausspnt.RadiusTransferFunctionEnabled = 0 + gausspnt.RadiusMode = 'Constant' + gausspnt.RadiusArray = ['POINTS', 'Constant Radius'] + + return gausspnt + +def StreamLinesOnField(proxy, entity, field_name, timestamp_nb, + direction='BOTH', is_colored=False, color=None, + vector_mode='Magnitude'): + """Creates Stream Lines presentation on the given field. + + Arguments: + proxy: the pipeline object, containig data + entity: the entity type from PrsTypeEnum + field_name: the field name + timestamp_nb: the number of time step (1, 2, ...) + direction: the stream lines direction ('FORWARD', 'BACKWARD' or 'BOTH') + is_colored: this option allows to color the presentation according to + the corresponding data values. If False - the presentation will + be one-coloured. + color: defines the presentation color as [R, G, B] triple. Taken into + account only if is_colored is False. + vector_mode: the mode of transformation of vector values + into scalar values, applicable only if the field contains vector values. + Possible modes: 'Magnitude', 'X', 'Y' or 'Z'. + + Returns: + Stream Lines as representation object. + + """ + # We don't need mesh parts with no data on them + if entity == EntityType.NODE: + select_cells_with_data(proxy, on_points=[field_name]) + else: + select_cells_with_data(proxy, on_cells=[field_name]) + + # Check vector mode + nb_components = get_nb_components(proxy, entity, field_name) + check_vector_mode(vector_mode, nb_components) + + # Get time value + time_value = get_time(proxy, timestamp_nb) + + # Set timestamp + pv.GetRenderView().ViewTime = time_value + pv.UpdatePipeline(time_value, proxy) + + # Extract only groups with data for the field + new_proxy = extract_groups_for_field(proxy, field_name, entity) + + # Do merge + source = pv.MergeBlocks(new_proxy) + + # Cell data to point data + if is_data_on_cells(proxy, field_name): + cell_to_point = pv.CellDatatoPointData(source) + cell_to_point.PassCellData = 1 + cell_to_point.UpdatePipeline() + source = cell_to_point + + vector_array = field_name + # If the given vector array has only 2 components, add the third one + if nb_components == 2: + calc = get_add_component_calc(source, EntityType.NODE, field_name) + vector_array = calc.ResultArrayName + calc.UpdatePipeline() + source = calc + + # Stream Tracer + stream = pv.StreamTracer(source) + stream.SeedType = "Point Source" + stream.Vectors = ['POINTS', vector_array] + stream.SeedType = "Point Source" + stream.IntegrationDirection = direction + stream.IntegratorType = 'Runge-Kutta 2' + stream.UpdatePipeline() + + # Get Stream Lines representation object + if is_empty(stream): + return None + streamlines = pv.GetRepresentation(stream) + + # Get lookup table + lookup_table = get_lookup_table(field_name, nb_components, vector_mode) + + # Set field range if necessary + data_range = get_data_range(new_proxy, entity, + field_name, vector_mode) + lookup_table.LockScalarRange = 1 + lookup_table.RGBPoints = [data_range[0], 0, 0, 1, data_range[1], 1, 0, 0] + + # Set properties + if is_colored: + streamlines.ColorAttributeType = EntityType.get_pvtype(entity) + streamlines.ColorArrayName = field_name + else: + streamlines.ColorArrayName = '' + if color: + streamlines.DiffuseColor = color + + streamlines.LookupTable = lookup_table + + # Add scalar bar + add_scalar_bar(field_name, nb_components, + vector_mode, lookup_table, time_value) + + return streamlines + + +def MeshOnEntity(proxy, mesh_name, entity): + """Creates submesh of the entity type for the mesh. + + Arguments: + proxy -- the pipeline object, containig data + mesh_name -- the mesh name + entity -- the entity type + + Returns: + Submesh as representation object of the given source. + + """ + # Select all cell types + select_all_cells(proxy) + + # Get subset of groups on the given entity + subset = get_group_names(proxy, mesh_name, entity) + + # Select only groups of the given entity type + proxy.Groups = subset + proxy.UpdatePipeline() + + # Get representation object if the submesh is not empty + prs = None + if (proxy.GetDataInformation().GetNumberOfPoints() or + proxy.GetDataInformation().GetNumberOfCells()): + prs = pv.GetRepresentation(proxy) + prs.ColorArrayName = '' + + return prs + + +def MeshOnGroup(proxy, group_name): + """Creates submesh on the group. + + Arguments: + proxy -- the pipeline object, containig data + group_name -- the full group name + + Returns: + Representation object of the given source with single group + selected. + + """ + # Select all cell types + select_all_cells(proxy) + + # Select only the group with the given name + one_group = [group_name] + proxy.Groups = one_group + proxy.UpdatePipeline() + + # Get representation object if the submesh is not empty + prs = None + + # Check if the group was set + if proxy.Groups.GetData() == one_group: + group_entity = get_group_entity(group_name) + # Check if the submesh is not empty + nb_items = 0 + if group_entity == EntityType.NODE: + nb_items = proxy.GetDataInformation().GetNumberOfPoints() + elif group_entity == EntityType.CELL: + nb_items = proxy.GetDataInformation().GetNumberOfCells() + + if nb_items: + prs = pv.GetRepresentation(proxy) + prs.ColorArrayName = '' + + return prs + + +def CreatePrsForFile(paravis_instance, file_name, prs_types, + picture_dir, picture_ext): + """Build presentations of the given types for the file. + + Build presentations for all fields on all timestamps. + + Arguments: + paravis_instance: ParaVis module instance object + file_name: full path to the MED file + prs_types: the list of presentation types to build + picture_dir: the directory path for saving snapshots + picture_ext: graphics files extension (determines file type) + + """ + # Import MED file + print "Import " + file_name.split(os.sep)[-1] + "..." + + try: + paravis_instance.ImportFile(file_name) + proxy = pv.GetActiveSource() + if proxy is None: + print "FAILED" + else: + proxy.UpdatePipeline() + print "OK" + except: + print "FAILED" + else: + # Get view + view = pv.GetRenderView() + + # Create required presentations for the proxy + CreatePrsForProxy(proxy, view, prs_types, + picture_dir, picture_ext) + + +def CreatePrsForProxy(proxy, view, prs_types, picture_dir, picture_ext): + """Build presentations of the given types for all fields of the proxy. + + Save snapshots in graphics files (type depends on the given extension). + Stores the files in the given directory. + + Arguments: + proxy: the pipeline object, containig data + view: the render view + prs_types: the list of presentation types to build + picture_dir: the directory path for saving snapshots + picture_ext: graphics files extension (determines file type) + + """ + # List of the field names + field_names = list(proxy.PointArrays.GetData()) + nb_on_nodes = len(field_names) + field_names.extend(proxy.CellArrays.GetData()) + + # Add path separator to the end of picture path if necessery + if not picture_dir.endswith(os.sep): + picture_dir += os.sep + + # Mesh Presentation + if PrsTypeEnum.MESH in prs_types: + # Create Mesh presentation. Build all possible submeshes. + + # Remember the current state + groups = list(proxy.Groups) + + # Iterate on meshes + mesh_names = get_mesh_names(proxy) + for mesh_name in mesh_names: + # Build mesh on nodes and cells + for entity in (EntityType.NODE, EntityType.CELL): + entity_name = EntityType.get_name(entity) + if if_possible(proxy, mesh_name, entity, PrsTypeEnum.MESH): + print "Creating submesh on " + entity_name + " for '" + mesh_name + "' mesh... " + prs = MeshOnEntity(proxy, mesh_name, entity) + if prs is None: + print "FAILED" + continue + else: + print "OK" + # Construct image file name + pic_name = picture_dir + mesh_name + "_" + entity_name + "." + picture_ext + + # Show and dump the presentation into a graphics file + process_prs_for_test(prs, view, pic_name, False) + + # Build submesh on all groups of the mesh + mesh_groups = get_group_names(proxy, mesh_name, + entity, wo_nogroups=True) + for group in mesh_groups: + print "Creating submesh on group " + group + "... " + prs = MeshOnGroup(proxy, group) + if prs is None: + print "FAILED" + continue + else: + print "OK" + # Construct image file name + pic_name = picture_dir + group.replace('/', '_') + "." + picture_ext + + # Show and dump the presentation into a graphics file + process_prs_for_test(prs, view, pic_name, False) + + # Restore the state + proxy.Groups = groups + proxy.UpdatePipeline() + + # Presentations on fields + for (i, field_name) in enumerate(field_names): + # Select only the current field: + # necessary for getting the right timestamps + cell_arrays = proxy.CellArrays.GetData() + point_arrays = proxy.PointArrays.GetData() + field_entity = None + if (i >= nb_on_nodes): + field_entity = EntityType.CELL + proxy.PointArrays.DeselectAll() + proxy.CellArrays = [field_name] + else: + field_entity = EntityType.NODE + proxy.CellArrays.DeselectAll() + proxy.PointArrays = [field_name] + + # Get timestamps + proxy.UpdatePipelineInformation() + timestamps = proxy.TimestepValues.GetData() + + # Restore fields selection state + proxy.CellArrays = cell_arrays + proxy.PointArrays = point_arrays + proxy.UpdatePipelineInformation() + + for prs_type in prs_types: + # Ignore mesh presentation + if prs_type == PrsTypeEnum.MESH: + continue + + # Get name of presentation type + prs_name = PrsTypeEnum.get_name(prs_type) + + # Build the presentation if possible + possible = if_possible(proxy, field_name, + field_entity, prs_type) + if possible: + # Presentation type for graphics file name + f_prs_type = prs_name.replace(' ', '').upper() + + for timestamp_nb in xrange(1, len(timestamps) + 1): + time = timestamps[timestamp_nb - 1] + print "Creating " + prs_name + " on " + field_name + ", time = " + str(time) + "... " + prs = create_prs(prs_type, proxy, + field_entity, field_name, timestamp_nb) + if prs is None: + print "FAILED" + continue + else: + print "OK" + + # Construct image file name + pic_name = picture_dir + field_name + "_" + str(time) + "_" + f_prs_type + "." + picture_ext + + # Show and dump the presentation into a graphics file + process_prs_for_test(prs, view, pic_name) diff --git a/src/PV_SWIG/VTKWrapping/pvsimple.py b/src/PV_SWIG/VTKWrapping/pvsimple.py new file mode 100644 index 00000000..6a77e5f2 --- /dev/null +++ b/src/PV_SWIG/VTKWrapping/pvsimple.py @@ -0,0 +1,1171 @@ +# Copyright (C) 2010-2013 CEA/DEN, EDF R&D +# +# This library is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License. +# +# This library is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with this library; if not, write to the Free Software +# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +# +# See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com +# + +r"""simple is a module for using paraview server manager in Python. It +provides a simple convenience layer to functionality provided by the +C++ classes wrapped to Python as well as the servermanager module. + +A simple example: + from paraview.simple import * + + # Create a new sphere proxy on the active connection and register it + # in the sources group. + sphere = Sphere(ThetaResolution=16, PhiResolution=32) + + # Apply a shrink filter + shrink = Shrink(sphere) + + # Turn the visiblity of the shrink object on. + Show(shrink) + + # Render the scene + Render() +""" + +import paravisSM + +servermanager = paravisSM + +def enableMultiServer(): + servermanager.enableMultiServer() + +def switchActiveConnection(newActiveConnection=None, ns=None): + if not ns: + ns = globals() + _remove_functions(ns) + servermanager.switchActiveConnection(newActiveConnection) + _add_functions(ns) + +def Disconnect(ns=None, force=True): + if servermanager.ActiveConnection and (force or servermanager.MultiServerConnections == None): + if ns: + _remove_functions(ns) + _remove_functions(globals()) + if not servermanager.fromGUI: + servermanager.ProxyManager().DisableStateUpdateNotification() + servermanager.ProxyManager().UnRegisterProxies() + active_objects.view = None + active_objects.source = None + servermanager.Disconnect() + if not servermanager.fromGUI: + import gc + gc.collect() + +def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111): + """Creates a connection to a server. Example usage: + > Connect("amber") # Connect to a single server at default port + > Connect("amber", 12345) # Connect to a single server at port 12345 + > Connect("amber", 11111, "vis_cluster", 11111) # connect to data server, render server pair""" + Disconnect(globals(), False) + connection = servermanager.Connect(ds_host, ds_port, rs_host, rs_port) + _add_functions(globals()) + + servermanager.ProxyManager().DisableStateUpdateNotification() + servermanager.ProxyManager().UpdateFromRemote() + tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper") + if not tk: + try: + tk = servermanager.misc.TimeKeeper() + servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk) + except AttributeError: + print "Error: Could not create TimeKeeper" + + scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene") + if not scene: + try: + scene = AnimationScene() + scene.TimeKeeper = tk + except NameError: + print "Error: Could not create AnimationScene" + + servermanager.ProxyManager().EnableStateUpdateNotification() + servermanager.ProxyManager().TriggerStateUpdate() + + return connection + +def ReverseConnect(port=11111): + """Create a reverse connection to a server. Listens on port and waits for + an incoming connection from the server.""" + Disconnect(globals(), False) + connection = servermanager.ReverseConnect(port) + _add_functions(globals()) + + servermanager.ProxyManager().DisableStateUpdateNotification() + servermanager.ProxyManager().UpdateFromRemote() + tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper") + if not tk: + tk = servermanager.misc.TimeKeeper() + servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk) + + scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene") + if not scene: + scene = AnimationScene() + scene.TimeKeeper = tk + + servermanager.ProxyManager().EnableStateUpdateNotification() + servermanager.ProxyManager().TriggerStateUpdate() + + return connection + +def _create_view(view_xml_name): + "Creates and returns a 3D render view." + view = servermanager._create_view(view_xml_name) + servermanager.ProxyManager().RegisterProxy("views", \ + "my_view%d" % _funcs_internals.view_counter, view) + active_objects.view = view + _funcs_internals.view_counter += 1 + + tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0] + views = tk.Views + if not view in views: + views.append(view) + try: + scene = GetAnimationScene() + if not view in scene.ViewModules: + scene.ViewModules.append(view) + except servermanager.MissingProxy: + pass + return view + +def CreateRenderView(): + return _create_view("RenderView") + +def CreateXYPlotView(): + return _create_view("XYChartView") + +def CreateBarChartView(): + return _create_view("XYBarChartView") + +def CreateComparativeRenderView(): + return _create_view("ComparativeRenderView") + +def CreateComparativeXYPlotView(): + return _create_view("ComparativeXYPlotView") + +def CreateComparativeBarChartView(): + return _create_view("ComparativeBarChartView") + +def CreateParallelCoordinatesChartView(): + return _create_view("ParallelCoordinatesChartView") + +def Create2DRenderView(): + return _create_view("2DRenderView") + +def OpenDataFile(filename, **extraArgs): + """Creates a reader to read the give file, if possible. + This uses extension matching to determine the best reader possible. + If a reader cannot be identified, then this returns None.""" + session = servermanager.ActiveConnection.Session + reader_factor = servermanager.vtkSMProxyManager.GetProxyManager().GetReaderFactory() + if reader_factor.GetNumberOfRegisteredPrototypes() == 0: + reader_factor.RegisterPrototypes(session, "sources") + first_file = filename + if type(filename) == list: + first_file = filename[0] + if not reader_factor.TestFileReadability(first_file, session): + msg = "File not readable: %s " % first_file + raise RuntimeError, msg + if not reader_factor.CanReadFile(first_file, session): + msg = "File not readable. No reader found for '%s' " % first_file + raise RuntimeError, msg + prototype = servermanager.ProxyManager().GetPrototypeProxy( + reader_factor.GetReaderGroup(), reader_factor.GetReaderName()) + xml_name = paraview.make_name_valid(prototype.GetXMLLabel()) + reader_func = _create_func(xml_name, servermanager.sources) + if prototype.GetProperty("FileNames"): + reader = reader_func(FileNames=filename, **extraArgs) + else : + reader = reader_func(FileName=filename, **extraArgs) + return reader + +def CreateWriter(filename, proxy=None, **extraArgs): + """Creates a writer that can write the data produced by the source proxy in + the given file format (identified by the extension). If no source is + provided, then the active source is used. This doesn't actually write the + data, it simply creates the writer and returns it.""" + if not filename: + raise RuntimeError, "filename must be specified" + session = servermanager.ActiveConnection.Session + writer_factory = servermanager.vtkSMProxyManager.GetProxyManager().GetWriterFactory() + if writer_factory.GetNumberOfRegisteredPrototypes() == 0: + writer_factory.RegisterPrototypes(session, "writers") + if not proxy: + proxy = GetActiveSource() + if not proxy: + raise RuntimeError, "Could not locate source to write" + writer_proxy = writer_factory.CreateWriter(filename, proxy.SMProxy, proxy.Port) + return servermanager._getPyProxy(writer_proxy) + +def GetRenderView(): + """Returns the active view if there is one. Else creates and returns a new view.""" + view = active_objects.view + if not view: + # it's possible that there's no active view, but a render view exists. + # If so, locate that and return it (before trying to create a new one). + view = servermanager.GetRenderView() + if not view: + view = CreateRenderView() + return view + +def GetRenderViews(): + """Returns all render views as a list.""" + return servermanager.GetRenderViews() + +def GetRepresentation(proxy=None, view=None): + """Given a pipeline object and view, returns the corresponding representation object. + If pipeline object and view are not specified, active objects are used.""" + if not view: + view = active_objects.view + if not proxy: + proxy = active_objects.source + rep = servermanager.GetRepresentation(proxy, view) + if not rep: + rep = servermanager.CreateRepresentation(proxy, view) + servermanager.ProxyManager().RegisterProxy("representations", \ + "my_representation%d" % _funcs_internals.rep_counter, rep) + _funcs_internals.rep_counter += 1 + return rep + +def GetDisplayProperties(proxy=None, view=None): + """Given a pipeline object and view, returns the corresponding representation object. + If pipeline object and/or view are not specified, active objects are used.""" + return GetRepresentation(proxy, view) + +def Show(proxy=None, view=None, **params): + """Turns the visibility of a given pipeline object on in the given view. + If pipeline object and/or view are not specified, active objects are used.""" + if proxy == None: + proxy = GetActiveSource() + if proxy == None: + raise RuntimeError, "Show() needs a proxy argument or that an active source is set." + if not view and not active_objects.view: + CreateRenderView() + rep = GetDisplayProperties(proxy, view) + if rep == None: + raise RuntimeError, "Could not create a representation object for proxy %s" % proxy.GetXMLLabel() + for param in params.keys(): + setattr(rep, param, params[param]) + rep.Visibility = 1 + return rep + +def Hide(proxy=None, view=None): + """Turns the visibility of a given pipeline object off in the given view. + If pipeline object and/or view are not specified, active objects are used.""" + rep = GetDisplayProperties(proxy, view) + rep.Visibility = 0 + +def Render(view=None): + """Renders the given view (default value is active view)""" + if not view: + view = active_objects.view + view.StillRender() + if _funcs_internals.first_render: + # Not all views have a ResetCamera method + try: + view.ResetCamera() + view.StillRender() + except AttributeError: pass + _funcs_internals.first_render = False + return view + +def ResetCamera(view=None): + """Resets the settings of the camera to preserver orientation but include + the whole scene. If an argument is not provided, the active view is + used.""" + if not view: + view = active_objects.view + if hasattr(view, "ResetCamera"): + view.ResetCamera() + if hasattr(view, "ResetDisplay"): + view.ResetDisplay() + Render(view) + +def _DisableFirstRenderCameraReset(): + """Disable the first render camera reset. Normally a ResetCamera is called + automatically when Render is called for the first time after importing + this module.""" + _funcs_internals.first_render = False + +def SetProperties(proxy=None, **params): + """Sets one or more properties of the given pipeline object. If an argument + is not provided, the active source is used. Pass a list of property_name=value + pairs to this function to set property values. For example: + SetProperties(Center=[1, 2, 3], Radius=3.5) + """ + if not proxy: + proxy = active_objects.source + for param in params.keys(): + if not hasattr(proxy, param): + raise AttributeError("object has no property %s" % param) + setattr(proxy, param, params[param]) + +def GetProperty(*arguments, **keywords): + """Get one property of the given pipeline object. If keywords are used, + you can set the proxy and the name of the property that you want to get + like in the following example : + GetProperty({proxy=sphere, name="Radius"}) + If it's arguments that are used, then you have two case: + - if only one argument is used that argument will be + the property name. + - if two arguments are used then the first one will be + the proxy and the second one the property name. + Several example are given below: + GetProperty({name="Radius"}) + GetProperty({proxy=sphereProxy, name="Radius"}) + GetProperty( sphereProxy, "Radius" ) + GetProperty( "Radius" ) + """ + name = None + proxy = None + for key in keywords: + if key == "name": + name = keywords[key] + if key == "proxy": + proxy = keywords[key] + if len(arguments) == 1 : + name = arguments[0] + if len(arguments) == 2 : + proxy = arguments[0] + name = arguments[1] + if not name: + raise RuntimeError, "Expecting at least a property name as input. Otherwise keyword could be used to set 'proxy' and property 'name'" + if not proxy: + proxy = active_objects.source + return proxy.GetProperty(name) + +def SetDisplayProperties(proxy=None, view=None, **params): + """Sets one or more display properties of the given pipeline object. If an argument + is not provided, the active source is used. Pass a list of property_name=value + pairs to this function to set property values. For example: + SetProperties(Color=[1, 0, 0], LineWidth=2) + """ + rep = GetDisplayProperties(proxy, view) + SetProperties(rep, **params) + +def SetViewProperties(view=None, **params): + """Sets one or more properties of the given view. If an argument + is not provided, the active view is used. Pass a list of property_name=value + pairs to this function to set property values. For example: + SetProperties(Background=[1, 0, 0], UseImmediateMode=0) + """ + if not view: + view = active_objects.view + SetProperties(view, **params) + +def RenameSource(newName, proxy=None): + """Renames the given source. If the given proxy is not registered + in the sources group this method will have no effect. If no source is + provided, the active source is used.""" + if not proxy: + proxy = active_objects.source + pxm = servermanager.ProxyManager() + oldName = pxm.GetProxyName("sources", proxy) + if oldName: + pxm.RegisterProxy("sources", newName, proxy) + pxm.UnRegisterProxy("sources", oldName, proxy) + +def FindSource(name): + return servermanager.ProxyManager().GetProxy("sources", name) + +def GetSources(): + """Given the name of a source, return its Python object.""" + return servermanager.ProxyManager().GetProxiesInGroup("sources") + +def GetRepresentations(): + """Returns all representations (display properties).""" + return servermanager.ProxyManager().GetProxiesInGroup("representations") + +def UpdatePipeline(time=None, proxy=None): + """Updates (executes) the given pipeline object for the given time as + necessary (i.e. if it did not already execute). If no source is provided, + the active source is used instead.""" + if not proxy: + proxy = active_objects.source + if time: + proxy.UpdatePipeline(time) + else: + proxy.UpdatePipeline() + +def Delete(proxy=None): + """Deletes the given pipeline object or the active source if no argument + is specified.""" + if not proxy: + proxy = active_objects.source + # Unregister any helper proxies stored by a vtkSMProxyListDomain + for prop in proxy: + listdomain = prop.GetDomain('proxy_list') + if listdomain: + if listdomain.GetClassName() != 'vtkSMProxyListDomain': + continue + group = "pq_helper_proxies." + proxy.GetGlobalIDAsString() + for i in xrange(listdomain.GetNumberOfProxies()): + pm = servermanager.ProxyManager() + iproxy = listdomain.GetProxy(i) + name = pm.GetProxyName(group, iproxy) + if iproxy and name: + pm.UnRegisterProxy(group, name, iproxy) + + # Remove source/view from time keeper + tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0] + if isinstance(proxy, servermanager.SourceProxy): + try: + idx = tk.TimeSources.index(proxy) + del tk.TimeSources[idx] + except ValueError: + pass + else: + try: + idx = tk.Views.index(proxy) + del tk.Views[idx] + except ValueError: + pass + servermanager.UnRegister(proxy) + + # If this is a representation, remove it from all views. + if proxy.SMProxy.IsA("vtkSMRepresentationProxy") or \ + proxy.SMProxy.IsA("vtkSMNewWidgetRepresentationProxy"): + for view in GetRenderViews(): + view.Representations.remove(proxy) + # If this is a source, remove the representation iff it has no consumers + # Also change the active source if necessary + elif proxy.SMProxy.IsA("vtkSMSourceProxy"): + sources = servermanager.ProxyManager().GetProxiesInGroup("sources") + for i in range(proxy.GetNumberOfConsumers()): + if proxy.GetConsumerProxy(i) in sources: + raise RuntimeError("Source has consumers. It cannot be deleted " + + "until all consumers are deleted.") + #VSV:== + if proxy.IsSame(GetActiveSource()): + if hasattr(proxy, "Input") and proxy.Input: + if isinstance(proxy.Input, servermanager.Proxy): + SetActiveSource(proxy.Input) + else: + SetActiveSource(proxy.Input[0]) + else: SetActiveSource(None) + for rep in GetRepresentations().values(): + #VSV:== + if rep.Input.IsSame(proxy): + Delete(rep) + # Change the active view if necessary + elif proxy.SMProxy.IsA("vtkSMRenderViewProxy"): + ##VSV:== + if proxy.IsSame(GetActiveView()): + if len(GetRenderViews()) > 0: + SetActiveView(GetRenderViews()[0]) + else: + SetActiveView(None) + +def CreateLookupTable(**params): + """Create and return a lookup table. Optionally, parameters can be given + to assign to the lookup table. + """ + lt = servermanager.rendering.PVLookupTable() + servermanager.Register(lt) + SetProperties(lt, **params) + return lt + +def CreatePiecewiseFunction(**params): + """Create and return a piecewise function. Optionally, parameters can be + given to assign to the piecewise function. + """ + pfunc = servermanager.piecewise_functions.PiecewiseFunction() + servermanager.Register(pfunc) + SetProperties(pfunc, **params) + return pfunc + +def GetLookupTableForArray(arrayname, num_components, **params): + """Used to get an existing lookuptable for a array or to create one if none + exists. Keyword arguments can be passed in to initialize the LUT if a new + one is created.""" + proxyName = "%d.%s.PVLookupTable" % (int(num_components), arrayname) + lut = servermanager.ProxyManager().GetProxy("lookup_tables", proxyName) + if lut: + return lut + # No LUT exists for this array, create a new one. + # TODO: Change this to go a LookupTableManager that is shared with the GUI, + # so that the GUI and python end up create same type of LUTs. For now, + # python will create a Blue-Red LUT, unless overridden by params. + lut = servermanager.rendering.PVLookupTable( + ColorSpace="HSV", RGBPoints=[0, 0, 0, 1, 1, 1, 0, 0]) + SetProperties(lut, **params) + servermanager.Register(lut, registrationName=proxyName) + return lut + +def CreateScalarBar(**params): + """Create and return a scalar bar widget. The returned widget may + be added to a render view by appending it to the view's representations + The widget must have a valid lookup table before it is added to a view. + It is possible to pass the lookup table (and other properties) as arguments + to this method: + + lt = MakeBlueToRedLt(3.5, 7.5) + bar = CreateScalarBar(LookupTable=lt, Title="Velocity") + GetRenderView().Representations.append(bar) + + By default the returned widget is selectable and resizable. + """ + sb = servermanager.rendering.ScalarBarWidgetRepresentation() + servermanager.Register(sb) + sb.Selectable = 1 + sb.Resizable = 1 + sb.Enabled = 1 + sb.Title = "Scalars" + SetProperties(sb, **params) + return sb + +# TODO: Change this to take the array name and number of components. Register +# the lt under the name ncomp.array_name +def MakeBlueToRedLT(min, max): + # Define RGB points. These are tuples of 4 values. First one is + # the scalar values, the other 3 the RGB values. + rgbPoints = [min, 0, 0, 1, max, 1, 0, 0] + return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV") + +def _find_writer(filename): + """Internal function.""" + extension = None + parts = filename.split('.') + if len(parts) > 1: + extension = parts[-1] + else: + raise RuntimeError, "Filename has no extension, please specify a write" + + if extension == 'png': + return 'vtkPNGWriter' + elif extension == 'bmp': + return 'vtkBMPWriter' + elif extension == 'ppm': + return 'vtkPNMWriter' + elif extension == 'tif' or extension == 'tiff': + return 'vtkTIFFWriter' + elif extension == 'jpg' or extension == 'jpeg': + return 'vtkJPEGWriter' + else: + raise RuntimeError, "Cannot infer filetype from extension:", extension + +def AddCameraLink(viewProxy, viewProxyOther, linkName): + """Create a camera link between two view proxies. A name must be given + so that the link can be referred to by name. If a link with the given + name already exists it will be removed first.""" + if not viewProxyOther: viewProxyOther = GetActiveView() + link = servermanager.vtkSMCameraLink() + link.AddLinkedProxy(viewProxy.SMProxy, 1) + link.AddLinkedProxy(viewProxyOther.SMProxy, 2) + link.AddLinkedProxy(viewProxyOther.SMProxy, 1) + link.AddLinkedProxy(viewProxy.SMProxy, 2) + RemoveCameraLink(linkName) + servermanager.ProxyManager().RegisterLink(linkName, link) + +def RemoveCameraLink(linkName): + """Remove a camera link with the given name.""" + servermanager.ProxyManager().UnRegisterLink(linkName) + +def WriteImage(filename, view=None, **params): + """Saves the given view (or the active one if none is given) as an + image. Optionally, you can specify the writer and the magnification + using the Writer and Magnification named arguments. For example: + WriteImage("foo.mypng", aview, Writer=vtkPNGWriter, Magnification=2) + If no writer is provided, the type is determined from the file extension. + Currently supported extensions are png, bmp, ppm, tif, tiff, jpg and jpeg. + The writer is a VTK class that is capable of writing images. + Magnification is used to determine the size of the written image. The size + is obtained by multiplying the size of the view with the magnification. + Rendering may be done using tiling to obtain the correct size without + resizing the view.""" + if not view: + view = active_objects.view + writer = None + if params.has_key('Writer'): + writer = params['Writer'] + mag = 1 + if params.has_key('Magnification'): + mag = int(params['Magnification']) + if not writer: + writer = _find_writer(filename) + view.WriteImage(filename, writer, mag) + +def AnimateReader(reader=None, view=None, filename=None): + """This is a utility function that, given a reader and a view + animates over all time steps of the reader. If the optional + filename is provided, a movie is created (type depends on the + extension of the filename.""" + if not reader: + reader = active_objects.source + if not view: + view = active_objects.view + + return servermanager.AnimateReader(reader, view, filename) + + +def _create_func(key, module): + """Internal function.""" + + def CreateObject(*input, **params): + """This function creates a new proxy. For pipeline objects that accept inputs, + all non-keyword arguments are assumed to be inputs. All keyword arguments are + assumed to be property,value pairs and are passed to the new proxy.""" + + # Instantiate the actual object from the given module. + px = module.__dict__[key]() + + # Make sure non-keyword arguments are valid + for inp in input: + if inp != None and not isinstance(inp, servermanager.Proxy): + if px.GetProperty("Input") != None: + raise RuntimeError, "Expecting a proxy as input." + else: + raise RuntimeError, "This function does not accept non-keyword arguments." + + # Assign inputs + if px.GetProperty("Input") != None: + if len(input) > 0: + px.Input = input + else: + # If no input is specified, try the active pipeline object + if px.GetProperty("Input").GetRepeatable() and active_objects.get_selected_sources(): + px.Input = active_objects.get_selected_sources() + elif active_objects.source: + px.Input = active_objects.source + else: + if len(input) > 0: + raise RuntimeError, "This function does not expect an input." + + registrationName = None + for nameParam in ['registrationName', 'guiName']: + if nameParam in params: + registrationName = params[nameParam] + del params[nameParam] + + # Pass all the named arguments as property,value pairs + for param in params.keys(): + setattr(px, param, params[param]) + + try: + # Register the proxy with the proxy manager. + if registrationName: + group, name = servermanager.Register(px, registrationName=registrationName) + else: + group, name = servermanager.Register(px) + + + # Register pipeline objects with the time keeper. This is used to extract time values + # from sources. NOTE: This should really be in the servermanager controller layer. + if group == "sources": + has_tk = True + try: + tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0] + except IndexError: + has_tk = False + if has_tk: + sources = tk.TimeSources + if not px in sources: + sources.append(px) + + active_objects.source = px + except servermanager.MissingRegistrationInformation: + pass + + return px + + return CreateObject + +def _create_doc(new, old): + """Internal function.""" + import string + res = "" + for doc in (new, old): + ts = [] + strpd = doc.split('\n') + for s in strpd: + ts.append(s.lstrip()) + res += string.join(ts) + res += '\n' + return res + +def _func_name_valid(name): + """Internal function.""" + valid = True + for c in name: + if c == '(' or c ==')': + valid = False + break + return valid + +def _add_functions(g): + activeModule = servermanager.ActiveConnection.Modules + for m in [activeModule.filters, activeModule.sources, + activeModule.writers, activeModule.animation]: + dt = m.__dict__ + for key in dt.keys(): + cl = dt[key] + if not isinstance(cl, str): + if not key in g and _func_name_valid(key): + g[key] = _create_func(key, m) + exec "g[key].__doc__ = _create_doc(m.%s.__doc__, g[key].__doc__)" % key + +def _remove_functions(g): + list = [] + if servermanager.ActiveConnection: + list = [m for m in dir(servermanager.ActiveConnection.Modules) if m[0] != '_'] + + for m in list: + dt = servermanager.ActiveConnection.Modules.__dict__[m].__dict__ + for key in dt.keys(): + cl = dt[key] + if not isinstance(cl, str) and g.has_key(key): + g.pop(key) + #print "remove %s function" % key + +def GetActiveView(): + """Returns the active view.""" + return active_objects.view + +def SetActiveView(view): + """Sets the active view.""" + active_objects.view = view + +def GetActiveSource(): + """Returns the active source.""" + return active_objects.source + +def SetActiveSource(source): + """Sets the active source.""" + active_objects.source = source + +def GetActiveCamera(): + """Returns the active camera for the active view. The returned object + is an instance of vtkCamera.""" + return GetActiveView().GetActiveCamera() + +def GetAnimationScene(): + """Returns the application-wide animation scene. ParaView has only one + global animation scene. This method provides access to that. Users are + free to create additional animation scenes directly, but those scenes + won't be shown in the ParaView GUI.""" + animation_proxies = servermanager.ProxyManager().GetProxiesInGroup("animation") + scene = None + for aProxy in animation_proxies.values(): + if aProxy.GetXMLName() == "AnimationScene": + scene = aProxy + break + if not scene: + raise servermanager.MissingProxy, "Could not locate global AnimationScene." + return scene + +def WriteAnimation(filename, **params): + """Writes the current animation as a file. Optionally one can specify + arguments that qualify the saved animation files as keyword arguments. + Accepted options are as follows: + * Magnification (integer) : set the maginification factor for the saved + animation. + * Quality (0 [worst] or 1 or 2 [best]) : set the quality of the generated + movie (if applicable). + * Subsampling (integer) : setting whether the movie encoder should use + subsampling of the chrome planes or not, if applicable. Since the human + eye is more sensitive to brightness than color variations, subsampling + can be useful to reduce the bitrate. Default value is 0. + * BackgroundColor (3-tuple of doubles) : set the RGB background color to + use to fill empty spaces in the image. + * FrameRate (double): set the frame rate (if applicable).""" + scene = GetAnimationScene() + # ensures that the TimeKeeper track is created. + GetTimeTrack() + iw = servermanager.vtkSMAnimationSceneImageWriter() + iw.SetAnimationScene(scene.SMProxy) + iw.SetFileName(filename) + if params.has_key("Magnification"): + iw.SetMagnification(int(params["Magnification"])) + if params.has_key("Quality"): + iw.SetQuality(int(params["Quality"])) + if params.has_key("Subsampling"): + iw.SetSubsampling(int(params["Subsampling"])) + if params.has_key("BackgroundColor"): + iw.SetBackgroundColor(params["BackgroundColor"]) + if params.has_key("FrameRate"): + iw.SetFrameRate(float(params["FrameRate"])) + iw.Save() + +def _GetRepresentationAnimationHelper(sourceproxy): + """Internal method that returns the representation animation helper for a + source proxy. It creates a new one if none exists.""" + # ascertain that proxy is a source proxy + if not sourceproxy in GetSources().values(): + return None + for proxy in servermanager.ProxyManager(): + if proxy.GetXMLName() == "RepresentationAnimationHelper" and\ + proxy.GetProperty("Source").IsProxyAdded(sourceproxy.SMProxy): + return proxy + # create a new helper + proxy = servermanager.misc.RepresentationAnimationHelper( + Source=sourceproxy) + servermanager.ProxyManager().RegisterProxy( + "pq_helper_proxies.%s" % sourceproxy.GetGlobalIDAsString(), + "RepresentationAnimationHelper", proxy) + return proxy + +def GetAnimationTrack(propertyname_or_property, index=None, proxy=None): + """Returns an animation cue for the property. If one doesn't exist then a + new one will be created. + Typical usage: + track = GetAnimationTrack("Center", 0, sphere) or + track = GetAnimationTrack(sphere.GetProperty("Radius")) or + + # this returns the track to animate visibility of the active source in + # all views. + track = GetAnimationTrack("Visibility") + + For animating properties on implicit planes etc., use the following + signatures: + track = GetAnimationTrack(slice.SliceType.GetProperty("Origin"), 0) or + track = GetAnimationTrack("Origin", 0, slice.SliceType) + + """ + if not proxy: + proxy = GetActiveSource() + if not isinstance(proxy, servermanager.Proxy): + raise TypeError, "proxy must be a servermanager.Proxy instance" + if isinstance(propertyname_or_property, str): + propertyname = propertyname_or_property + elif isinstance(propertyname_or_property, servermanager.Property): + prop = propertyname_or_property + propertyname = prop.Name + proxy = prop.Proxy + else: + raise TypeError, "propertyname_or_property must be a string or servermanager.Property" + + # To handle the case where the property is actually a "display" property, in + # which case we are actually animating the "RepresentationAnimationHelper" + # associated with the source. + if propertyname in ["Visibility", "Opacity"]: + proxy = _GetRepresentationAnimationHelper(proxy) + if not proxy or not proxy.GetProperty(propertyname): + raise AttributeError, "Failed to locate property %s" % propertyname + + scene = GetAnimationScene() + for cue in scene.Cues: + try: + if cue.AnimatedProxy.IsSame(proxy) and\ + cue.AnimatedPropertyName == propertyname: + if index == None or index.IsSame(cue.AnimatedElement): ##index == cue.AnimatedElement: + return cue + except AttributeError: + pass + + # matching animation track wasn't found, create a new one. + cue = KeyFrameAnimationCue() + cue.AnimatedProxy = proxy + cue.AnimatedPropertyName = propertyname + if index != None: + cue.AnimatedElement = index + scene.Cues.append(cue) + return cue + +def GetCameraTrack(view=None): + """Returns the camera animation track for the given view. If no view is + specified, active view will be used. If no exisiting camera animation track + is found, a new one will be created.""" + if not view: + view = GetActiveView() + if not view: + raise ValueError, "No view specified" + scene = GetAnimationScene() + for cue in scene.Cues: + if cue.AnimatedProxy.IsSame(view) and\ + cue.GetXMLName() == "CameraAnimationCue": + return cue + # no cue was found, create a new one. + cue = CameraAnimationCue() + cue.AnimatedProxy = view + scene.Cues.append(cue) + return cue + +def GetTimeTrack(): + """Returns the animation track used to control the time requested from all + readers/filters during playback. + This is the "TimeKeeper - Time" track shown in ParaView's 'Animation View'. + If none exists, a new one will be created.""" + scene = GetAnimationScene() + tk = scene.TimeKeeper + for cue in scene.Cues: + if cue.GetXMLName() == "TimeAnimationCue" and cue.AnimatedProxy.IsSame(tk)\ + and cue.AnimatedPropertyName == "Time": + return cue + # no cue was found, create a new one. + cue = TimeAnimationCue() + cue.AnimatedProxy = tk + cue.AnimatedPropertyName = "Time" + scene.Cues.append(cue) + return cue + +def LoadXML(xmlstring, ns=None): + """Given a server manager XML as a string, parse and process it. + If you loaded the simple module with from paraview.simple import *, + make sure to pass globals() as the second arguments: + LoadXML(xmlstring, globals()) + Otherwise, the new functions will not appear in the global namespace.""" + if not ns: + ns = globals() + servermanager.LoadXML(xmlstring) + _add_functions(ns) + +def LoadPlugin(filename, remote=True, ns=None): + """Loads a ParaView plugin and updates this module with new constructors + if any. The remote argument (default to True) is to specify whether + the plugin will be loaded on client (remote=False) or on server (remote=True). + If you loaded the simple module with from paraview.simple import *, + make sure to pass globals() as an argument: + LoadPlugin("myplugin", False, globals()), to load on client; + LoadPlugin("myplugin", True, globals()), to load on server; + LoadPlugin("myplugin", ns=globals()), to load on server. + Otherwise, the new functions will not appear in the global namespace.""" + + if not ns: + ns = globals() + servermanager.LoadPlugin(filename, remote) + _add_functions(ns) + +def LoadDistributedPlugin(pluginname, remote=True, ns=None): + """Loads a plugin that's distributed with the executable. This uses the + information known about plugins distributed with ParaView to locate the + shared library for the plugin to load. Raises a RuntimeError if the plugin + was not found.""" + if not servermanager.ActiveConnection: + raise RuntimeError, "Cannot load a plugin without a session." + plm = servermanager.vtkSMProxyManager.GetProxyManager().GetPluginManager() + if remote: + session = servermanager.ActiveConnection.Session + info = plm.GetRemoteInformation(session) + else: + info = plm.GetLocalInformation() + for cc in range(0, info.GetNumberOfPlugins()): + if info.GetPluginName(cc) == pluginname: + return LoadPlugin(info.GetPluginFileName(cc), remote, ns) + raise RuntimeError, "Plugin '%s' not found" % pluginname + +def GetLayouts(): + """Returns the layout proxies on the active session. + Layout proxies are used to place views in a grid.""" + return servermanager.ProxyManager().GetProxiesInGroup("layouts") + +def GetLayout(view=None): + """Return the layout containing the give view, if any. + If no view is specified, active view is used. + """ + if not view: + view = GetActiveView() + if not view: + raise RuntimeError, "No active view was found." + layouts = GetLayouts() + for layout in layouts.values(): + if layout.GetViewLocation(view) != -1: + return layout + return None + + +def SelectCells(query=None, proxy=None): + """Select cells satisfying the query. If query is None, then all cells are + selected. If proxy is None, then the active source is used.""" + if not proxy: + proxy = GetActiveSource() + if not proxy: + raise RuntimeError, "No active source was found." + + if not query: + # This ends up being true for all cells. + query = "id >= 0" + + # Note, selSource is not registered with the proxy manager. + selSource = servermanager.sources.SelectionQuerySource() + selSource.FieldType = "CELL" + selSource.QueryString = str(query) + proxy.SMProxy.SetSelectionInput(proxy.Port, selSource.SMProxy, 0) + return selSource + +def ClearSelection(proxy=None): + """Clears the selection on the active source.""" + if not proxy: + proxy = GetActiveSource() + if not proxy: + raise RuntimeError, "No active source was found." + proxy.SMProxy.SetSelectionInput(proxy.Port, None, 0) + +class ActiveObjects(object): + """This class manages the active objects (source and view). The active + objects are shared between Python and the user interface. This class + is for internal use. Use the Set/Get methods for setting and getting + active objects.""" + def __get_selection_model(self, name, session=None): + "Internal method." + if session and not servermanager.ActiveConnection.Session.IsSame(session): + raise RuntimeError, "Try to set an active object with invalid active connection." + pxm = servermanager.ProxyManager(session) + model = pxm.GetSelectionModel(name) + if not model: + model = servermanager.vtkSMProxySelectionModel() + pxm.RegisterSelectionModel(name, model) + return model + + def set_view(self, view): + "Sets the active view." + active_view_model = self.__get_selection_model("ActiveView") + if view: + active_view_model = self.__get_selection_model("ActiveView", view.GetSession()) + active_view_model.SetCurrentProxy(view.SMProxy, 0) + else: + active_view_model = self.__get_selection_model("ActiveView") + active_view_model.SetCurrentProxy(None, 0) + + def get_view(self): + "Returns the active view." + return servermanager._getPyProxy( + self.__get_selection_model("ActiveView").GetCurrentProxy()) + + def set_source(self, source): + "Sets the active source." + active_sources_model = self.__get_selection_model("ActiveSources") + if source: + # 3 == CLEAR_AND_SELECT + active_sources_model = self.__get_selection_model("ActiveSources", source.GetSession()) + active_sources_model.SetCurrentProxy(source.SMProxy, 3) + else: + active_sources_model = self.__get_selection_model("ActiveSources") + active_sources_model.SetCurrentProxy(None, 3) + + def __convert_proxy(self, px): + "Internal method." + if not px: + return None + if px.IsA("vtkSMSourceProxy"): + return servermanager._getPyProxy(px) + else: + return servermanager.OutputPort( + servermanager._getPyProxy(px.GetSourceProxy()), + px.GetPortIndex()) + + def get_source(self): + "Returns the active source." + return self.__convert_proxy( + self.__get_selection_model("ActiveSources").GetCurrentProxy()) + + def get_selected_sources(self): + "Returns the set of sources selected in the pipeline browser." + model = self.__get_selection_model("ActiveSources") + proxies = [] + for i in xrange(model.GetNumberOfSelectedProxies()): + proxies.append(self.__convert_proxy(model.GetSelectedProxy(i))) + return proxies + + view = property(get_view, set_view) + source = property(get_source, set_source) + +class _funcs_internals: + """Internal class.""" + first_render = True + view_counter = 0 + rep_counter = 0 + +def demo1(): + """Simple demo that create the following pipeline + sphere - shrink - \ + - append + cone - / + """ + # Create a sphere of radius = 2, theta res. = 32 + # This object becomes the active source. + ss = Sphere(Radius=2, ThetaResolution=32) + # Apply the shrink filter. The Input property is optional. If Input + # is not specified, the filter is applied to the active source. + shr = Shrink(Input=ss) + # Create a cone source. + cs = Cone() + # Append cone and shrink + app = AppendDatasets() + app.Input = [shr, cs] + # Show the output of the append filter. The argument is optional + # as the app filter is now the active object. + Show(app) + # Render the default view. + Render() + +def demo2(fname="/Users/berk/Work/ParaView/ParaViewData/Data/disk_out_ref.ex2"): + """This demo shows the use of readers, data information and display + properties.""" + + # Create the exodus reader and specify a file name + reader = ExodusIIReader(FileName=fname) + # Get the list of point arrays. + avail = reader.PointVariables.Available + print avail + # Select all arrays + reader.PointVariables = avail + + # Turn on the visibility of the reader + Show(reader) + # Set representation to wireframe + SetDisplayProperties(Representation = "Wireframe") + # Black background is not pretty + SetViewProperties(Background = [0.4, 0.4, 0.6]) + Render() + # Change the elevation of the camera. See VTK documentation of vtkCamera + # for camera parameters. + # NOTE: THIS WILL BE SIMPLER + GetActiveCamera().Elevation(45) + Render() + # Now that the reader executed, let's get some information about it's + # output. + pdi = reader[0].PointData + # This prints a list of all read point data arrays as well as their + # value ranges. + print 'Number of point arrays:', len(pdi) + for i in range(len(pdi)): + ai = pdi[i] + print "----------------" + print "Array:", i, " ", ai.Name, ":" + numComps = ai.GetNumberOfComponents() + print "Number of components:", numComps + for j in range(numComps): + print "Range:", ai.GetRange(j) + # White is boring. Let's color the geometry using a variable. + # First create a lookup table. This object controls how scalar + # values are mapped to colors. See VTK documentation for + # details. + # Map min (0.00678) to blue, max (0.0288) to red + SetDisplayProperties(LookupTable = MakeBlueToRedLT(0.00678, 0.0288)) + # Color by point array called Pres + SetDisplayProperties(ColorAttributeType = "POINT_DATA") + SetDisplayProperties(ColorArrayName = "Pres") + Render() + +def PrintTrace(): + print paravisSM.myParavis.GetTrace() + +def SaveTrace(fileName): + paravisSM.myParavis.SaveTrace(fileName) + + +if not servermanager.ActiveConnection: + Connect() +else: + _add_functions(globals()) + +def ImportFile(theFileName): + paravisSM.ImportFile(theFileName) + +active_objects = ActiveObjects() +active_objects.view = GetRenderView() diff --git a/src/PV_SWIG/servermanager.diff b/src/PV_SWIG/VTKWrapping/servermanager.diff similarity index 100% rename from src/PV_SWIG/servermanager.diff rename to src/PV_SWIG/VTKWrapping/servermanager.diff diff --git a/src/PV_SWIG/simple.diff b/src/PV_SWIG/VTKWrapping/simple.diff similarity index 100% rename from src/PV_SWIG/simple.diff rename to src/PV_SWIG/VTKWrapping/simple.diff diff --git a/src/PV_SWIG/paravis.py b/src/PV_SWIG/paravis.py index d5c228ed..7dbfa2df 100644 --- a/src/PV_SWIG/paravis.py +++ b/src/PV_SWIG/paravis.py @@ -67,31 +67,12 @@ def ImportFile(theFileName): "Import a file of any format supported by ParaView" myParavis.ImportFile(theFileName) - -def createFunction(theName): - "Create function - constructor of Paravis object" - def MyFunction(): - return myParavis.CreateClass(theName) - return MyFunction - - -def createConstructors(): - "Create constructor functions according to list of extracted classes" - g = globals() - aClassNames = myParavis.GetClassesList(); - for aName in aClassNames: - g[aName] = createFunction(aName) - -## Initialize of a PARAVIS interface +## Initialize PARAVIS interface myParavis = Initialize(orb, naming_service,lcc,myStudyManager,myStudy, 2) -## Initialize constructor functions -createConstructors() - ## Initialize Paravis static objects -vtkSMObject = vtkSMObject() -vtkProcessModule = vtkProcessModule() -vtkPVPythonModule = vtkPVPythonModule() -vtkSMProxyManager = vtkSMProxyManager() - +#vtkSMObject = vtkSMObject() +#vtkProcessModule = vtkProcessModule() +#vtkPVPythonModule = vtkPVPythonModule() +#vtkSMProxyManager = vtkSMProxyManager() diff --git a/src/PV_SWIG/paravisSM.py b/src/PV_SWIG/paravisSM.py index 8237dfc1..1586fcdf 100644 --- a/src/PV_SWIG/paravisSM.py +++ b/src/PV_SWIG/paravisSM.py @@ -17,2998 +17,16 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -r"""servermanager is a module for using paraview server manager in Python. -One can always use the server manager API directly. However, this module -provides an interface easier to use from Python by wrapping several VTK -classes around Python classes. - -Note that, upon load, this module will create several sub-modules: sources, -filters and rendering. These modules can be used to instantiate specific -proxy types. For a list, try "dir(servermanager.sources)" - -A simple example: - from paraview.servermanager import * - - # Creates a new built-in session and makes it the active session. - Connect() - - # Creates a new render view on the active session. - renModule = CreateRenderView() - - # Create a new sphere proxy on the active session and register it - # in the sources group. - sphere = sources.SphereSource(registrationGroup="sources", ThetaResolution=16, PhiResolution=32) - - # Create a representation for the sphere proxy and adds it to the render - # module. - display = CreateRepresentation(sphere, renModule) - - renModule.StillRender() +r""" This module is a direct forward to the initial +'servermanager' module of ParaView. """ - - -import re, os, new, sys +from paraview import servermanager from paravis import * -# VTN: Avoid paraview.* instructions in this file. -# It leads to problems during execution. - -def _wrap_property(proxy, smproperty): - """ Internal function. - Given a server manager property and its domains, returns the - appropriate python object. - """ - property = None - if smproperty.IsA("vtkSMStringVectorProperty"): - al = smproperty.GetDomain("array_list") - if al and al.IsA("vtkSMArraySelectionDomain") and \ - smproperty.GetRepeatable(): - property = ArrayListProperty(proxy, smproperty) - elif al and al.IsA("vtkSMArrayListDomain") and smproperty.GetNumberOfElements() == 5: - property = ArraySelectionProperty(proxy, smproperty) - else: - iter = smproperty.NewDomainIterator() - isFileName = False - while not iter.IsAtEnd(): - # Refer to BUG #9710 to see why optional domains need to be - # ignored. - if iter.GetDomain().IsA("vtkSMFileListDomain") and \ - iter.GetDomain().GetIsOptional() == 0 : - isFileName = True - break - iter.Next() - iter.UnRegister(None) - if isFileName: - property = FileNameProperty(proxy, smproperty) - elif _make_name_valid(smproperty.GetXMLLabel()) == 'ColorArrayName': - property = ColorArrayProperty(proxy, smproperty) - else: - property = VectorProperty(proxy, smproperty) - elif smproperty.IsA("vtkSMVectorProperty"): - if smproperty.IsA("vtkSMIntVectorProperty") and \ - smproperty.GetDomain("enum"): - property = EnumerationProperty(proxy, smproperty) - else: - property = VectorProperty(proxy, smproperty) - elif smproperty.IsA("vtkSMInputProperty"): - property = InputProperty(proxy, smproperty) - elif smproperty.IsA("vtkSMProxyProperty"): - property = ProxyProperty(proxy, smproperty) - else: - property = Property(proxy, smproperty) - return property - -class Proxy(object): - """Proxy for a server side object. A proxy manages the lifetime of - one or more server manager objects. It also provides an interface - to set and get the properties of the server side objects. These - properties are presented as Python properties. For example, - you can set a property Foo using the following: - proxy.Foo = (1,2) - or - proxy.Foo.SetData((1,2)) - or - proxy.Foo[0:2] = (1,2) - For more information, see the documentation of the property which - you can obtain with - help(proxy.Foo). - - This class also provides an iterator which can be used to iterate - over all properties. - eg: - proxy = Proxy(proxy=smproxy) - for property in proxy: - print property - - For advanced users: - This is a python class that wraps a vtkSMProxy.. Makes it easier to - set/get properties. - Instead of: - proxy.GetProperty("Foo").SetElement(0, 1) - proxy.GetProperty("Foo").SetElement(0, 2) - you can do: - proxy.Foo = (1,2) - or - proxy.Foo.SetData((1,2)) - or - proxy.Foo[0:2] = (1,2) - Instead of: - proxy.GetProperty("Foo").GetElement(0) - you can do: - proxy.Foo.GetData()[0] - or - proxy.Foo[0] - For proxy properties, you can use append: - proxy.GetProperty("Bar").AddProxy(foo) - you can do: - proxy.Bar.append(foo) - Properties support most of the list API. See VectorProperty and - ProxyProperty documentation for details. - - Please note that some of the methods accessible through the Proxy - class are not listed by help() because the Proxy objects forward - unresolved attributes to the underlying object. To get the full list, - see also dir(proxy.SMProxy). See also the doxygen based documentation - of the vtkSMProxy C++ class. - """ - - def __init__(self, **args): - """ Default constructor. It can be used to initialize properties - by passing keyword arguments where the key is the name of the - property. In addition registrationGroup and registrationName (optional) - can be specified (as keyword arguments) to automatically register - the proxy with the proxy manager. """ - self.add_attribute('Observed', None) - self.add_attribute('ObserverTag', -1) - self.add_attribute('_Proxy__Properties', {}) - self.add_attribute('_Proxy__LastAttrName', None) - self.add_attribute('SMProxy', None) - self.add_attribute('Port', 0) - - if 'port' in args: - self.Port = args['port'] - del args['port'] - - update = True - if 'no_update' in args: - if args['no_update']: - update = False - del args['no_update'] - - if 'proxy' in args: - self.InitializeFromProxy(args['proxy']) - del args['proxy'] - else: - self.Initialize(None, update) - if 'registrationGroup' in args: - registrationGroup = args['registrationGroup'] - del args['registrationGroup'] - registrationName = self.SMProxy.GetGlobalIDAsString() - if 'registrationName' in args: - registrationName = args['registrationName'] - del args['registrationName'] - pxm = ProxyManager() - pxm.RegisterProxy(registrationGroup, registrationName, self.SMProxy) - if update: - self.UpdateVTKObjects() - for key in args.keys(): - setattr(self, key, args[key]) - # Visit all properties so that they are created - for prop in self: - pass - - def __setattr__(self, name, value): - try: - setter = getattr(self.__class__, name) - setter = setter.__set__ - except AttributeError: - if not hasattr(self, name): - raise AttributeError("Attribute %s does not exist. " % name + - " This class does not allow addition of new attributes to avoid " + - "mistakes due to typos. Use add_attribute() if you really want " + - "to add this attribute.") - self.__dict__[name] = value - else: - setter(self, value) - - def add_attribute(self, name, value): - self.__dict__[name] = value - - def __del__(self): - """Destructor. Cleans up all observers as well as remove - the proxy from the _pyproxies dictionary""" - # Make sure that we remove observers we added - if self.Observed: - observed = self.Observed - tag = self.ObserverTag - self.Observed = None - self.ObserverTag = -1 - observed.RemoveObserver(tag) - if _pyproxies and self.SMProxy and (self.SMProxy, self.Port) in _pyproxies: - del _pyproxies[(self.SMProxy, self.Port)] - - def InitializeFromProxy(self, aProxy, update=True): - """Constructor. Assigns proxy to self.SMProxy, updates the server - object as well as register the proxy in _pyproxies dictionary.""" - import weakref - self.SMProxy = aProxy - if update: - self.SMProxy.UpdateVTKObjects() - _pyproxies[(self.SMProxy, self.Port)] = weakref.ref(self) - - def Initialize(self): - "Overridden by the subclass created automatically" - pass - - def __eq__(self, other): - "Returns true if the underlying SMProxies are the same." - if isinstance(other, Proxy): - try: - if self.Port != other.Port: - return False - except: - pass - ## VSV using IsSame instead == - return self.SMProxy.IsSame(other.SMProxy) - return self.SMProxy.IsSame(other) - - def __ne__(self, other): - "Returns false if the underlying SMProxies are the same." - return not self.__eq__(other) - - def __iter__(self): - "Creates an iterator for the properties." - return PropertyIterator(self) - - def SetPropertyWithName(self, pname, arg): - """Generic method for setting the value of a property.""" - prop = self.GetProperty(pname) - if prop is None: - raise RuntimeError, "Property %s does not exist. Please check the property name for typos." % pname - prop.SetData(arg) - - def GetPropertyValue(self, name): - """Returns a scalar for properties with 1 elements, the property - itself for vectors.""" - p = self.GetProperty(name) - if isinstance(p, VectorProperty): - if p.GetNumberOfElements() == 1 and not p.GetRepeatable(): - if p.SMProperty.IsA("vtkSMStringVectorProperty") or not p.GetArgumentIsArray(): - return p[0] - elif isinstance(p, InputProperty): - if not p.GetMultipleInput(): - if len(p) > 0: - return p[0] - else: - return None - elif isinstance(p, ProxyProperty): - if not p.GetRepeatable(): - if len(p) > 0: - return p[0] - else: - return None - return p - - def GetProperty(self, name): - """Given a property name, returns the property object.""" - if name in self.__Properties and self.__Properties[name](): - return self.__Properties[name]() - smproperty = self.SMProxy.GetProperty(name) - # Maybe they are looking by the label. Try to match that. - if not smproperty: - iter = PropertyIterator(self) - for prop in iter: - if name == _make_name_valid(iter.PropertyLabel): - smproperty = prop.SMProperty - break - if smproperty: - property = _wrap_property(self, smproperty) - if property is not None: - import weakref - self.__Properties[name] = weakref.ref(property) - return property - return None - - def ListProperties(self): - """Returns a list of all property names on this proxy.""" - property_list = [] - iter = self.__iter__() - for property in iter: - name = _make_name_valid(iter.PropertyLabel) - if name: - property_list.append(name) - return property_list - - def __ConvertArgumentsAndCall(self, *args): - """ Internal function. - Used to call a function on SMProxy. Converts input and - output values as appropriate. - """ - newArgs = [] - for arg in args: - if issubclass(type(arg), Proxy) or isinstance(arg, Proxy): - newArgs.append(arg.SMProxy) - else: - newArgs.append(arg) - func = getattr(self.SMProxy, self.__LastAttrName) - retVal = func(*newArgs) - if type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProxy"): - return _getPyProxy(retVal) - elif type(retVal) is type(self.SMProxy) and retVal.IsA("vtkSMProperty"): - return _wrap_property(self, retVal) - else: - return retVal - - def __GetActiveCamera(self): - """ This method handles GetActiveCamera specially. It adds - an observer to the camera such that everytime it is modified - the render view updated""" - import weakref - c = self.SMProxy.GetActiveCamera() - # VSV: Observers are not supported -## if not c.HasObserver("ModifiedEvent"): -## self.ObserverTag =c.AddObserver("ModifiedEvent", _makeUpdateCameraMethod(weakref.ref(self))) -## self.Observed = c - return c - - def __getattr__(self, name): - """With the exception of a few overloaded methods, - returns the SMProxy method""" - if not self.SMProxy: - raise AttributeError("class %s has no attribute %s" % ("None", name)) - return None - # Handle GetActiveCamera specially. - if name == "GetActiveCamera" and \ - hasattr(self.SMProxy, "GetActiveCamera"): - return self.__GetActiveCamera - if name == "SaveDefinition" and hasattr(self.SMProxy, "SaveDefinition"): - return self.__SaveDefinition - # If not a property, see if SMProxy has the method - try: - proxyAttr = getattr(self.SMProxy, name) - self.__LastAttrName = name - return self.__ConvertArgumentsAndCall - except: - pass - return getattr(self.SMProxy, name) - -class SourceProxy(Proxy): - """Proxy for a source object. This class adds a few methods to Proxy - that are specific to sources. It also provides access to the output - ports. Output ports can be accessed by name or index: - > op = source[0] - or - > op = source['some name']. - """ - def UpdatePipeline(self, time=None): - """This method updates the server-side VTK pipeline and the associated - data information. Make sure to update a source to validate the output - meta-data.""" - if time != None: - self.SMProxy.UpdatePipeline(time) - else: - self.SMProxy.UpdatePipeline() - # This is here to cause a receive - # on the client side so that progress works properly. - if ActiveConnection and ActiveConnection.IsRemote(): - self.SMProxy.GetDataInformation() - - def FileNameChanged(self): - "Called when the filename of a source proxy is changed." - self.UpdatePipelineInformation() - - def UpdatePipelineInformation(self): - """This method updates the meta-data of the server-side VTK pipeline and - the associated information properties""" - self.SMProxy.UpdatePipelineInformation() - - def GetDataInformation(self, idx=None): - """This method returns a DataInformation wrapper around a - vtkPVDataInformation""" - if idx == None: - idx = self.Port - if self.SMProxy: - return DataInformation( \ - self.SMProxy.GetDataInformation(idx), \ - self.SMProxy, idx) - - def __getitem__(self, idx): - """Given a slice, int or string, returns the corresponding - output port""" - if isinstance(idx, slice): - indices = idx.indices(self.SMProxy.GetNumberOfOutputPorts()) - retVal = [] - for i in range(*indices): - retVal.append(OutputPort(self, i)) - return retVal - elif isinstance(idx, int): - if idx >= self.SMProxy.GetNumberOfOutputPorts() or idx < 0: - raise IndexError - return OutputPort(self, idx) - else: - return OutputPort(self, self.SMProxy.GetOutputPortIndex(idx)) - - def GetPointDataInformation(self): - """Returns the associated point data information.""" - self.UpdatePipeline() - return FieldDataInformation(self.SMProxy, self.Port, "PointData") - - def GetCellDataInformation(self): - """Returns the associated cell data information.""" - self.UpdatePipeline() - return FieldDataInformation(self.SMProxy, self.Port, "CellData") - - def GetFieldDataInformation(self): - """Returns the associated cell data information.""" - self.UpdatePipeline() - return FieldDataInformation(self.SMProxy, self.Port, "FieldData") - - PointData = property(GetPointDataInformation, None, None, "Returns point data information") - CellData = property(GetCellDataInformation, None, None, "Returns cell data information") - FieldData = property(GetFieldDataInformation, None, None, "Returns field data information") - - -class ExodusIIReaderProxy(SourceProxy): - """Special class to define convenience functions for array - selection.""" - - def FileNameChanged(self): - "Called when the filename changes. Selects all variables." - SourceProxy.FileNameChanged(self) - self.SelectAllVariables() - - def SelectAllVariables(self): - "Select all available variables for reading." - for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables', - 'ElementVariables', 'GlobalVariables'): - f = getattr(self, prop) - f.SelectAll() - - def DeselectAllVariables(self): - "Deselects all variables." - for prop in ('PointVariables', 'EdgeVariables', 'FaceVariables', - 'ElementVariables', 'GlobalVariables'): - f = getattr(self, prop) - f.DeselectAll() - -class ViewLayoutProxy(Proxy): - """Special class to define convenience methods for View Layout""" - - def SplitViewHorizontal(self, view, fraction=0.5): - """Split the cell containing the specified view horizontally. - If no fraction is specified, the frame is split into equal parts. - On success returns a positve number that identifying the new cell - location that can be used to assign view to, or split further. - Return -1 on failure.""" - location = self.GetViewLocation(view) - if location == -1: - raise RuntimeError, "View is not present in this layout." - if fraction < 0.0 or fraction > 1.0: - raise RuntimeError, "'fraction' must be in the range [0.0, 1.0]" - return self.SMProxy.SplitHorizontal(location, fraction) - - def SplitViewVertical(self, view=None, fraction=0.5): - """Split the cell containing the specified view horizontally. - If no view is specified, active view is used. - If no fraction is specified, the frame is split into equal parts. - On success returns a positve number that identifying the new cell - location that can be used to assign view to, or split further. - Return -1 on failure.""" - location = self.GetViewLocation(view) - if location == -1: - raise RuntimeError, "View is not present in this layout." - if fraction < 0.0 or fraction > 1.0: - raise RuntimeError, "'fraction' must be in the range [0.0, 1.0]" - return self.SMProxy.SplitVertical(location, fraction) - - def AssignView(self, location, view): - """Assign a view at a particular location. Note that the view's position may - be changed by subsequent Split() calls. Returns true on success.""" - viewproxy = None - if isinstance(view, Proxy): - view = view.SMProxy - return self.SMProxy.AssignView(location, view) - - def GetViewLocation(self, view): - if isinstance(view, Proxy): - view = view.SMProxy - return self.SMProxy.GetViewLocation(view) - -class Property(object): - """Generic property object that provides access to one of the properties of - a server object. This class does not allow setting/getting any values but - provides an interface to update a property using __call__. This can be used - for command properties that correspond to function calls without arguments. - For example, - > proxy.Foo() - would push a Foo property which may cause the proxy to call a Foo method - on the actual VTK object. - - For advanced users: - Python wrapper around a vtkSMProperty with a simple interface. - In addition to all method provided by vtkSMProperty (obtained by - forwarding unknown attributes requests to the underlying SMProxy), - Property and sub-class provide a list API. - - Please note that some of the methods accessible through the Property - class are not listed by help() because the Property objects forward - unresolved attributes to the underlying object. To get the full list, - see also dir(proxy.SMProperty). See also the doxygen based documentation - of the vtkSMProperty C++ class. - """ - def __init__(self, proxy, smproperty): - """Default constructor. Stores a reference to the proxy.""" - import weakref - self.SMProperty = smproperty - self.Proxy = proxy - - def __repr__(self): - """Returns a string representation containing property name - and value""" - if not type(self) is Property: - if self.GetData() is not None: - repr = self.GetData().__repr__() - else: - repr = "None" - else: - repr = "Property name= " - name = self.Proxy.GetPropertyName(self.SMProperty) - if name: - repr += name - else: - repr += "Unknown" - - return repr - - def __call__(self): - """Forces a property update using InvokeCommand.""" - if type(self) is Property: - self.Proxy.SMProxy.InvokeCommand(self._FindPropertyName()) - else: - raise RuntimeError, "Cannot invoke this property" - - def _FindPropertyName(self): - "Returns the name of this property." - return self.Proxy.GetPropertyName(self.SMProperty) - - def _UpdateProperty(self): - "Pushes the value of this property to the server." - # For now, we are updating all properties. This is due to an - # issue with the representations. Their VTK objects are not - # created until Input is set therefore, updating a property - # has no effect. Updating all properties everytime one is - # updated has the effect of pushing values set before Input - # when Input is updated. - # self.Proxy.SMProxy.UpdateProperty(self._FindPropertyName()) - self.Proxy.SMProxy.UpdateVTKObjects() - - def __getattr__(self, name): - "Unknown attribute requests get forwarded to SMProperty." - return getattr(self.SMProperty, name) - - Name = property(_FindPropertyName, None, None, - "Returns the name for the property") - -class GenericIterator(object): - """Iterator for container type objects""" - - def __init__(self, obj): - self.Object = obj - self.index = 0 - - def __iter__(self): - return self - - def next(self): - if self.index >= len(self.Object): - raise StopIteration - - idx = self.index - self.index += 1 - return self.Object[idx] - -class VectorProperty(Property): - """A VectorProperty provides access to one or more values. You can use - a slice to get one or more property values: - > val = property[2] - or - > vals = property[0:5:2] - You can use a slice to set one or more property values: - > property[2] = val - or - > property[1:3] = (1,2) - """ - def ConvertValue(self, value): - return value - - def __len__(self): - """Returns the number of elements.""" - return self.SMProperty.GetNumberOfElements() - - def __iter__(self): - """Implementation of the sequence API""" - return GenericIterator(self) - - def __setitem__(self, idx, value): - """Given a list or tuple of values, sets a slice of values [min, max)""" - if isinstance(idx, slice): - indices = idx.indices(len(self)) - for i, j in zip(range(*indices), value): - self.SMProperty.SetElement(i, self.ConvertValue(j)) - self._UpdateProperty() - elif idx >= len(self) or idx < 0: - raise IndexError - else: - self.SMProperty.SetElement(idx, self.ConvertValue(value)) - self._UpdateProperty() - - def GetElement(self, index): - return self.SMProperty.GetElement(index) - - def __getitem__(self, idx): - """Returns the range [min, max) of elements. Raises an IndexError - exception if an argument is out of bounds.""" - ls = len(self) - if isinstance(idx, slice): - indices = idx.indices(ls) - retVal = [] - for i in range(*indices): - retVal.append(self.GetElement(i)) - return retVal - elif idx >= ls: - raise IndexError - elif idx < 0: - idx = ls + idx - if idx < 0: - raise IndexError - - return self.GetElement(idx) - - def GetData(self): - "Returns all elements as either a list or a single value." - property = self.SMProperty - if property.GetRepeatable() or \ - property.GetNumberOfElements() > 1: - return self[0:len(self)] - elif property.GetNumberOfElements() == 1: - return self.GetElement(0) - - def SetData(self, values): - """Allows setting of all values at once. Requires a single value or - a iterable object.""" - if not hasattr(values, "__iter__"): - values = (values,) - if not self.GetRepeatable() and len(values) != self.GetNumberOfElements(): - raise RuntimeError("This property requires %d values." % self.GetNumberOfElements()) - if self.GetRepeatable(): - # Clean up first - self.SMProperty.SetNumberOfElements(0) - idx = 0 - for val in values: - self.SMProperty.SetElement(idx, self.ConvertValue(val)) - idx += 1 - self._UpdateProperty() - - def Clear(self): - "Removes all elements." - self.SMProperty().SetNumberOfElements(0) - self._UpdateProperty() - -class ColorArrayProperty(VectorProperty): - """This subclass of VectorProperty handles setting of the array to - color by. It handles attribute type as well as well array name.""" - - def GetAvailable(self): - """Returns the list of available arrays as (attribute type, array name - tuples.""" - arrays = [] - for a in self.Proxy.Input.PointData: - arrays.append(('POINT_DATA', a.GetName())) - for a in self.Proxy.Input.CellData: - arrays.append(('CELL_DATA', a.GetName())) - return arrays - - def SetData(self, value): - """Overwritten to enable setting attribute type (the ColorAttributeType - property and the array name. The argument should be the array name - (in which case the first appropriate attribute type is picked) or - a tuple of attribute type and array name.""" - if isinstance(value, tuple) and len(value) == 2: - att = value[0] - arr = value[1] - elif isinstance(value, str): - att = None - arr = value - else: - raise ValueError("Expected a tuple of 2 values or a string.") - - if not arr: - self.SMProperty.SetElement(0, '') - self._UpdateProperty() - return - - found = False - for a in self.Available: - if a[1] == arr and (not att or att == a[0]): - att = a[0] - found = True - break - - if not found: - pvoptions = vtkProcessModule.GetProcessModule().GetOptions() - # if this process is from a parallel batch run in symmetric mpi mode - # then we may not have any points or cells on some processes in which - # case we'll probably be missing the point and cell data too. the - # check below makes sure that we avoid this situation. - if pvoptions.GetProcessType() != 0x40 or pvoptions.GetSymmetricMPIMode() == False \ - or len(self.Available) != 0: - raise ValueError("Could not locate array %s in the input." % arr) - - catt = self.Proxy.GetProperty("ColorAttributeType") - if att != None: - catt.SetData(att) - self.SMProperty.SetElement(0, arr) - self._UpdateProperty() - - Available = property(GetAvailable, None, None, \ - "This read-only property returns the list of arrays that can be colored by.") - - -class EnumerationProperty(VectorProperty): - """Subclass of VectorProperty that is applicable for enumeration type - properties.""" - - def GetElement(self, index): - """Returns the text for the given element if available. Returns - the numerical values otherwise.""" - val = self.SMProperty.GetElement(index) - domain = self.SMProperty.GetDomain("enum") - for i in range(domain.GetNumberOfEntries()): - if domain.GetEntryValue(i) == val: - return domain.GetEntryText(i) - return val - - def ConvertValue(self, value): - """Converts value to type suitable for vtSMProperty::SetElement()""" - if type(value) == str: - domain = self.SMProperty.GetDomain("enum") - if domain.HasEntryText(value): - return domain.GetEntryValueForText(value) - else: - raise ValueError("%s is not a valid value." % value) - return VectorProperty.ConvertValue(self, value) - - def GetAvailable(self): - "Returns the list of available values for the property." - retVal = [] - domain = self.SMProperty.GetDomain("enum") - for i in range(domain.GetNumberOfEntries()): - retVal.append(domain.GetEntryText(i)) - return retVal - - Available = property(GetAvailable, None, None, \ - "This read-only property contains the list of values that can be applied to this property.") - - -class FileNameProperty(VectorProperty): - """Property to set/get one or more file names. - This property updates the pipeline information everytime its value changes. - This is used to keep the array lists up to date.""" - - def _UpdateProperty(self): - "Pushes the value of this property to the server." - VectorProperty._UpdateProperty(self) - self.Proxy.FileNameChanged() - -class ArraySelectionProperty(VectorProperty): - "Property to select an array to be processed by a filter." - - def GetAssociation(self): - val = self.GetElement(3) - if val == "": - return None - for key, value in ASSOCIATIONS.iteritems(): - if value == int(val): - return key - - return None - - def GetArrayName(self): - return self.GetElement(4) - - def __len__(self): - """Returns the number of elements.""" - return 2 - - def __setitem__(self, idx, value): - raise RuntimeError, "This property cannot be accessed using __setitem__" - - def __getitem__(self, idx): - """Returns attribute type for index 0, array name for index 1""" - if isinstance(idx, slice): - indices = idx.indices(len(self)) - retVal = [] - for i in range(*indices): - if i >= 2 or i < 0: - raise IndexError - if i == 0: - retVal.append(self.GetAssociation()) - else: - retVal.append(self.GetArrayName()) - return retVal - elif idx >= 2 or idx < 0: - raise IndexError - - if i == 0: - return self.GetAssociation() - else: - return self.GetArrayName() - - def SetData(self, values): - """Allows setting of all values at once. Requires a single value, - a tuple or list.""" - if not isinstance(values, tuple) and \ - not isinstance(values, list): - values = (values,) - if len(values) == 1: - self.SMProperty.SetElement(4, values[0]) - elif len(values) == 2: - if isinstance(values[0], str): - val = str(ASSOCIATIONS[values[0]]) - else: - # In case user didn't specify valid association, - # just pick POINTS. - val = str(ASSOCIATIONS['POINTS']) - self.SMProperty.SetElement(3, str(val)) - self.SMProperty.SetElement(4, values[1]) - else: - raise RuntimeError, "Expected 1 or 2 values." - self._UpdateProperty() - - def UpdateDefault(self): - "Helper method to set default values." - if self.SMProperty.GetNumberOfElements() != 5: - return - if self.GetElement(4) != '' or \ - self.GetElement(3) != '': - return - - for i in range(0,3): - if self.GetElement(i) == '': - self.SMProperty.SetElement(i, '0') - al = self.SMProperty.GetDomain("array_list") - al.Update(self.SMProperty) - al.SetDefaultValues(self.SMProperty) - -class ArrayListProperty(VectorProperty): - """This property provides a simpler interface for selecting arrays. - Simply assign a list of arrays that should be loaded by the reader. - Use the Available property to get a list of available arrays.""" - - def __init__(self, proxy, smproperty): - VectorProperty.__init__(self, proxy, smproperty) - self.__arrays = [] - - def GetAvailable(self): - "Returns the list of available arrays" - dm = self.GetDomain("array_list") - retVal = [] - for i in range(dm.GetNumberOfStrings()): - retVal.append(dm.GetString(i)) - return retVal - - Available = property(GetAvailable, None, None, \ - "This read-only property contains the list of items that can be read by a reader.") - - def SelectAll(self): - "Selects all arrays." - self.SetData(self.Available) - - def DeselectAll(self): - "Deselects all arrays." - self.SetData([]) - - def __iter__(self): - """Implementation of the sequence API""" - return GenericIterator(self) - - def __len__(self): - """Returns the number of elements.""" - return len(self.GetData()) - - def __setitem__(self, idx, value): - """Given a list or tuple of values, sets a slice of values [min, max)""" - self.GetData() - if isinstance(idx, slice): - indices = idx.indices(len(self)) - for i, j in zip(range(*indices), value): - self.__arrays[i] = j - self.SetData(self.__arrays) - elif idx >= len(self) or idx < 0: - raise IndexError - else: - self.__arrays[idx] = self.ConvertValue(value) - self.SetData(self.__arrays) - - def __getitem__(self, idx): - """Returns the range [min, max) of elements. Raises an IndexError - exception if an argument is out of bounds.""" - self.GetData() - if isinstance(idx, slice): - indices = idx.indices(len(self)) - retVal = [] - for i in range(*indices): - retVal.append(self.__arrays[i]) - return retVal - elif idx >= len(self) or idx < 0: - raise IndexError - return self.__arrays[idx] - - def SetData(self, values): - """Allows setting of all values at once. Requires a single value, - a tuple or list.""" - # Clean up first - iup = self.SMProperty.GetImmediateUpdate() - self.SMProperty.SetImmediateUpdate(False) - # Clean up first - self.SMProperty.SetNumberOfElements(0) - if not isinstance(values, tuple) and \ - not isinstance(values, list): - values = (values,) - fullvalues = [] - - # WARNING: - # The order of the two loops below are delibrately set in this way - # so that values passed in will take precedence. - # This is needed for backward compatibility of the - # property ElementBlocks for vtkExodusIIReader. - # If you attemp to change this, please verify that - # python state files for opening old .ex2 file (<=3.14) still works. - for array in self.Available: - if not values.__contains__(array): - fullvalues.append(array) - fullvalues.append('0') - - for i in range(len(values)): - val = self.ConvertValue(values[i]) - fullvalues.append(val) - fullvalues.append('1') - - - i = 0 - for value in fullvalues: - self.SMProperty.SetElement(i, value) - i += 1 - - self._UpdateProperty() - self.SMProperty.SetImmediateUpdate(iup) - - def GetData(self): - "Returns all elements as a list." - property = self.SMProperty - nElems = property.GetNumberOfElements() - if nElems%2 != 0: - raise ValueError, "The SMProperty with XML label '%s' has a size that is not a multiple of 2." % property.GetXMLLabel() - self.__arrays = [] - for i in range(0, nElems, 2): - if self.GetElement(i+1) != '0': - self.__arrays.append(self.GetElement(i)) - return list(self.__arrays) - -class ProxyProperty(Property): - """A ProxyProperty provides access to one or more proxies. You can use - a slice to get one or more property values: - > proxy = property[2] - or - > proxies = property[0:5:2] - You can use a slice to set one or more property values: - > property[2] = proxy - or - > property[1:3] = (proxy1, proxy2) - You can also append and delete: - > property.append(proxy) - and - > del property[1:2] - - You can also remove all elements with Clear(). - - Note that some properties expect only 1 proxy and will complain if - you set the number of values to be something else. - """ - def __init__(self, proxy, smproperty): - """Default constructor. Stores a reference to the proxy. Also looks - at domains to find valid values.""" - Property.__init__(self, proxy, smproperty) - # Check to see if there is a proxy list domain and, if so, - # initialize ourself. (Should this go in ProxyProperty?) - listdomain = self.GetDomain('proxy_list') - if listdomain: - if listdomain.GetClassName() != 'vtkSMProxyListDomain': - raise ValueError, "Found a 'proxy_list' domain on an InputProperty that is not a ProxyListDomain." - pm = ProxyManager() - group = "pq_helper_proxies." + proxy.GetGlobalIDAsString() - if listdomain.GetNumberOfProxies() == 0: - for i in xrange(listdomain.GetNumberOfProxyTypes()): - igroup = listdomain.GetProxyGroup(i) - name = listdomain.GetProxyName(i) - iproxy = CreateProxy(igroup, name) - listdomain.AddProxy(iproxy) - pm.RegisterProxy(group, proxy.GetPropertyName(smproperty), iproxy) - listdomain.SetDefaultValues(self.SMProperty) - - def GetAvailable(self): - """If this proxy has a list domain, then this function returns the - strings you can use to select from the domain. If there is no such - list domain, the returned list is empty.""" - listdomain = self.GetDomain('proxy_list') - retval = [] - if listdomain: - for i in xrange(listdomain.GetNumberOfProxies()): - proxy = listdomain.GetProxy(i) - retval.append(proxy.GetXMLLabel()) - return retval - - Available = property(GetAvailable, None, None, - """This read only property is a list of strings you can - use to select from the list domain. If there is no - such list domain, the array is empty.""") - - def __iter__(self): - """Implementation of the sequence API""" - return GenericIterator(self) - - def __len__(self): - """Returns the number of elements.""" - return self.SMProperty.GetNumberOfProxies() - - def remove(self, proxy): - """Removes the first occurence of the proxy from the property.""" - self.SMProperty.RemoveProxy(proxy.SMProxy) - self._UpdateProperty() - - def __setitem__(self, idx, value): - """Given a list or tuple of values, sets a slice of values [min, max)""" - if isinstance(idx, slice): - indices = idx.indices(len(self)) - for i, j in zip(range(*indices), value): - self.SMProperty.SetProxy(i, j.SMProxy) - self._UpdateProperty() - elif idx >= len(self) or idx < 0: - raise IndexError - else: - self.SMProperty.SetProxy(idx, value.SMProxy) - self._UpdateProperty() - - def __delitem__(self,idx): - """Removes the element idx""" - if isinstance(idx, slice): - indices = idx.indices(len(self)) - # Collect the elements to delete to a new list first. - # Otherwise indices are screwed up during the actual - # remove loop. - toremove = [] - for i in range(*indices): - toremove.append(self[i]) - for i in toremove: - self.SMProperty.RemoveProxy(i.SMProxy) - self._UpdateProperty() - elif idx >= len(self) or idx < 0: - raise IndexError - else: - self.SMProperty.RemoveProxy(self[idx].SMProxy) - self._UpdateProperty() - - def __getitem__(self, idx): - """Returns the range [min, max) of elements. Raises an IndexError - exception if an argument is out of bounds.""" - if isinstance(idx, slice): - indices = idx.indices(len(self)) - retVal = [] - for i in range(*indices): - retVal.append(_getPyProxy(self.SMProperty.GetProxy(i))) - return retVal - elif idx >= len(self) or idx < 0: - raise IndexError - return _getPyProxy(self.SMProperty.GetProxy(idx)) - - def __getattr__(self, name): - "Unknown attribute requests get forwarded to SMProperty." - return getattr(self.SMProperty, name) - - def index(self, proxy): - idx = 0 - for px in self: - ## VSV: == - if proxy.IsSame(px): - return idx - idx += 1 - raise ValueError("proxy is not in the list.") - - def append(self, proxy): - "Appends the given proxy to the property values." - self.SMProperty.AddProxy(proxy.SMProxy) - self._UpdateProperty() - - def GetData(self): - "Returns all elements as either a list or a single value." - property = self.SMProperty - if property.GetRepeatable() or property.GetNumberOfProxies() > 1: - return self[0:len(self)] - else: - if property.GetNumberOfProxies() > 0: - return _getPyProxy(property.GetProxy(0)) - return None - - def SetData(self, values): - """Allows setting of all values at once. Requires a single value, - a tuple or list.""" - if isinstance(values, str): - position = -1 - try: - position = self.Available.index(values) - except: - raise ValueError, values + " is not a valid object in the domain." - values = self.GetDomain('proxy_list').GetProxy(position) - if not isinstance(values, tuple) and \ - not isinstance(values, list): - values = (values,) - self.SMProperty.RemoveAllProxies() - for value in values: - if isinstance(value, Proxy): - value_proxy = value.SMProxy - else: - value_proxy = value - self.SMProperty.AddProxy(value_proxy) - self._UpdateProperty() - - def Clear(self): - "Removes all elements." - self.SMProperty.RemoveAllProxies() - self._UpdateProperty() - -class InputProperty(ProxyProperty): - """An InputProperty allows making pipeline connections. You can set either - a source proxy or an OutputProperty to an input property: - - > property[0] = proxy - or - > property[0] = OuputPort(proxy, 1) - - > property.append(proxy) - or - > property.append(OutputPort(proxy, 0)) - """ - def __setitem__(self, idx, value): - """Given a list or tuple of values, sets a slice of values [min, max)""" - if isinstance(idx, slice): - indices = idx.indices(len(self)) - for i, j in zip(range(*indices), value): - op = value[i-min] - self.SMProperty.SetInputConnection(i, op.SMProxy, op.Port) - self._UpdateProperty() - elif idx >= len(self) or idx < 0: - raise IndexError - else: - self.SMProperty.SetInputConnection(idx, value.SMProxy, value.Port) - self._UpdateProperty() - - def __getitem__(self, idx): - """Returns the range [min, max) of elements. Raises an IndexError - exception if an argument is out of bounds.""" - if isinstance(idx, slice): - indices = idx.indices(len(self)) - retVal = [] - for i in range(*indices): - port = None - if self.SMProperty.GetProxy(i): - port = OutputPort(_getPyProxy(self.SMProperty.GetProxy(i)),\ - self.SMProperty.GetOutputPortForConnection(i)) - retVal.append(port) - return retVal - elif idx >= len(self) or idx < 0: - raise IndexError - return OutputPort(_getPyProxy(self.SMProperty.GetProxy(idx)),\ - self.SMProperty.GetOutputPortForConnection(idx)) - - def append(self, value): - """Appends the given proxy to the property values. - Accepts Proxy or OutputPort objects.""" - self.SMProperty.AddInputConnection(value.SMProxy, value.Port) - self._UpdateProperty() - - def GetData(self): - """Returns all elements as either a list of OutputPort objects or - a single OutputPort object.""" - property = self.SMProperty - if property.GetRepeatable() or property.GetNumberOfProxies() > 1: - return self[0:len(self)] - else: - if property.GetNumberOfProxies() > 0: - return OutputPort(_getPyProxy(property.GetProxy(0)),\ - self.SMProperty.GetOutputPortForConnection(0)) - return None - - def SetData(self, values): - """Allows setting of all values at once. Requires a single value, - a tuple or list. Accepts Proxy or OutputPort objects.""" - if isinstance(values, str): - ProxyProperty.SetData(self, values) - return - if not isinstance(values, tuple) and \ - not isinstance(values, list): - values = (values,) - self.SMProperty.RemoveAllProxies() - for value in values: - if value: - self.SMProperty.AddInputConnection(value.SMProxy, value.Port) - self._UpdateProperty() - - def _UpdateProperty(self): - "Pushes the value of this property to the server." - ProxyProperty._UpdateProperty(self) - iter = PropertyIterator(self.Proxy) - for prop in iter: - if isinstance(prop, ArraySelectionProperty): - prop.UpdateDefault() - - -class DataInformation(object): - """DataInformation is a contained for meta-data associated with an - output data. - - DataInformation is a python wrapper around a vtkPVDataInformation. - In addition to proving all methods of a vtkPVDataInformation, it provides - a few convenience methods. - - Please note that some of the methods accessible through the DataInformation - class are not listed by help() because the DataInformation objects forward - unresolved attributes to the underlying object. To get the full list, - see also dir(proxy.DataInformation). - See also the doxygen based documentation of the vtkPVDataInformation C++ - class. - """ - def __init__(self, dataInformation, proxy, idx): - """Default constructor. Requires a vtkPVDataInformation, a source proxy - and an output port id.""" - self.DataInformation = dataInformation - self.Proxy = proxy - self.Idx = idx - - def Update(self): - """****Deprecated**** There is no reason anymore to use this method - explicitly, it is called automatically when one gets any value from the - data information object. - Update the data information if necessary. Note that this - does not cause execution of the underlying object. In certain - cases, you may have to call UpdatePipeline() on the proxy.""" - if self.Proxy: - self.Proxy.GetDataInformation(self.Idx) - - def GetDataSetType(self): - """Returns the dataset type as defined in vtkDataObjectTypes.""" - self.Update() - if not self.DataInformation: - raise RuntimeError, "No data information is available" - if self.DataInformation.GetCompositeDataSetType() > -1: - return self.DataInformation.GetCompositeDataSetType() - return self.DataInformation.GetDataSetType() - - def GetDataSetTypeAsString(self): - """Returns the dataset type as a user-friendly string. This is - not the same as the enumaration used by VTK""" - return vtk.vtkDataObjectTypes.GetClassNameFromTypeId(self.GetDataSetType()) - - def __getattr__(self, name): - """Forwards unknown attribute requests to the underlying - vtkPVInformation.""" - if not self.DataInformation: - raise AttributeError("class has no attribute %s" % name) - return None - self.Update() - return getattr(self.DataInformation, name) - -class ArrayInformation(object): - """Meta-information associated with an array. Use the Name - attribute to get the array name. - - Please note that some of the methods accessible through the ArrayInformation - class are not listed by help() because the ArrayInformation objects forward - unresolved attributes to the underlying object. - See the doxygen based documentation of the vtkPVArrayInformation C++ - class for a full list. - """ - def __init__(self, proxy, field, name): - self.Proxy = proxy - self.FieldData = field - self.Name = name - - def __getattr__(self, name): - """Forward unknown methods to vtkPVArrayInformation""" - array = self.FieldData.GetFieldData().GetArrayInformation(self.Name) - if not array: return None - return getattr(array, name) - - def __repr__(self): - """Returns a user-friendly representation string.""" - return "Array: " + self.Name - - def GetRange(self, component=0): - """Given a component, returns its value range as a tuple of 2 values.""" - array = self.FieldData.GetFieldData().GetArrayInformation(self.Name) - range = array.GetComponentRange(component) - return (range[0], range[1]) - -class FieldDataInformationIterator(object): - """Iterator for FieldDataInformation""" - - def __init__(self, info, items=False): - self.FieldDataInformation = info - self.index = 0 - self.items = items - - def __iter__(self): - return self - - def next(self): - if self.index >= self.FieldDataInformation.GetNumberOfArrays(): - raise StopIteration - - self.index += 1 - ai = self.FieldDataInformation[self.index-1] - if self.items: - return (ai.GetName(), ai) - else: - return ai - - -class FieldDataInformation(object): - """Meta-data for a field of an output object (point data, cell data etc...). - Provides easy access to the arrays using the slice interface: - > narrays = len(field_info) - > for i in range(narrays): - > array_info = field_info[i] - - Full slice interface is supported: - > arrays = field_info[0:5:3] - where arrays is a list. - - Array access by name is also possible: - > array_info = field_info['Temperature'] - - The number of arrays can also be accessed using the NumberOfArrays - property. - """ - def __init__(self, proxy, idx, field): - self.Proxy = proxy - self.OutputPort = idx - self.FieldData = field - - def GetFieldData(self): - """Convenience method to get the underlying - vtkPVDataSetAttributesInformation""" - return getattr(self.Proxy.GetDataInformation(self.OutputPort), "Get%sInformation" % self.FieldData)() - - def GetNumberOfArrays(self): - """Returns the number of arrays.""" - self.Proxy.UpdatePipeline() - return self.GetFieldData().GetNumberOfArrays() - - def GetArray(self, idx): - """Given an index or a string, returns an array information. - Raises IndexError if the index is out of bounds.""" - self.Proxy.UpdatePipeline() - if not self.GetFieldData().GetArrayInformation(idx): - return None - if isinstance(idx, str): - return ArrayInformation(self.Proxy, self, idx) - elif idx >= len(self) or idx < 0: - raise IndexError - return ArrayInformation(self.Proxy, self, self.GetFieldData().GetArrayInformation(idx).GetName()) - - def __len__(self): - """Returns the number of arrays.""" - return self.GetNumberOfArrays() - - def __getitem__(self, idx): - """Implements the [] operator. Accepts an array name.""" - if isinstance(idx, slice): - indices = idx.indices(self.GetNumberOfArrays()) - retVal = [] - for i in range(*indices): - retVal.append(self.GetArray(i)) - return retVal - return self.GetArray(idx) - - def keys(self): - """Implementation of the dictionary API""" - kys = [] - narrays = self.GetNumberOfArrays() - for i in range(narrays): - kys.append(self.GetArray(i).GetName()) - return kys - - def values(self): - """Implementation of the dictionary API""" - vals = [] - narrays = self.GetNumberOfArrays() - for i in range(narrays): - vals.append(self.GetArray(i)) - return vals - - def iteritems(self): - """Implementation of the dictionary API""" - return FieldDataInformationIterator(self, True) - - def items(self): - """Implementation of the dictionary API""" - itms = [] - narrays = self.GetNumberOfArrays() - for i in range(narrays): - ai = self.GetArray(i) - itms.append((ai.GetName(), ai)) - return itms - - def has_key(self, key): - """Implementation of the dictionary API""" - if self.GetArray(key): - return True - return False - - def __iter__(self): - """Implementation of the dictionary API""" - return FieldDataInformationIterator(self) - - def __getattr__(self, name): - """Forwards unknown attributes to the underlying - vtkPVDataSetAttributesInformation""" - array = self.GetArray(name) - if array: return array - raise AttributeError("class has no attribute %s" % name) - return None - - NumberOfArrays = property(GetNumberOfArrays, None, None, "Returns the number of arrays.") - -def OutputPort(proxy, outputPort=0): - if not Proxy: - return None - if isinstance(outputPort, str): - outputPort = proxy.GetOutputPortIndex(outputPort) - if outputPort >= proxy.GetNumberOfOutputPorts(): - return None - if proxy.Port == outputPort: - return proxy - newinstance = _getPyProxy(proxy.SMProxy, outputPort) - newinstance.Port = outputPort - newinstance._Proxy__Properties = proxy._Proxy__Properties - return newinstance - -class ProxyManager(object): - """When running scripts from the python shell in the ParaView application, - registering proxies with the proxy manager is the only mechanism to - notify the graphical user interface (GUI) that a proxy - exists. Therefore, unless a proxy is registered, it will not show up in - the user interface. Also, the proxy manager is the only way to get - access to proxies created using the GUI. Proxies created using the GUI - are automatically registered under an appropriate group (sources, - filters, representations and views). To get access to these objects, - you can use proxyManager.GetProxy(group, name). The name is the same - as the name shown in the pipeline browser. - - This class is a python wrapper for vtkSMProxyManager. Note that the - underlying vtkSMProxyManager is a singleton. All instances of this - class will refer to the same object. In addition to all methods provided by - vtkSMProxyManager (all unknown attribute requests are forwarded - to the vtkSMProxyManager), this class provides several convenience - methods. - - Please note that some of the methods accessible through the ProxyManager - class are not listed by help() because the ProxyManager objects forwards - unresolved attributes to the underlying object. To get the full list, - see also dir(proxy.SMProxyManager). See also the doxygen based documentation - of the vtkSMProxyManager C++ class. - """ - - def __init__(self, session=None): - """Constructor. Assigned self.SMProxyManager to - vtkSMProxyManager.GetProxyManager().""" - global ActiveConnection - if not session: - session = ActiveConnection.Session - self.SMProxyManager = session.GetSessionProxyManager() - - def RegisterProxy(self, group, name, aProxy): - """Registers a proxy (either SMProxy or proxy) with the - server manager""" - if isinstance(aProxy, Proxy): - self.SMProxyManager.RegisterProxy(group, name, aProxy.SMProxy) - else: - self.SMProxyManager.RegisterProxy(group, name, aProxy) - - def NewProxy(self, group, name): - """Creates a new proxy of given group and name and returns an SMProxy. - Note that this is a server manager object. You should normally create - proxies using the class objects. For example: - obj = servermanager.sources.SphereSource()""" - if not self.SMProxyManager: - return None - aProxy = self.SMProxyManager.NewProxy(group, name, "NULL") - if not aProxy: - return None - aProxy.UnRegister(None) - return aProxy - - def GetProxy(self, group, name): - """Returns a Proxy registered under a group and name""" - if not self.SMProxyManager: - return None - aProxy = self.SMProxyManager.GetProxy(group, name) - if not aProxy: - return None - return _getPyProxy(aProxy) - - def GetPrototypeProxy(self, group, name): - """Returns a prototype proxy given a group and name. This is an - SMProxy. This is a low-level method. You should not normally - have to call it.""" - if not self.SMProxyManager: - return None - aProxy = self.SMProxyManager.GetPrototypeProxy(group, name) - if not aProxy: - return None - return aProxy - - def GetProxiesInGroup(self, groupname): - """Returns a map of proxies in a particular group.""" - proxies = {} - iter = self.NewGroupIterator(groupname) - for aProxy in iter: - proxies[(iter.GetKey(), aProxy.GetGlobalIDAsString())] = aProxy - return proxies - - def UnRegisterProxy(self, groupname, proxyname, aProxy): - """Unregisters a proxy.""" - if not self.SMProxyManager: - return - if aProxy != None and isinstance(aProxy,Proxy): - aProxy = aProxy.SMProxy - if aProxy: - self.SMProxyManager.UnRegisterProxy(groupname, proxyname, aProxy) - - def GetProxies(self, groupname, proxyname): - """Returns all proxies registered under the given group with the - given name. Note that it is possible to register more than one - proxy with the same name in the same group. Because the proxies - are different, there is no conflict. Use this method instead of - GetProxy() if you know that there are more than one proxy registered - with this name.""" - if not self.SMProxyManager: - return [] - collection = vtk.vtkCollection() - result = [] - self.SMProxyManager.GetProxies(groupname, proxyname, collection) - for i in range(0, collection.GetNumberOfItems()): - aProxy = _getPyProxy(collection.GetItemAsObject(i)) - if aProxy: - result.append(aProxy) - - return result - - def __iter__(self): - """Returns a new ProxyIterator.""" - iter = ProxyIterator() - iter.Begin() - return iter - - def NewGroupIterator(self, group_name): - """Returns a ProxyIterator for a group. The resulting object - can be used to traverse the proxies that are in the given - group.""" - iter = self.__iter__() - iter.SetModeToOneGroup() - iter.Begin(group_name) - return iter - - def NewDefinitionIterator(self, groupname=None): - """Returns an iterator that can be used to iterate over - all groups and types of proxies that the proxy manager - can create.""" - iter = None - if groupname != None: - iter = ProxyDefinitionIterator(self.GetProxyDefinitionManager().NewSingleGroupIterator(groupname,0)) - else: - iter = ProxyDefinitionIterator(self.GetProxyDefinitionManager().NewIterator(0)) - - return iter - - def __ConvertArgumentsAndCall(self, *args): - newArgs = [] - for arg in args: - if issubclass(type(arg), Proxy) or isinstance(arg, Proxy): - newArgs.append(arg.SMProxy) - else: - newArgs.append(arg) - func = getattr(self.SMProxyManager, self.__LastAttrName) - retVal = func(*newArgs) - if type(retVal) is type(self.SMProxyManager) and retVal.IsA("vtkSMProxy"): - return _getPyProxy(retVal) - else: - return retVal - - def __getattr__(self, name): - """Returns attribute from the ProxyManager""" - try: - pmAttr = getattr(self.SMProxyManager, name) - self.__LastAttrName = name - return self.__ConvertArgumentsAndCall - except: - pass - return getattr(self.SMProxyManager, name) - - def LoadState(self, filename, loader = None): - self.SMProxyManager.LoadXMLState(filename, loader) - - def SaveState(self, filename): - self.SMProxyManager.SaveXMLState(filename) - -class PropertyIterator(object): - """Wrapper for a vtkSMPropertyIterator class to satisfy - the python iterator protocol. Note that the list of - properties can also be obtained from the class object's - dictionary. - See the doxygen documentation for vtkSMPropertyIterator C++ - class for details. - """ - - def __init__(self, aProxy): - self.SMIterator = aProxy.NewPropertyIterator() - if self.SMIterator: - self.SMIterator.UnRegister(None) - self.SMIterator.Begin() - self.Key = None - self.PropertyLabel = None - self.Proxy = aProxy - - def __iter__(self): - return self - - def next(self): - if not self.SMIterator: - raise StopIteration - - if self.SMIterator.IsAtEnd(): - self.Key = None - raise StopIteration - self.Key = self.SMIterator.GetKey() - self.PropertyLabel = self.SMIterator.GetPropertyLabel() - self.SMIterator.Next() - return self.Proxy.GetProperty(self.Key) - - def GetProxy(self): - """Returns the proxy for the property last returned by the call to - 'next()'""" - return self.Proxy - - def GetKey(self): - """Returns the key for the property last returned by the call to - 'next()' """ - return self.Key - - def GetProperty(self): - """Returns the property last returned by the call to 'next()' """ - return self.Proxy.GetProperty(self.Key) - - def __getattr__(self, name): - """returns attributes from the vtkSMPropertyIterator.""" - return getattr(self.SMIterator, name) - -class ProxyDefinitionIterator(object): - """Wrapper for a vtkPVProxyDefinitionIterator class to satisfy - the python iterator protocol. - See the doxygen documentation of the vtkPVProxyDefinitionIterator - C++ class for more information.""" - def __init__(self, iter): - self.SMIterator = iter - if self.SMIterator: - self.SMIterator.UnRegister(None) - self.SMIterator.InitTraversal() - self.Group = None - self.Key = None - - def __iter__(self): - return self - - def next(self): - if self.SMIterator.IsDoneWithTraversal(): - self.Group = None - self.Key = None - raise StopIteration - self.Group = self.SMIterator.GetGroupName() - self.Key = self.SMIterator.GetProxyName() - self.SMIterator.GoToNextItem() - return {"group": self.Group, "key":self.Key } - - def GetProxyName(self): - """Returns the key for the proxy definition last returned by the call - to 'next()' """ - return self.Key - - def GetGroup(self): - """Returns the group for the proxy definition last returned by the - call to 'next()' """ - return self.Group - - def __getattr__(self, name): - """returns attributes from the vtkPVProxyDefinitionIterator.""" - return getattr(self.SMIterator, name) - - -class ProxyIterator(object): - """Wrapper for a vtkSMProxyIterator class to satisfy the - python iterator protocol. - See the doxygen documentation of vtkSMProxyIterator C++ class for - more information. - """ - def __init__(self): - self.SMIterator = vtkSMProxyIterator() - self.SMIterator.SetSession(ActiveConnection.Session) - self.SMIterator.Begin() - self.AProxy = None - self.Group = None - self.Key = None - - def __iter__(self): - return self - - def next(self): - if self.SMIterator.IsAtEnd(): - self.AProxy = None - self.Group = None - self.Key = None - raise StopIteration - return None - self.AProxy = _getPyProxy(self.SMIterator.GetProxy()) - self.Group = self.SMIterator.GetGroup() - self.Key = self.SMIterator.GetKey() - self.SMIterator.Next() - return self.AProxy - - def GetProxy(self): - """Returns the proxy last returned by the call to 'next()'""" - return self.AProxy - - def GetKey(self): - """Returns the key for the proxy last returned by the call to - 'next()' """ - return self.Key - - def GetGroup(self): - """Returns the group for the proxy last returned by the call to - 'next()' """ - return self.Group - - def __getattr__(self, name): - """returns attributes from the vtkSMProxyIterator.""" - return getattr(self.SMIterator, name) - -# Caution: Observers must be global methods otherwise we run into memory -# leak when the interpreter get reset from the C++ layer. -def _update_definitions(caller, event): - updateModules(ActiveConnection.Modules) - -class Connection(object): - """ - This is a python representation for a session/connection. - """ - def __init__(self, connectionId, session): - """Default constructor. Creates a Connection with the given - ID, all other data members initialized to None.""" - global MultiServerConnections - global ActiveConnection - self.ID = connectionId - self.Session = session - self.Modules = PVModule() - self.Alive = True - self.DefinitionObserverTag = 0 - self.CustomDefinitionObserverTag = 0 - if MultiServerConnections == None and ActiveConnection: - raise RuntimeError, "Concurrent connections not supported!" - if MultiServerConnections != None and not self in MultiServerConnections: - MultiServerConnections.append(self) - ActiveConnection = self - __InitAfterConnect__(self) - __exposeActiveModules__() - - def __eq__(self, other): - "Returns true if the connection ids are the same." - return (self.ID == other.ID) - - def __repr__(self): - """User friendly string representation""" - return "Connection (%s) [%d]" % (self.Session.GetURI(), self.ID) - - def GetURI(self): - """Get URI of the connection""" - return self.Session.GetURI() - - def IsRemote(self): - """Returns True if the connection to a remote server, False if - it is local (built-in)""" - if self.Session.IsA("vtkSMSessionClient"): - return True - return False - - def GetNumberOfDataPartitions(self): - """Returns the number of partitions on the data server for this - connection""" - return self.Session.GetServerInformation().GetNumberOfProcesses() - - def AttachDefinitionUpdater(self): - """Attach observer to automatically update modules when needed.""" - # VTN: Observers are not supported - # ProxyDefinitionsUpdated = 2000 -## self.DefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2000, _update_definitions) - # CompoundProxyDefinitionsUpdated = 2001 -## self.CustomDefinitionObserverTag = self.Session.GetProxyDefinitionManager().AddObserver(2001, _update_definitions) - pass - - def close(self): - if self.DefinitionObserverTag: - self.Session.GetProxyDefinitionManager().RemoveObserver(self.DefinitionObserverTag) - self.Session.GetProxyDefinitionManager().RemoveObserver(self.CustomDefinitionObserverTag) - self.Session = None - self.Modules = None - self.Alive = False - - def __del__(self): - if self.Alive: - self.close() - -def SaveState(filename): - """Given a state filename, saves the state of objects registered - with the proxy manager.""" - pm = ProxyManager() - pm.SaveState(filename) - -def LoadState(filename, connection=None): - """Given a state filename and an optional connection, loads the server - manager state.""" - if not connection: - connection = ActiveConnection - if not connection: - raise RuntimeError, "Cannot load state without a connection" - pm = ProxyManager() - pm.LoadState(filename, None) - views = GetRenderViews() - for view in views: - # Make sure that the client window size matches the - # ViewSize property. In paraview, the GUI takes care - # of this. - if view.GetClassName() == "vtkSMIceTDesktopRenderViewProxy": - view.GetRenderWindow().SetSize(view.ViewSize[0], \ - view.ViewSize[1]) - -def InitFromGUI(): - """ - Method used to initialize the Python Shell from the ParaView GUI. - """ - global fromGUI, ActiveConnection - if not fromGUI: - print "from paraview.simple import *" - fromGUI = True - # ToggleProgressPrinting() ### FIXME COLLABORATION - enableMultiServer(vtkProcessModule.GetProcessModule().GetMultipleSessionsSupport()) - iter = vtkProcessModule.GetProcessModule().NewSessionIterator(); - iter.InitTraversal() - ActiveConnection = None - activeSession = vtkSMProxyManager.GetProxyManager().GetActiveSession() - tmpActiveConnection = None - while not iter.IsDoneWithTraversal(): - c = Connection(iter.GetCurrentSessionId(), iter.GetCurrentSession()) - if c.Session == activeSession: - tmpActiveConnection = c - iter.GoToNextItem() - iter.UnRegister(None) - if tmpActiveConnection: - ActiveConnection = tmpActiveConnection - -def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=22221): - """ - Use this function call to create a new session. On success, - it returns a vtkSMSession object that abstracts the connection. - Otherwise, it returns None. - There are several ways in which this function can be called: - * When called with no arguments, it creates a new session - to the built-in server on the client itself. - * When called with ds_host and ds_port arguments, it - attempts to connect to a server(data and render server on the same server) - on the indicated host:port. - * When called with ds_host, ds_port, rs_host, rs_port, it - creates a new connection to the data server on ds_host:ds_port and to the - render server on rs_host: rs_port. - """ - if ds_host == None: - session = vtkSMSession() - elif rs_host == None: - session = vtkSMSessionClient() - session.Connect("cs://%s:%d" % (ds_host, ds_port)) - else: - session = vtkSMSessionClient() - session.Connect("cdsrs://%s:%d/%s:%d" % (ds_host, ds_port, rs_host, rs_port)) - id = vtkProcessModule.GetProcessModule().RegisterSession(session) - connection = Connection(id, session) - return connection - -def ReverseConnect(port=11111): - """ - Use this function call to create a new session. On success, - it returns a Session object that abstracts the connection. - Otherwise, it returns None. - In reverse connection mode, the client waits for a connection - from the server (client has to be started first). The server - then connects to the client (run pvserver with -rc and -ch - option). - The optional port specified the port to listen to. - """ - session = vtkSMSessionClient() - session.Connect("csrc://hostname:" + port) - id = vtkProcessModule.GetProcessModule().RegisterSession(session) - connection = Connection(id, session) - return connection - -def Disconnect(session=None): - """Disconnects the connection. Make sure to clear the proxy manager - first.""" - global ActiveConnection - global MultiServerConnections - global fromGUI - if fromGUI: - # Let the UI know that we want to disconnect - ActiveConnection.Session.InvokeEvent('ExitEvent') - return - if ActiveConnection and (not session or session == ActiveConnection.Session): - session = ActiveConnection.Session - if MultiServerConnections: - MultiServerConnections.remove(ActiveConnection) - ActiveConnection.close() - ActiveConnection = None - switchActiveConnection() - else: - ActiveConnection.close() - ActiveConnection = None - elif MultiServerConnections: - for connection in MultiServerConnections: - if connection.Session == session: - connection.close() - MultiServerConnections.remove(connection) - if session: - vtkProcessModule.GetProcessModule().UnRegisterSession(session) - return - -def CreateProxy(xml_group, xml_name, session=None): - """Creates a proxy. If session is set, the proxy's session is - set accordingly. If session is None, the current Session is used, if - present. You should not have to use method normally. Instantiate the - appropriate class from the appropriate module, for example: - sph = servermanager.sources.SphereSource()""" - global ActiveConnection - if not session: - session = ActiveConnection.Session - if not session: - raise RuntimeError, "Cannot create objects without a session." - pxm = ProxyManager(session) - return pxm.NewProxy(xml_group, xml_name) - -def GetRenderView(connection=None): - """Return the render view in use. If more than one render view is in - use, return the first one.""" - - render_module = None - for aProxy in ProxyManager(): - if aProxy.IsA("vtkSMRenderViewProxy"): - render_module = aProxy - break - return render_module - -def GetRenderViews(connection=None): - """Returns the set of all render views.""" - render_modules = [] - for aProxy in ProxyManager(): - if aProxy.IsA("vtkSMRenderViewProxy"): - render_modules.append(aProxy) - return render_modules - -def GetContextViews(connection=None): - """Returns the set of all context views.""" - context_modules = [] - for aProxy in ProxyManager(): - if aProxy.IsA("vtkSMContextViewProxy"): - context_modules.append(aProxy) - return context_modules - -def CreateRenderView(session=None, **extraArgs): - """Creates a render window on the particular session. If session - is not specified, then the active session is used, if available. - - This method can also be used to initialize properties by passing - keyword arguments where the key is the name of the property. In addition - registrationGroup and registrationName (optional) can be specified (as - keyword arguments) to automatically register the proxy with the proxy - manager.""" - return _create_view("RenderView", session, **extraArgs) - -def _create_view(view_xml_name, session=None, **extraArgs): - """Creates a view on the particular session. If session - is not specified, then the active session is used, if available. - This method can also be used to initialize properties by passing - keyword arguments where the key is the name of the property.""" - if not session: - session = ActiveConnection.Session - if not session: - raise RuntimeError, "Cannot create view without session." - pxm = ProxyManager() - view_module = None - if view_xml_name: - view_module = CreateProxy("views", view_xml_name, session) - if not view_module: - return None - extraArgs['proxy'] = view_module - python_proxy_name = _make_name_valid(view_module.GetXMLName()) - proxy = rendering.__dict__[python_proxy_name](**extraArgs) - return proxy - -def GetRepresentation(aProxy, view): - for rep in view.Representations: - #VSV: == - try: isRep = rep.Input.IsSame(aProxy) - except: isRep = False - if isRep: return rep - return None - -def CreateRepresentation(aProxy, view, **extraArgs): - """Creates a representation for the proxy and adds it to the render - module. - - This method can also be used to initialize properties by passing - keyword arguments where the key is the name of the property.In addition - registrationGroup and registrationName (optional) can be specified (as - keyword arguments) to automatically register the proxy with the proxy - manager. - - This method tries to create the best possible representation for the given - proxy in the given view. Additionally, the user can specify proxyName - (optional) to create a representation of a particular type.""" - - global rendering - if not aProxy: - raise RuntimeError, "proxy argument cannot be None." - if not view: - raise RuntimeError, "view argument cannot be None." - if "proxyName" in extraArgs: - display = CreateProxy("representations", extraArgs['proxyName'], None) - del extraArgs['proxyName'] - else: - display = view.SMProxy.CreateDefaultRepresentation(aProxy.SMProxy, 0) - if display: - display.UnRegister(None) - if not display: - return None - extraArgs['proxy'] = display - proxy = rendering.__dict__[display.GetXMLName()](**extraArgs) - proxy.Input = aProxy - proxy.UpdateVTKObjects() - view.Representations.append(proxy) - return proxy - -class _ModuleLoader(object): - def find_module(self, fullname, path=None): - if vtkPVPythonModule.HasModule(fullname): - return self - else: - return None - def load_module(self, fullname): - import imp - moduleInfo = vtkPVPythonModule.GetModule(fullname) - if not moduleInfo: - raise ImportError - module = sys.modules.setdefault(fullname, imp.new_module(fullname)) - module.__file__ = "<%s>" % moduleInfo.GetFullName() - module.__loader__ = self - if moduleInfo.GetIsPackage: - module.__path__ = moduleInfo.GetFullName() - code = compile(moduleInfo.GetSource(), module.__file__, 'exec') - exec code in module.__dict__ - return module - -def LoadXML(xmlstring): - """DEPRECATED. Given a server manager XML as a string, parse and process it.""" - raise RuntimeError, "Deprecated. Use LoadPlugin(...) instead." - - -def LoadPlugin(filename, remote=True, connection=None): - """ Given a filename and a session (optional, otherwise uses - ActiveConnection), loads a plugin. It then updates the sources, - filters and rendering modules.""" - - if not connection: - connection = ActiveConnection - if not connection: - raise RuntimeError, "Cannot load a plugin without a connection." - plm = vtkSMProxyManager.GetProxyManager().GetPluginManager() - - if remote: - status = plm.LoadRemotePlugin(filename, connection.Session) - else: - status = plm.LoadLocalPlugin(filename) - - # shouldn't the extension check happend before attempting to load the plugin? - if not status: - raise RuntimeError, "Problem loading plugin %s" % (filename) - else: - # we should never have to call this. The modules should update automatically. - updateModules(connection.Modules) - - -def Fetch(input, arg1=None, arg2=None, idx=0): - """ - A convenience method that moves data from the server to the client, - optionally performing some operation on the data as it moves. - The input argument is the name of the (proxy for a) source or filter - whose output is needed on the client. - - You can use Fetch to do three things: - - If arg1 is None (the default) then all of the data is brought to the client. - In parallel runs an appropriate append Filter merges the - data on each processor into one data object. The filter chosen will be - vtkAppendPolyData for vtkPolyData, vtkAppendRectilinearGrid for - vtkRectilinearGrid, vtkMultiBlockDataGroupFilter for vtkCompositeData, - and vtkAppendFilter for anything else. - - If arg1 is an integer then one particular processor's output is brought to - the client. In serial runs the arg is ignored. If you have a filter that - computes results in parallel and brings them to the root node, then set - arg to be 0. - - If arg1 and arg2 are a algorithms, for example vtkMinMax, the algorithm - will be applied to the data to obtain some result. Here arg1 will be - applied pre-gather and arg2 will be applied post-gather. In parallel - runs the algorithm will be run on each processor to make intermediate - results and then again on the root processor over all of the - intermediate results to create a global result. - - Optional argument idx is used to specify the output port number to fetch the - data from. Default is port 0. - """ - - import types - - reducer = filters.ReductionFilter(Input=OutputPort(input,idx)) - - #create the pipeline that reduces and transmits the data - if arg1 == None: - cdinfo = input.GetDataInformation(idx).GetCompositeDataInformation() - if cdinfo.GetDataIsComposite(): - print "use composite data append" - reducer.PostGatherHelperName = "vtkMultiBlockDataGroupFilter" - - elif input.GetDataInformation(idx).GetDataClassName() == "vtkPolyData": - print "use append poly data filter" - reducer.PostGatherHelperName = "vtkAppendPolyData" - - elif input.GetDataInformation(idx).GetDataClassName() == "vtkRectilinearGrid": - print "use append rectilinear grid filter" - reducer.PostGatherHelperName = "vtkAppendRectilinearGrid" - - elif input.GetDataInformation(idx).IsA("vtkDataSet"): - print "use unstructured append filter" - reducer.PostGatherHelperName = "vtkAppendFilter" - - elif type(arg1) is types.IntType: - reducer.PassThrough = arg1 - - else: - reducer.PreGatherHelper = arg1 - reducer.PostGatherHelper = arg2 - - # reduce - reducer.UpdatePipeline() - dataInfo = reducer.GetDataInformation(0) - dataType = dataInfo.GetDataSetType() - if dataInfo.GetCompositeDataSetType() > 0: - dataType = dataInfo.GetCompositeDataSetType() - - fetcher = filters.ClientServerMoveData(Input=reducer) - fetcher.OutputDataType = dataType - fetcher.WholeExtent = dataInfo.GetExtent()[:] - #fetch - fetcher.UpdatePipeline() - - op = fetcher.GetClientSideObject().GetOutputDataObject(0) - opc = op.NewInstance() - opc.ShallowCopy(op) - opc.UnRegister(None) - return opc - -def AnimateReader(reader, view, filename=None): - """This is a utility function that, given a reader and a view - animates over all time steps of the reader. If the optional - filename is provided, a movie is created (type depends on the - extension of the filename.""" - if not reader: - raise RuntimeError, "No reader was specified, cannot animate." - if not view: - raise RuntimeError, "No view was specified, cannot animate." - # Create an animation scene - scene = animation.AnimationScene() - - # We need to have the reader and the view registered with - # the time keeper. This is how the scene gets its time values. - try: - tk = ProxyManager().GetProxiesInGroup("timekeeper").values()[0] - scene.TimeKeeper = tk - except IndexError: - tk = misc.TimeKeeper() - scene.TimeKeeper = tk - - if not reader in tk.TimeSources: - tk.TimeSources.append(reader) - if not view in tk.Views: - tk.Views.append(view) - - - # with 1 view - scene.ViewModules = [view] - # Update the reader to get the time information - reader.UpdatePipelineInformation() - # Animate from 1st time step to last - scene.StartTime = reader.TimestepValues.GetData()[0] - scene.EndTime = reader.TimestepValues.GetData()[-1] - - # Each frame will correspond to a time step - scene.PlayMode = 2 #Snap To Timesteps - - # Create a special animation cue for time. - cue = animation.TimeAnimationCue() - cue.AnimatedProxy = view - cue.AnimatedPropertyName = "ViewTime" - scene.Cues = [cue] - - if filename: - writer = vtkSMAnimationSceneImageWriter() - writer.SetFileName(filename) - writer.SetFrameRate(1) - writer.SetAnimationScene(scene.SMProxy) - - # Now save the animation. - if not writer.Save(): - raise RuntimeError, "Saving of animation failed!" - else: - scene.Play() - return scene - -def GetProgressPrintingIsEnabled(): - return progressObserverTag is not None - -def SetProgressPrintingEnabled(value): - """Is not supported because of not supported observers""" - pass - -def ToggleProgressPrinting(): - """Turn on/off printing of progress. See SetProgressPrintingEnabled.""" - SetProgressPrintingEnabled(not GetProgressPrintingIsEnabled()) - -def Finalize(): - """Although not required, this can be called at exit to cleanup.""" - global progressObserverTag - # Make sure to remove the observer - if progressObserverTag: - ToggleProgressPrinting() - vtkInitializationHelper.Finalize() - -# Internal methods - -def _getPyProxy(smproxy, outputPort=0): - """Returns a python wrapper for a server manager proxy. This method - first checks if there is already such an object by looking in the - _pyproxies group and returns it if found. Otherwise, it creates a - new one. Proxies register themselves in _pyproxies upon creation.""" - if not smproxy: - return None - if (smproxy, outputPort) in _pyproxies: - return _pyproxies[(smproxy, outputPort)]() - - xmlName = smproxy.GetXMLName() - if smproxy.GetXMLLabel(): - xmlName = smproxy.GetXMLLabel() - classForProxy = _findClassForProxy(_make_name_valid(xmlName), smproxy.GetXMLGroup()) - if classForProxy: - retVal = classForProxy(proxy=smproxy, port=outputPort) - else: - retVal = Proxy(proxy=smproxy, port=outputPort) - return retVal - -def _makeUpdateCameraMethod(rv): - """ This internal method is used to create observer methods """ - if not hasattr(rv(), "BlockUpdateCamera"): - rv().add_attribute("BlockUpdateCamera", False) - def UpdateCamera(obj, string): - if not rv().BlockUpdateCamera: - # used to avoid some nasty recursion that occurs when interacting in - # the GUI. - rv().BlockUpdateCamera = True - rv().SynchronizeCameraProperties() - rv().BlockUpdateCamera = False - return UpdateCamera - -def _createInitialize(group, name): - """Internal method to create an Initialize() method for the sub-classes - of Proxy""" - pgroup = group - pname = name - def aInitialize(self, connection=None, update=True): - if not connection: - connection = ActiveConnection - if not connection: - raise RuntimeError,\ - 'Cannot create a proxy without a session.' - if not connection.Session.GetProxyDefinitionManager().HasDefinition(pgroup, pname): - error_msg = "The connection does not provide any definition for %s." % pname - raise RuntimeError, error_msg - self.InitializeFromProxy(\ - CreateProxy(pgroup, pname, connection.Session), update) - return aInitialize - -def _createGetProperty(pName): - """Internal method to create a GetXXX() method where XXX == pName.""" - propName = pName - def getProperty(self): - return self.GetPropertyValue(propName) - return getProperty - -def _createSetProperty(pName): - """Internal method to create a SetXXX() method where XXX == pName.""" - propName = pName - def setProperty(self, value): - return self.SetPropertyWithName(propName, value) - return setProperty - -def _findClassForProxy(xmlName, xmlGroup): - """Given the xmlName for a proxy, returns a Proxy class. Note - that if there are duplicates, the first one is returned.""" - global sources, filters, writers, rendering, animation, implicit_functions,\ - piecewise_functions, extended_sources, misc - if not xmlName: - return None - if xmlGroup == "sources": - return sources.__dict__[xmlName] - elif xmlGroup == "filters": - return filters.__dict__[xmlName] - elif xmlGroup == "implicit_functions": - return implicit_functions.__dict__[xmlName] - elif xmlGroup == "piecewise_functions": - return piecewise_functions.__dict__[xmlName] - elif xmlGroup == "writers": - return writers.__dict__[xmlName] - elif xmlGroup == "extended_sources": - return extended_sources.__dict__[xmlName] - elif xmlName in rendering.__dict__: - return rendering.__dict__[xmlName] - elif xmlName in animation.__dict__: - return animation.__dict__[xmlName] - elif xmlName in misc.__dict__: - return misc.__dict__[xmlName] - else: - return None - -def _printProgress(caller, event): - """The default event handler for progress. Prints algorithm - name and 1 '.' per 10% progress.""" - global currentAlgorithm, currentProgress - - pm = vtkProcessModule.GetProcessModule() - progress = pm.GetLastProgress() / 10 - # If we got a 100% as the first thing, ignore - # This is to get around the fact that some vtk - # algorithms report 100% more than once (which is - # a bug) - if not currentAlgorithm and progress == 10: - return - alg = pm.GetLastProgressName() - if alg != currentAlgorithm and alg: - if currentAlgorithm: - while currentProgress <= 10: - import sys - sys.stdout.write(".") - currentProgress += 1 - print "]" - currentProgress = 0 - print alg, ": [ ", - currentAlgorithm = alg - while currentProgress <= progress: - import sys - sys.stdout.write(".") - #sys.stdout.write("%d " % pm.GetLastProgress()) - currentProgress += 1 - if progress == 10: - print "]" - currentAlgorithm = None - currentProgress = 0 - -def updateModules(m): - """Called when a plugin is loaded, this method updates - the proxy class object in all known modules.""" - - createModule("sources", m.sources) - createModule("filters", m.filters) - createModule("writers", m.writers) - createModule("representations", m.rendering) - createModule("views", m.rendering) - createModule("lookup_tables", m.rendering) - createModule("textures", m.rendering) - createModule('cameramanipulators', m.rendering) - createModule("animation", m.animation) - createModule("misc", m.misc) - createModule('animation_keyframes', m.animation) - createModule('implicit_functions', m.implicit_functions) - createModule('piecewise_functions', m.piecewise_functions) - createModule("extended_sources", m.extended_sources) - createModule("incremental_point_locators", m.misc) - -def _createModules(m): - """Called when the module is loaded, this creates sub- - modules for all know proxy groups.""" - - m.sources = createModule('sources') - m.filters = createModule('filters') - m.writers = createModule('writers') - m.rendering = createModule('representations') - createModule('views', m.rendering) - createModule("lookup_tables", m.rendering) - createModule("textures", m.rendering) - createModule('cameramanipulators', m.rendering) - m.animation = createModule('animation') - createModule('animation_keyframes', m.animation) - m.implicit_functions = createModule('implicit_functions') - m.piecewise_functions = createModule('piecewise_functions') - m.extended_sources = createModule("extended_sources") - m.misc = createModule("misc") - createModule("incremental_point_locators", m.misc) - -class PVModule(object): - pass - -def _make_name_valid(name): - """Make a string into a valid Python variable name.""" - if not name: - return None - import string - valid_chars = "_%s%s" % (string.ascii_letters, string.digits) - name = str().join([c for c in name if c in valid_chars]) - if not name[0].isalpha(): - name = 'a' + name - return name - -def createModule(groupName, mdl=None): - """Populates a module with proxy classes defined in the given group. - If mdl is not specified, it also creates the module""" - global ActiveConnection - - if not ActiveConnection: - raise RuntimeError, "Please connect to a server using \"Connect\"" - - pxm = ProxyManager() - # Use prototypes to find all proxy types. - pxm.InstantiateGroupPrototypes(groupName) - - debug = False - if not mdl: - debug = True - mdl = PVModule() - definitionIter = pxm.NewDefinitionIterator(groupName) - for i in definitionIter: - proxyName = i['key'] - proto = pxm.GetPrototypeProxy(groupName, proxyName) - if not proto: - print "Error while loading %s/%s %s"%(groupName, i['group'], proxyName) - continue - pname = proxyName - if proto.GetXMLLabel(): - pname = proto.GetXMLLabel() - pname = _make_name_valid(pname) - if not pname: - continue - if pname in mdl.__dict__: - if debug: - print "Warning: %s is being overwritten. This may point to an issue in the ParaView configuration files" % pname - cdict = {} - # Create an Initialize() method for this sub-class. - cdict['Initialize'] = _createInitialize(groupName, proxyName) - iter = PropertyIterator(proto) - # Add all properties as python properties. - for prop in iter: - propName = iter.GetKey() - if (prop.GetInformationOnly() and propName != "TimestepValues" ) \ - or prop.GetIsInternal(): - continue - names = [propName] - names = [iter.PropertyLabel] - - propDoc = None - if prop.GetDocumentation(): - propDoc = prop.GetDocumentation().GetDescription() - for name in names: - name = _make_name_valid(name) - if name: - cdict[name] = property(_createGetProperty(propName), - _createSetProperty(propName), - None, - propDoc) - # Add the documentation as the class __doc__ - if proto.GetDocumentation() and \ - proto.GetDocumentation().GetDescription(): - doc = proto.GetDocumentation().GetDescription() - else: - doc = Proxy.__doc__ - cdict['__doc__'] = doc - # Create the new type - if proto.GetXMLName() == "ExodusIIReader": - superclasses = (ExodusIIReaderProxy,) - elif proto.IsA("vtkSMSourceProxy"): - superclasses = (SourceProxy,) - elif proto.IsA("vtkSMViewLayoutProxy"): - superclasses = (ViewLayoutProxy,) - else: - superclasses = (Proxy,) - - cobj = type(pname, superclasses, cdict) - # Add it to the modules dictionary - mdl.__dict__[pname] = cobj - return mdl - - -def __determineGroup(proxy): - """Internal method""" - if not proxy: - return None - xmlgroup = proxy.GetXMLGroup() - xmlname = proxy.GetXMLName() - if xmlgroup == "sources": - if xmlname in ["BlockSelectionSource", - "FrustumSelectionSource", - "GlobalIDSelectionSource", - "PedigreeIDSelectionSource", - "IDSelectionSource", - "CompositeDataIDSelectionSource", - "HierarchicalDataIDSelectionSource", - "ThresholdSelectionSource", - "LocationSelectionSource"]: - return "selection_sources" - return "sources" - elif xmlgroup == "filters": - return "sources" - elif xmlgroup == "representations": - if xmlname == "ScalarBarWidgetRepresentation": - return "scalar_bars" - return "representations" - elif xmlgroup == "animation_keyframes": - return "animation" - return xmlgroup - -__nameCounter = {} -def __determineName(proxy, group): - global __nameCounter - name = _make_name_valid(proxy.GetXMLLabel()) - if not name: - return None - if not __nameCounter.has_key(name): - __nameCounter[name] = 1 - val = 1 - else: - __nameCounter[name] += 1 - val = __nameCounter[name] - return "%s%d" % (name, val) - -def __getName(proxy, group): - pxm = ProxyManager(proxy.GetSession()) - if isinstance(proxy, Proxy): - proxy = proxy.SMProxy - return pxm.GetProxyName(group, proxy) - -class MissingRegistrationInformation(Exception): - """Exception for missing registration information. Raised when a name or group - is not specified or when a group cannot be deduced.""" - pass - -class MissingProxy(Exception): - """Exception fired when the requested proxy is missing.""" - pass - -def Register(proxy, **extraArgs): - """Registers a proxy with the proxy manager. If no 'registrationGroup' is - specified, then the group is inferred from the type of the proxy. - 'registrationName' may be specified to register with a particular name - otherwise a default name will be created.""" - # TODO: handle duplicate registration - if "registrationGroup" in extraArgs: - registrationGroup = extraArgs["registrationGroup"] - else: - registrationGroup = __determineGroup(proxy) - - if "registrationName" in extraArgs: - registrationName = extraArgs["registrationName"] - else: - registrationName = __determineName(proxy, registrationGroup) - if registrationGroup and registrationName: - pxm = ProxyManager() - pxm.RegisterProxy(registrationGroup, registrationName, proxy) - else: - raise MissingRegistrationInformation, "Registration error %s %s." % (registrationGroup, registrationName) - return (registrationGroup, registrationName) - -def UnRegister(proxy, **extraArgs): - """UnRegisters proxies registered using Register().""" - if "registrationGroup" in extraArgs: - registrationGroup = extraArgs["registrationGroup"] - else: - registrationGroup = __determineGroup(proxy) - - if "registrationName" in extraArgs: - registrationName = extraArgs["registrationName"] - else: - registrationName = __getName(proxy, registrationGroup) - - if registrationGroup and registrationName: - pxm = ProxyManager() - pxm.UnRegisterProxy(registrationGroup, registrationName, proxy) - else: - raise RuntimeError, "UnRegistration error." - return (registrationGroup, registrationName) - -def demo1(): - """This simple demonstration creates a sphere, renders it and delivers - it to the client using Fetch. It returns a tuple of (data, render - view)""" - if not ActiveConnection: - Connect() - ss = sources.Sphere(Radius=2, ThetaResolution=32) - shr = filters.Shrink(Input=OutputPort(ss,0)) - cs = sources.Cone() - app = filters.AppendDatasets() - app.Input = [shr, cs] - rv = CreateRenderView() - rep = CreateRepresentation(app, rv) - rv.ResetCamera() - rv.StillRender() - data = Fetch(ss) - - return (data, rv) - -def demo2(fname="/Users/berk/Work/ParaViewData/Data/disk_out_ref.ex2"): - """This method demonstrates the user of a reader, representation and - view. It also demonstrates how meta-data can be obtained using proxies. - Make sure to pass the full path to an exodus file. Also note that certain - parameters are hard-coded for disk_out_ref.ex2 which can be found - in ParaViewData. This method returns the render view.""" - if not ActiveConnection: - Connect() - # Create the exodus reader and specify a file name - reader = sources.ExodusIIReader(FileName=fname) - # Get the list of point arrays. - arraySelection = reader.PointVariables - print arraySelection.Available - # Select all arrays - arraySelection.SetData(arraySelection.Available) - - # Next create a default render view appropriate for the session type. - rv = CreateRenderView() - # Create the matching representation - rep = CreateRepresentation(reader, rv) - rep.Representation = 1 # Wireframe - # Black background is not pretty - rv.Background = [0.4, 0.4, 0.6] - rv.StillRender() - # Reset the camera to include the whole thing - rv.ResetCamera() - rv.StillRender() - # Change the elevation of the camera. See VTK documentation of vtkCamera - # for camera parameters. - c = rv.GetActiveCamera() - c.Elevation(45) - rv.StillRender() - # Now that the reader execute, let's get some information about it's - # output. - pdi = reader[0].PointData - # This prints a list of all read point data arrays as well as their - # value ranges. - print 'Number of point arrays:', len(pdi) - for i in range(len(pdi)): - ai = pdi[i] - print "----------------" - print "Array:", i, ai.Name, ":" - numComps = ai.GetNumberOfComponents() - print "Number of components:", numComps - for j in range(numComps): - print "Range:", ai.GetRange(j) - # White is boring. Let's color the geometry using a variable. - # First create a lookup table. This object controls how scalar - # values are mapped to colors. See VTK documentation for - # details. - lt = rendering.PVLookupTable() - # Assign it to the representation - rep.LookupTable = lt - # Color by point array called Pres - rep.ColorAttributeType = 0 # point data - rep.ColorArrayName = "Pres" - # Add to RGB points. These are tuples of 4 values. First one is - # the scalar values, the other 3 the RGB values. This list has - # 2 points: Pres: 0.00678, color: blue, Pres: 0.0288, color: red - lt.RGBPoints = [0.00678, 0, 0, 1, 0.0288, 1, 0, 0] - lt.ColorSpace = 1 # HSV - rv.StillRender() - return rv - -def demo3(): - """This method demonstrates the use of servermanager with numpy as - well as pylab for plotting. It creates an artificial data sources, - probes it with a line, delivers the result to the client using Fetch - and plots it using pylab. This demo requires numpy and pylab installed. - It returns a tuple of (data, render view).""" - import paraview.numpy_support - import pylab - - if not ActiveConnection: - Connect() - # Create a synthetic data source - source = sources.Wavelet() - # Let's get some information about the data. First, for the - # source to execute - source.UpdatePipeline() - - di = source.GetDataInformation() - print "Data type:", di.GetPrettyDataTypeString() - print "Extent:", di.GetExtent() - print "Array name:", \ - source[0].PointData[0].Name - - rv = CreateRenderView() - - rep1 = CreateRepresentation(source, rv) - rep1.Representation = 3 # outline - - # Let's apply a contour filter - cf = filters.Contour(Input=source, ContourValues=[200]) - - # Select the array to contour by - #cf.SelectInputScalars = 'RTData' - - rep2 = CreateRepresentation(cf, rv) - - rv.Background = (0.4, 0.4, 0.6) - # Reset the camera to include the whole thing - rv.StillRender() - rv.ResetCamera() - rv.StillRender() - - # Now, let's probe the data - probe = filters.ResampleWithDataset(Input=source) - # with a line - line = sources.Line(Resolution=60) - # that spans the dataset - bounds = di.GetBounds() - print "Bounds: ", bounds - line.Point1 = bounds[0:6:2] - line.Point2 = bounds[1:6:2] - - probe.Source = line - - # Render with the line - rep3 = CreateRepresentation(line, rv) - rv.StillRender() - - # Now deliver it to the client. Remember, this is for small data. - data = Fetch(probe) - # Convert it to a numpy array - data = paraview.numpy_support.vtk_to_numpy( - data.GetPointData().GetArray("RTData")) - # Plot it using matplotlib - pylab.plot(data) - pylab.show() - - return (data, rv, probe) - -def demo4(fname="/Users/berk/Work/ParaViewData/Data/can.ex2"): - """This method demonstrates the user of AnimateReader for - creating animations.""" - if not ActiveConnection: - Connect() - reader = sources.ExodusIIReader(FileName=fname) - view = CreateRenderView() - repr = CreateRepresentation(reader, view) - view.StillRender() - view.ResetCamera() - view.StillRender() - c = view.GetActiveCamera() - c.Elevation(95) - return AnimateReader(reader, view) - - -def demo5(): - """ Simple sphere animation""" - if not ActiveConnection: - Connect() - sphere = sources.Sphere() - view = CreateRenderView() - repr = CreateRepresentation(sphere, view) - - view.StillRender() - view.ResetCamera() - view.StillRender() - - # Create an animation scene - scene = animation.AnimationScene() - # Add 1 view - scene.ViewModules = [view] - - # Create a cue to animate the StartTheta property - cue = animation.KeyFrameAnimationCue() - cue.AnimatedProxy = sphere - cue.AnimatedPropertyName = "StartTheta" - # Add it to the scene's cues - scene.Cues = [cue] - - # Create 2 keyframes for the StartTheta track - keyf0 = animation.CompositeKeyFrame() - keyf0.Type = 2 # Set keyframe interpolation type to Ramp. - # At time = 0, value = 0 - keyf0.KeyTime = 0 - keyf0.KeyValues= [0] - - keyf1 = animation.CompositeKeyFrame() - # At time = 1.0, value = 200 - keyf1.KeyTime = 1.0 - keyf1.KeyValues= [200] - - # Add keyframes. - cue.KeyFrames = [keyf0, keyf1] - - scene.Play() - return scene - -ASSOCIATIONS = { 'POINTS' : 0, 'CELLS' : 1, 'VERTICES' : 4, 'EDGES' : 5, 'ROWS' : 6} - -# Users can set the active connection which will be used by API -# to create proxies etc when no connection argument is passed. -# Connect() automatically sets this if it is not already set. -ActiveConnection = None - -# Fields for multi-server support -MultiServerConnections = None - -# API for multi-server support -def enableMultiServer(multiServer=True): - """This method enable the current servermanager to support several - connections. Once we enable the multi-server support, the user can create - as many connection as he want and switch from one to another in order to - create and manage proxy.""" - global MultiServerConnections, ActiveConnection - if not multiServer and MultiServerConnections: - raise RuntimeError, "Once we enable Multi-Server support we can not get back" - MultiServerConnections = [] - if ActiveConnection: - MultiServerConnections.append(ActiveConnection) - -def switchActiveConnection(newActiveConnection=None): - """Switch active connection to be the provided one or if none just pick the - other one""" - global MultiServerConnections, ActiveConnection - if MultiServerConnections == None: - raise RuntimeError, "enableMultiServer() must be called before" - - # Manage the case when no connection is provided - if newActiveConnection: - ActiveConnection = newActiveConnection - __exposeActiveModules__() - # Update active session for ParaView - if vtkSMProxyManager.GetProxyManager().GetActiveSession() != ActiveConnection.Session: - vtkSMProxyManager.GetProxyManager().SetActiveSession(ActiveConnection.Session) - return ActiveConnection - else: - for connection in MultiServerConnections: - if connection != ActiveConnection: - ActiveConnection = connection - __exposeActiveModules__() - # Update active session for ParaView - if vtkSMProxyManager.GetProxyManager().GetActiveSession() != ActiveConnection.Session: - vtkSMProxyManager.GetProxyManager().SetActiveSession(ActiveConnection.Session) - return ActiveConnection - return None - -# Needs to be called when paraview module is loaded from python instead -# of pvpython, pvbatch or GUI. -if not vtkProcessModule.GetProcessModule(): -# pvoptions = None Not applicable for SALOME Python console -# if paraview.options.batch: -# pvoptions = vtkPVOptions(); -# pvoptions.SetProcessType(0x40) -# if paraview.options.symmetric: -# pvoptions.SetSymmetricMPIMode(True) - vtkInitializationHelper.Initialize(sys.executable, - vtkProcessModule.PROCESS_CLIENT, pvoptions) - -# Initialize progress printing. Can be turned off by calling -# ToggleProgressPrinting() again. -progressObserverTag = None -currentAlgorithm = False -currentProgress = 0 -fromGUI = False -ToggleProgressPrinting() - -_pyproxies = {} - -# Create needed sub-modules -# We can no longer create modules, unless we have connected to a server. -# _createModules() - -# Set up our custom importer (if possible) -loader = _ModuleLoader() -sys.meta_path.append(loader) - -def __InitAfterConnect__(connection): - """ - This function is called everytime after a server connection is made. - Since the ProxyManager and all proxy definitions are changed every time a - new connection is made, we re-create all the modules - """ - _createModules(connection.Modules) - ## VSV fromFilter is alwais False for SALOME because it can't be changed from ParaView code - #if not paraview.fromFilter: - # fromFilter is set when this module is imported from the programmable - # filter -# global _defUpdater -# _defUpdater = __DefinitionUpdater() - connection.AttachDefinitionUpdater() - pass - -def __exposeActiveModules__(): - """Update servermanager submodules to point to the current - ActiveConnection.Modules.*""" - # Expose all active module to the current servermanager module - if ActiveConnection: - for m in [mName for mName in dir(ActiveConnection.Modules) if mName[0] != '_' ]: - exec "global %s;%s = ActiveConnection.Modules.%s" % (m,m,m) - -# Definitions for working in SALOME GUI mode -#aParams = myParavis.GetConnectionParameters() -#ActiveConnection = Connect() -##Connection(aParams[0]) -#ActiveConnection.SetHost(aParams[1], aParams[2], aParams[3], aParams[4], aParams[5]) -#ToggleProgressPrinting() -#fromGUI = True +for name in dir(servermanager): + if name != "__file__": + globals()[name] = getattr(servermanager, name) +del servermanager InitFromGUI() - -if hasattr(sys, "ps1"): - # session is interactive. - print vtkSMProxyManager.GetParaViewSourceVersion(); - -def GetConnectionFromId(id): - for connection in MultiServerConnections: - if connection.ID == id: - return connection - return None - -def GetConnectionFromSession(session): - for connection in MultiServerConnections: - if connection.Session == session: - return connection - return None - -def GetConnectionAt(index): - return MultiServerConnections[index] - -def GetNumberOfConnections(): - return len(MultiServerConnections) - -#VTN: Problem during execution -#atexit.register(vtkPythonProgrammableFilter.DeleteGlobalPythonInterpretor) diff --git a/src/PV_SWIG/pvsimple.py b/src/PV_SWIG/pvsimple.py index 6a77e5f2..28b84303 100644 --- a/src/PV_SWIG/pvsimple.py +++ b/src/PV_SWIG/pvsimple.py @@ -17,1155 +17,25 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # -r"""simple is a module for using paraview server manager in Python. It -provides a simple convenience layer to functionality provided by the -C++ classes wrapped to Python as well as the servermanager module. - -A simple example: - from paraview.simple import * - - # Create a new sphere proxy on the active connection and register it - # in the sources group. - sphere = Sphere(ThetaResolution=16, PhiResolution=32) - - # Apply a shrink filter - shrink = Shrink(sphere) - - # Turn the visiblity of the shrink object on. - Show(shrink) - - # Render the scene - Render() +r""" This module is a direct forward to the initial +'simple' module of ParaView. """ -import paravisSM - -servermanager = paravisSM - -def enableMultiServer(): - servermanager.enableMultiServer() - -def switchActiveConnection(newActiveConnection=None, ns=None): - if not ns: - ns = globals() - _remove_functions(ns) - servermanager.switchActiveConnection(newActiveConnection) - _add_functions(ns) - -def Disconnect(ns=None, force=True): - if servermanager.ActiveConnection and (force or servermanager.MultiServerConnections == None): - if ns: - _remove_functions(ns) - _remove_functions(globals()) - if not servermanager.fromGUI: - servermanager.ProxyManager().DisableStateUpdateNotification() - servermanager.ProxyManager().UnRegisterProxies() - active_objects.view = None - active_objects.source = None - servermanager.Disconnect() - if not servermanager.fromGUI: - import gc - gc.collect() - -def Connect(ds_host=None, ds_port=11111, rs_host=None, rs_port=11111): - """Creates a connection to a server. Example usage: - > Connect("amber") # Connect to a single server at default port - > Connect("amber", 12345) # Connect to a single server at port 12345 - > Connect("amber", 11111, "vis_cluster", 11111) # connect to data server, render server pair""" - Disconnect(globals(), False) - connection = servermanager.Connect(ds_host, ds_port, rs_host, rs_port) - _add_functions(globals()) - - servermanager.ProxyManager().DisableStateUpdateNotification() - servermanager.ProxyManager().UpdateFromRemote() - tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper") - if not tk: - try: - tk = servermanager.misc.TimeKeeper() - servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk) - except AttributeError: - print "Error: Could not create TimeKeeper" - - scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene") - if not scene: - try: - scene = AnimationScene() - scene.TimeKeeper = tk - except NameError: - print "Error: Could not create AnimationScene" - - servermanager.ProxyManager().EnableStateUpdateNotification() - servermanager.ProxyManager().TriggerStateUpdate() - - return connection - -def ReverseConnect(port=11111): - """Create a reverse connection to a server. Listens on port and waits for - an incoming connection from the server.""" - Disconnect(globals(), False) - connection = servermanager.ReverseConnect(port) - _add_functions(globals()) - - servermanager.ProxyManager().DisableStateUpdateNotification() - servermanager.ProxyManager().UpdateFromRemote() - tk = servermanager.ProxyManager().GetProxy("timekeeper", "TimeKeeper") - if not tk: - tk = servermanager.misc.TimeKeeper() - servermanager.ProxyManager().RegisterProxy("timekeeper", "TimeKeeper", tk) - - scene = servermanager.ProxyManager().GetProxy("animation", "AnimationScene") - if not scene: - scene = AnimationScene() - scene.TimeKeeper = tk - - servermanager.ProxyManager().EnableStateUpdateNotification() - servermanager.ProxyManager().TriggerStateUpdate() - - return connection - -def _create_view(view_xml_name): - "Creates and returns a 3D render view." - view = servermanager._create_view(view_xml_name) - servermanager.ProxyManager().RegisterProxy("views", \ - "my_view%d" % _funcs_internals.view_counter, view) - active_objects.view = view - _funcs_internals.view_counter += 1 - - tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0] - views = tk.Views - if not view in views: - views.append(view) - try: - scene = GetAnimationScene() - if not view in scene.ViewModules: - scene.ViewModules.append(view) - except servermanager.MissingProxy: - pass - return view - -def CreateRenderView(): - return _create_view("RenderView") - -def CreateXYPlotView(): - return _create_view("XYChartView") - -def CreateBarChartView(): - return _create_view("XYBarChartView") - -def CreateComparativeRenderView(): - return _create_view("ComparativeRenderView") - -def CreateComparativeXYPlotView(): - return _create_view("ComparativeXYPlotView") - -def CreateComparativeBarChartView(): - return _create_view("ComparativeBarChartView") - -def CreateParallelCoordinatesChartView(): - return _create_view("ParallelCoordinatesChartView") - -def Create2DRenderView(): - return _create_view("2DRenderView") - -def OpenDataFile(filename, **extraArgs): - """Creates a reader to read the give file, if possible. - This uses extension matching to determine the best reader possible. - If a reader cannot be identified, then this returns None.""" - session = servermanager.ActiveConnection.Session - reader_factor = servermanager.vtkSMProxyManager.GetProxyManager().GetReaderFactory() - if reader_factor.GetNumberOfRegisteredPrototypes() == 0: - reader_factor.RegisterPrototypes(session, "sources") - first_file = filename - if type(filename) == list: - first_file = filename[0] - if not reader_factor.TestFileReadability(first_file, session): - msg = "File not readable: %s " % first_file - raise RuntimeError, msg - if not reader_factor.CanReadFile(first_file, session): - msg = "File not readable. No reader found for '%s' " % first_file - raise RuntimeError, msg - prototype = servermanager.ProxyManager().GetPrototypeProxy( - reader_factor.GetReaderGroup(), reader_factor.GetReaderName()) - xml_name = paraview.make_name_valid(prototype.GetXMLLabel()) - reader_func = _create_func(xml_name, servermanager.sources) - if prototype.GetProperty("FileNames"): - reader = reader_func(FileNames=filename, **extraArgs) - else : - reader = reader_func(FileName=filename, **extraArgs) - return reader - -def CreateWriter(filename, proxy=None, **extraArgs): - """Creates a writer that can write the data produced by the source proxy in - the given file format (identified by the extension). If no source is - provided, then the active source is used. This doesn't actually write the - data, it simply creates the writer and returns it.""" - if not filename: - raise RuntimeError, "filename must be specified" - session = servermanager.ActiveConnection.Session - writer_factory = servermanager.vtkSMProxyManager.GetProxyManager().GetWriterFactory() - if writer_factory.GetNumberOfRegisteredPrototypes() == 0: - writer_factory.RegisterPrototypes(session, "writers") - if not proxy: - proxy = GetActiveSource() - if not proxy: - raise RuntimeError, "Could not locate source to write" - writer_proxy = writer_factory.CreateWriter(filename, proxy.SMProxy, proxy.Port) - return servermanager._getPyProxy(writer_proxy) - -def GetRenderView(): - """Returns the active view if there is one. Else creates and returns a new view.""" - view = active_objects.view - if not view: - # it's possible that there's no active view, but a render view exists. - # If so, locate that and return it (before trying to create a new one). - view = servermanager.GetRenderView() - if not view: - view = CreateRenderView() - return view - -def GetRenderViews(): - """Returns all render views as a list.""" - return servermanager.GetRenderViews() - -def GetRepresentation(proxy=None, view=None): - """Given a pipeline object and view, returns the corresponding representation object. - If pipeline object and view are not specified, active objects are used.""" - if not view: - view = active_objects.view - if not proxy: - proxy = active_objects.source - rep = servermanager.GetRepresentation(proxy, view) - if not rep: - rep = servermanager.CreateRepresentation(proxy, view) - servermanager.ProxyManager().RegisterProxy("representations", \ - "my_representation%d" % _funcs_internals.rep_counter, rep) - _funcs_internals.rep_counter += 1 - return rep - -def GetDisplayProperties(proxy=None, view=None): - """Given a pipeline object and view, returns the corresponding representation object. - If pipeline object and/or view are not specified, active objects are used.""" - return GetRepresentation(proxy, view) - -def Show(proxy=None, view=None, **params): - """Turns the visibility of a given pipeline object on in the given view. - If pipeline object and/or view are not specified, active objects are used.""" - if proxy == None: - proxy = GetActiveSource() - if proxy == None: - raise RuntimeError, "Show() needs a proxy argument or that an active source is set." - if not view and not active_objects.view: - CreateRenderView() - rep = GetDisplayProperties(proxy, view) - if rep == None: - raise RuntimeError, "Could not create a representation object for proxy %s" % proxy.GetXMLLabel() - for param in params.keys(): - setattr(rep, param, params[param]) - rep.Visibility = 1 - return rep - -def Hide(proxy=None, view=None): - """Turns the visibility of a given pipeline object off in the given view. - If pipeline object and/or view are not specified, active objects are used.""" - rep = GetDisplayProperties(proxy, view) - rep.Visibility = 0 - -def Render(view=None): - """Renders the given view (default value is active view)""" - if not view: - view = active_objects.view - view.StillRender() - if _funcs_internals.first_render: - # Not all views have a ResetCamera method - try: - view.ResetCamera() - view.StillRender() - except AttributeError: pass - _funcs_internals.first_render = False - return view - -def ResetCamera(view=None): - """Resets the settings of the camera to preserver orientation but include - the whole scene. If an argument is not provided, the active view is - used.""" - if not view: - view = active_objects.view - if hasattr(view, "ResetCamera"): - view.ResetCamera() - if hasattr(view, "ResetDisplay"): - view.ResetDisplay() - Render(view) - -def _DisableFirstRenderCameraReset(): - """Disable the first render camera reset. Normally a ResetCamera is called - automatically when Render is called for the first time after importing - this module.""" - _funcs_internals.first_render = False - -def SetProperties(proxy=None, **params): - """Sets one or more properties of the given pipeline object. If an argument - is not provided, the active source is used. Pass a list of property_name=value - pairs to this function to set property values. For example: - SetProperties(Center=[1, 2, 3], Radius=3.5) - """ - if not proxy: - proxy = active_objects.source - for param in params.keys(): - if not hasattr(proxy, param): - raise AttributeError("object has no property %s" % param) - setattr(proxy, param, params[param]) - -def GetProperty(*arguments, **keywords): - """Get one property of the given pipeline object. If keywords are used, - you can set the proxy and the name of the property that you want to get - like in the following example : - GetProperty({proxy=sphere, name="Radius"}) - If it's arguments that are used, then you have two case: - - if only one argument is used that argument will be - the property name. - - if two arguments are used then the first one will be - the proxy and the second one the property name. - Several example are given below: - GetProperty({name="Radius"}) - GetProperty({proxy=sphereProxy, name="Radius"}) - GetProperty( sphereProxy, "Radius" ) - GetProperty( "Radius" ) - """ - name = None - proxy = None - for key in keywords: - if key == "name": - name = keywords[key] - if key == "proxy": - proxy = keywords[key] - if len(arguments) == 1 : - name = arguments[0] - if len(arguments) == 2 : - proxy = arguments[0] - name = arguments[1] - if not name: - raise RuntimeError, "Expecting at least a property name as input. Otherwise keyword could be used to set 'proxy' and property 'name'" - if not proxy: - proxy = active_objects.source - return proxy.GetProperty(name) - -def SetDisplayProperties(proxy=None, view=None, **params): - """Sets one or more display properties of the given pipeline object. If an argument - is not provided, the active source is used. Pass a list of property_name=value - pairs to this function to set property values. For example: - SetProperties(Color=[1, 0, 0], LineWidth=2) - """ - rep = GetDisplayProperties(proxy, view) - SetProperties(rep, **params) - -def SetViewProperties(view=None, **params): - """Sets one or more properties of the given view. If an argument - is not provided, the active view is used. Pass a list of property_name=value - pairs to this function to set property values. For example: - SetProperties(Background=[1, 0, 0], UseImmediateMode=0) - """ - if not view: - view = active_objects.view - SetProperties(view, **params) - -def RenameSource(newName, proxy=None): - """Renames the given source. If the given proxy is not registered - in the sources group this method will have no effect. If no source is - provided, the active source is used.""" - if not proxy: - proxy = active_objects.source - pxm = servermanager.ProxyManager() - oldName = pxm.GetProxyName("sources", proxy) - if oldName: - pxm.RegisterProxy("sources", newName, proxy) - pxm.UnRegisterProxy("sources", oldName, proxy) - -def FindSource(name): - return servermanager.ProxyManager().GetProxy("sources", name) - -def GetSources(): - """Given the name of a source, return its Python object.""" - return servermanager.ProxyManager().GetProxiesInGroup("sources") - -def GetRepresentations(): - """Returns all representations (display properties).""" - return servermanager.ProxyManager().GetProxiesInGroup("representations") - -def UpdatePipeline(time=None, proxy=None): - """Updates (executes) the given pipeline object for the given time as - necessary (i.e. if it did not already execute). If no source is provided, - the active source is used instead.""" - if not proxy: - proxy = active_objects.source - if time: - proxy.UpdatePipeline(time) - else: - proxy.UpdatePipeline() - -def Delete(proxy=None): - """Deletes the given pipeline object or the active source if no argument - is specified.""" - if not proxy: - proxy = active_objects.source - # Unregister any helper proxies stored by a vtkSMProxyListDomain - for prop in proxy: - listdomain = prop.GetDomain('proxy_list') - if listdomain: - if listdomain.GetClassName() != 'vtkSMProxyListDomain': - continue - group = "pq_helper_proxies." + proxy.GetGlobalIDAsString() - for i in xrange(listdomain.GetNumberOfProxies()): - pm = servermanager.ProxyManager() - iproxy = listdomain.GetProxy(i) - name = pm.GetProxyName(group, iproxy) - if iproxy and name: - pm.UnRegisterProxy(group, name, iproxy) - - # Remove source/view from time keeper - tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0] - if isinstance(proxy, servermanager.SourceProxy): - try: - idx = tk.TimeSources.index(proxy) - del tk.TimeSources[idx] - except ValueError: - pass - else: - try: - idx = tk.Views.index(proxy) - del tk.Views[idx] - except ValueError: - pass - servermanager.UnRegister(proxy) - - # If this is a representation, remove it from all views. - if proxy.SMProxy.IsA("vtkSMRepresentationProxy") or \ - proxy.SMProxy.IsA("vtkSMNewWidgetRepresentationProxy"): - for view in GetRenderViews(): - view.Representations.remove(proxy) - # If this is a source, remove the representation iff it has no consumers - # Also change the active source if necessary - elif proxy.SMProxy.IsA("vtkSMSourceProxy"): - sources = servermanager.ProxyManager().GetProxiesInGroup("sources") - for i in range(proxy.GetNumberOfConsumers()): - if proxy.GetConsumerProxy(i) in sources: - raise RuntimeError("Source has consumers. It cannot be deleted " + - "until all consumers are deleted.") - #VSV:== - if proxy.IsSame(GetActiveSource()): - if hasattr(proxy, "Input") and proxy.Input: - if isinstance(proxy.Input, servermanager.Proxy): - SetActiveSource(proxy.Input) - else: - SetActiveSource(proxy.Input[0]) - else: SetActiveSource(None) - for rep in GetRepresentations().values(): - #VSV:== - if rep.Input.IsSame(proxy): - Delete(rep) - # Change the active view if necessary - elif proxy.SMProxy.IsA("vtkSMRenderViewProxy"): - ##VSV:== - if proxy.IsSame(GetActiveView()): - if len(GetRenderViews()) > 0: - SetActiveView(GetRenderViews()[0]) - else: - SetActiveView(None) - -def CreateLookupTable(**params): - """Create and return a lookup table. Optionally, parameters can be given - to assign to the lookup table. - """ - lt = servermanager.rendering.PVLookupTable() - servermanager.Register(lt) - SetProperties(lt, **params) - return lt - -def CreatePiecewiseFunction(**params): - """Create and return a piecewise function. Optionally, parameters can be - given to assign to the piecewise function. - """ - pfunc = servermanager.piecewise_functions.PiecewiseFunction() - servermanager.Register(pfunc) - SetProperties(pfunc, **params) - return pfunc - -def GetLookupTableForArray(arrayname, num_components, **params): - """Used to get an existing lookuptable for a array or to create one if none - exists. Keyword arguments can be passed in to initialize the LUT if a new - one is created.""" - proxyName = "%d.%s.PVLookupTable" % (int(num_components), arrayname) - lut = servermanager.ProxyManager().GetProxy("lookup_tables", proxyName) - if lut: - return lut - # No LUT exists for this array, create a new one. - # TODO: Change this to go a LookupTableManager that is shared with the GUI, - # so that the GUI and python end up create same type of LUTs. For now, - # python will create a Blue-Red LUT, unless overridden by params. - lut = servermanager.rendering.PVLookupTable( - ColorSpace="HSV", RGBPoints=[0, 0, 0, 1, 1, 1, 0, 0]) - SetProperties(lut, **params) - servermanager.Register(lut, registrationName=proxyName) - return lut - -def CreateScalarBar(**params): - """Create and return a scalar bar widget. The returned widget may - be added to a render view by appending it to the view's representations - The widget must have a valid lookup table before it is added to a view. - It is possible to pass the lookup table (and other properties) as arguments - to this method: - - lt = MakeBlueToRedLt(3.5, 7.5) - bar = CreateScalarBar(LookupTable=lt, Title="Velocity") - GetRenderView().Representations.append(bar) - - By default the returned widget is selectable and resizable. - """ - sb = servermanager.rendering.ScalarBarWidgetRepresentation() - servermanager.Register(sb) - sb.Selectable = 1 - sb.Resizable = 1 - sb.Enabled = 1 - sb.Title = "Scalars" - SetProperties(sb, **params) - return sb - -# TODO: Change this to take the array name and number of components. Register -# the lt under the name ncomp.array_name -def MakeBlueToRedLT(min, max): - # Define RGB points. These are tuples of 4 values. First one is - # the scalar values, the other 3 the RGB values. - rgbPoints = [min, 0, 0, 1, max, 1, 0, 0] - return CreateLookupTable(RGBPoints=rgbPoints, ColorSpace="HSV") - -def _find_writer(filename): - """Internal function.""" - extension = None - parts = filename.split('.') - if len(parts) > 1: - extension = parts[-1] - else: - raise RuntimeError, "Filename has no extension, please specify a write" - - if extension == 'png': - return 'vtkPNGWriter' - elif extension == 'bmp': - return 'vtkBMPWriter' - elif extension == 'ppm': - return 'vtkPNMWriter' - elif extension == 'tif' or extension == 'tiff': - return 'vtkTIFFWriter' - elif extension == 'jpg' or extension == 'jpeg': - return 'vtkJPEGWriter' - else: - raise RuntimeError, "Cannot infer filetype from extension:", extension - -def AddCameraLink(viewProxy, viewProxyOther, linkName): - """Create a camera link between two view proxies. A name must be given - so that the link can be referred to by name. If a link with the given - name already exists it will be removed first.""" - if not viewProxyOther: viewProxyOther = GetActiveView() - link = servermanager.vtkSMCameraLink() - link.AddLinkedProxy(viewProxy.SMProxy, 1) - link.AddLinkedProxy(viewProxyOther.SMProxy, 2) - link.AddLinkedProxy(viewProxyOther.SMProxy, 1) - link.AddLinkedProxy(viewProxy.SMProxy, 2) - RemoveCameraLink(linkName) - servermanager.ProxyManager().RegisterLink(linkName, link) - -def RemoveCameraLink(linkName): - """Remove a camera link with the given name.""" - servermanager.ProxyManager().UnRegisterLink(linkName) - -def WriteImage(filename, view=None, **params): - """Saves the given view (or the active one if none is given) as an - image. Optionally, you can specify the writer and the magnification - using the Writer and Magnification named arguments. For example: - WriteImage("foo.mypng", aview, Writer=vtkPNGWriter, Magnification=2) - If no writer is provided, the type is determined from the file extension. - Currently supported extensions are png, bmp, ppm, tif, tiff, jpg and jpeg. - The writer is a VTK class that is capable of writing images. - Magnification is used to determine the size of the written image. The size - is obtained by multiplying the size of the view with the magnification. - Rendering may be done using tiling to obtain the correct size without - resizing the view.""" - if not view: - view = active_objects.view - writer = None - if params.has_key('Writer'): - writer = params['Writer'] - mag = 1 - if params.has_key('Magnification'): - mag = int(params['Magnification']) - if not writer: - writer = _find_writer(filename) - view.WriteImage(filename, writer, mag) - -def AnimateReader(reader=None, view=None, filename=None): - """This is a utility function that, given a reader and a view - animates over all time steps of the reader. If the optional - filename is provided, a movie is created (type depends on the - extension of the filename.""" - if not reader: - reader = active_objects.source - if not view: - view = active_objects.view - - return servermanager.AnimateReader(reader, view, filename) - - -def _create_func(key, module): - """Internal function.""" - - def CreateObject(*input, **params): - """This function creates a new proxy. For pipeline objects that accept inputs, - all non-keyword arguments are assumed to be inputs. All keyword arguments are - assumed to be property,value pairs and are passed to the new proxy.""" - - # Instantiate the actual object from the given module. - px = module.__dict__[key]() - - # Make sure non-keyword arguments are valid - for inp in input: - if inp != None and not isinstance(inp, servermanager.Proxy): - if px.GetProperty("Input") != None: - raise RuntimeError, "Expecting a proxy as input." - else: - raise RuntimeError, "This function does not accept non-keyword arguments." - - # Assign inputs - if px.GetProperty("Input") != None: - if len(input) > 0: - px.Input = input - else: - # If no input is specified, try the active pipeline object - if px.GetProperty("Input").GetRepeatable() and active_objects.get_selected_sources(): - px.Input = active_objects.get_selected_sources() - elif active_objects.source: - px.Input = active_objects.source - else: - if len(input) > 0: - raise RuntimeError, "This function does not expect an input." - - registrationName = None - for nameParam in ['registrationName', 'guiName']: - if nameParam in params: - registrationName = params[nameParam] - del params[nameParam] - - # Pass all the named arguments as property,value pairs - for param in params.keys(): - setattr(px, param, params[param]) - - try: - # Register the proxy with the proxy manager. - if registrationName: - group, name = servermanager.Register(px, registrationName=registrationName) - else: - group, name = servermanager.Register(px) - - - # Register pipeline objects with the time keeper. This is used to extract time values - # from sources. NOTE: This should really be in the servermanager controller layer. - if group == "sources": - has_tk = True - try: - tk = servermanager.ProxyManager().GetProxiesInGroup("timekeeper").values()[0] - except IndexError: - has_tk = False - if has_tk: - sources = tk.TimeSources - if not px in sources: - sources.append(px) - - active_objects.source = px - except servermanager.MissingRegistrationInformation: - pass - - return px - - return CreateObject - -def _create_doc(new, old): - """Internal function.""" - import string - res = "" - for doc in (new, old): - ts = [] - strpd = doc.split('\n') - for s in strpd: - ts.append(s.lstrip()) - res += string.join(ts) - res += '\n' - return res - -def _func_name_valid(name): - """Internal function.""" - valid = True - for c in name: - if c == '(' or c ==')': - valid = False - break - return valid - -def _add_functions(g): - activeModule = servermanager.ActiveConnection.Modules - for m in [activeModule.filters, activeModule.sources, - activeModule.writers, activeModule.animation]: - dt = m.__dict__ - for key in dt.keys(): - cl = dt[key] - if not isinstance(cl, str): - if not key in g and _func_name_valid(key): - g[key] = _create_func(key, m) - exec "g[key].__doc__ = _create_doc(m.%s.__doc__, g[key].__doc__)" % key - -def _remove_functions(g): - list = [] - if servermanager.ActiveConnection: - list = [m for m in dir(servermanager.ActiveConnection.Modules) if m[0] != '_'] - - for m in list: - dt = servermanager.ActiveConnection.Modules.__dict__[m].__dict__ - for key in dt.keys(): - cl = dt[key] - if not isinstance(cl, str) and g.has_key(key): - g.pop(key) - #print "remove %s function" % key - -def GetActiveView(): - """Returns the active view.""" - return active_objects.view - -def SetActiveView(view): - """Sets the active view.""" - active_objects.view = view - -def GetActiveSource(): - """Returns the active source.""" - return active_objects.source - -def SetActiveSource(source): - """Sets the active source.""" - active_objects.source = source - -def GetActiveCamera(): - """Returns the active camera for the active view. The returned object - is an instance of vtkCamera.""" - return GetActiveView().GetActiveCamera() - -def GetAnimationScene(): - """Returns the application-wide animation scene. ParaView has only one - global animation scene. This method provides access to that. Users are - free to create additional animation scenes directly, but those scenes - won't be shown in the ParaView GUI.""" - animation_proxies = servermanager.ProxyManager().GetProxiesInGroup("animation") - scene = None - for aProxy in animation_proxies.values(): - if aProxy.GetXMLName() == "AnimationScene": - scene = aProxy - break - if not scene: - raise servermanager.MissingProxy, "Could not locate global AnimationScene." - return scene - -def WriteAnimation(filename, **params): - """Writes the current animation as a file. Optionally one can specify - arguments that qualify the saved animation files as keyword arguments. - Accepted options are as follows: - * Magnification (integer) : set the maginification factor for the saved - animation. - * Quality (0 [worst] or 1 or 2 [best]) : set the quality of the generated - movie (if applicable). - * Subsampling (integer) : setting whether the movie encoder should use - subsampling of the chrome planes or not, if applicable. Since the human - eye is more sensitive to brightness than color variations, subsampling - can be useful to reduce the bitrate. Default value is 0. - * BackgroundColor (3-tuple of doubles) : set the RGB background color to - use to fill empty spaces in the image. - * FrameRate (double): set the frame rate (if applicable).""" - scene = GetAnimationScene() - # ensures that the TimeKeeper track is created. - GetTimeTrack() - iw = servermanager.vtkSMAnimationSceneImageWriter() - iw.SetAnimationScene(scene.SMProxy) - iw.SetFileName(filename) - if params.has_key("Magnification"): - iw.SetMagnification(int(params["Magnification"])) - if params.has_key("Quality"): - iw.SetQuality(int(params["Quality"])) - if params.has_key("Subsampling"): - iw.SetSubsampling(int(params["Subsampling"])) - if params.has_key("BackgroundColor"): - iw.SetBackgroundColor(params["BackgroundColor"]) - if params.has_key("FrameRate"): - iw.SetFrameRate(float(params["FrameRate"])) - iw.Save() - -def _GetRepresentationAnimationHelper(sourceproxy): - """Internal method that returns the representation animation helper for a - source proxy. It creates a new one if none exists.""" - # ascertain that proxy is a source proxy - if not sourceproxy in GetSources().values(): - return None - for proxy in servermanager.ProxyManager(): - if proxy.GetXMLName() == "RepresentationAnimationHelper" and\ - proxy.GetProperty("Source").IsProxyAdded(sourceproxy.SMProxy): - return proxy - # create a new helper - proxy = servermanager.misc.RepresentationAnimationHelper( - Source=sourceproxy) - servermanager.ProxyManager().RegisterProxy( - "pq_helper_proxies.%s" % sourceproxy.GetGlobalIDAsString(), - "RepresentationAnimationHelper", proxy) - return proxy - -def GetAnimationTrack(propertyname_or_property, index=None, proxy=None): - """Returns an animation cue for the property. If one doesn't exist then a - new one will be created. - Typical usage: - track = GetAnimationTrack("Center", 0, sphere) or - track = GetAnimationTrack(sphere.GetProperty("Radius")) or - - # this returns the track to animate visibility of the active source in - # all views. - track = GetAnimationTrack("Visibility") - - For animating properties on implicit planes etc., use the following - signatures: - track = GetAnimationTrack(slice.SliceType.GetProperty("Origin"), 0) or - track = GetAnimationTrack("Origin", 0, slice.SliceType) - - """ - if not proxy: - proxy = GetActiveSource() - if not isinstance(proxy, servermanager.Proxy): - raise TypeError, "proxy must be a servermanager.Proxy instance" - if isinstance(propertyname_or_property, str): - propertyname = propertyname_or_property - elif isinstance(propertyname_or_property, servermanager.Property): - prop = propertyname_or_property - propertyname = prop.Name - proxy = prop.Proxy - else: - raise TypeError, "propertyname_or_property must be a string or servermanager.Property" - - # To handle the case where the property is actually a "display" property, in - # which case we are actually animating the "RepresentationAnimationHelper" - # associated with the source. - if propertyname in ["Visibility", "Opacity"]: - proxy = _GetRepresentationAnimationHelper(proxy) - if not proxy or not proxy.GetProperty(propertyname): - raise AttributeError, "Failed to locate property %s" % propertyname - - scene = GetAnimationScene() - for cue in scene.Cues: - try: - if cue.AnimatedProxy.IsSame(proxy) and\ - cue.AnimatedPropertyName == propertyname: - if index == None or index.IsSame(cue.AnimatedElement): ##index == cue.AnimatedElement: - return cue - except AttributeError: - pass - - # matching animation track wasn't found, create a new one. - cue = KeyFrameAnimationCue() - cue.AnimatedProxy = proxy - cue.AnimatedPropertyName = propertyname - if index != None: - cue.AnimatedElement = index - scene.Cues.append(cue) - return cue - -def GetCameraTrack(view=None): - """Returns the camera animation track for the given view. If no view is - specified, active view will be used. If no exisiting camera animation track - is found, a new one will be created.""" - if not view: - view = GetActiveView() - if not view: - raise ValueError, "No view specified" - scene = GetAnimationScene() - for cue in scene.Cues: - if cue.AnimatedProxy.IsSame(view) and\ - cue.GetXMLName() == "CameraAnimationCue": - return cue - # no cue was found, create a new one. - cue = CameraAnimationCue() - cue.AnimatedProxy = view - scene.Cues.append(cue) - return cue - -def GetTimeTrack(): - """Returns the animation track used to control the time requested from all - readers/filters during playback. - This is the "TimeKeeper - Time" track shown in ParaView's 'Animation View'. - If none exists, a new one will be created.""" - scene = GetAnimationScene() - tk = scene.TimeKeeper - for cue in scene.Cues: - if cue.GetXMLName() == "TimeAnimationCue" and cue.AnimatedProxy.IsSame(tk)\ - and cue.AnimatedPropertyName == "Time": - return cue - # no cue was found, create a new one. - cue = TimeAnimationCue() - cue.AnimatedProxy = tk - cue.AnimatedPropertyName = "Time" - scene.Cues.append(cue) - return cue - -def LoadXML(xmlstring, ns=None): - """Given a server manager XML as a string, parse and process it. - If you loaded the simple module with from paraview.simple import *, - make sure to pass globals() as the second arguments: - LoadXML(xmlstring, globals()) - Otherwise, the new functions will not appear in the global namespace.""" - if not ns: - ns = globals() - servermanager.LoadXML(xmlstring) - _add_functions(ns) - -def LoadPlugin(filename, remote=True, ns=None): - """Loads a ParaView plugin and updates this module with new constructors - if any. The remote argument (default to True) is to specify whether - the plugin will be loaded on client (remote=False) or on server (remote=True). - If you loaded the simple module with from paraview.simple import *, - make sure to pass globals() as an argument: - LoadPlugin("myplugin", False, globals()), to load on client; - LoadPlugin("myplugin", True, globals()), to load on server; - LoadPlugin("myplugin", ns=globals()), to load on server. - Otherwise, the new functions will not appear in the global namespace.""" - - if not ns: - ns = globals() - servermanager.LoadPlugin(filename, remote) - _add_functions(ns) - -def LoadDistributedPlugin(pluginname, remote=True, ns=None): - """Loads a plugin that's distributed with the executable. This uses the - information known about plugins distributed with ParaView to locate the - shared library for the plugin to load. Raises a RuntimeError if the plugin - was not found.""" - if not servermanager.ActiveConnection: - raise RuntimeError, "Cannot load a plugin without a session." - plm = servermanager.vtkSMProxyManager.GetProxyManager().GetPluginManager() - if remote: - session = servermanager.ActiveConnection.Session - info = plm.GetRemoteInformation(session) - else: - info = plm.GetLocalInformation() - for cc in range(0, info.GetNumberOfPlugins()): - if info.GetPluginName(cc) == pluginname: - return LoadPlugin(info.GetPluginFileName(cc), remote, ns) - raise RuntimeError, "Plugin '%s' not found" % pluginname - -def GetLayouts(): - """Returns the layout proxies on the active session. - Layout proxies are used to place views in a grid.""" - return servermanager.ProxyManager().GetProxiesInGroup("layouts") - -def GetLayout(view=None): - """Return the layout containing the give view, if any. - If no view is specified, active view is used. - """ - if not view: - view = GetActiveView() - if not view: - raise RuntimeError, "No active view was found." - layouts = GetLayouts() - for layout in layouts.values(): - if layout.GetViewLocation(view) != -1: - return layout - return None - - -def SelectCells(query=None, proxy=None): - """Select cells satisfying the query. If query is None, then all cells are - selected. If proxy is None, then the active source is used.""" - if not proxy: - proxy = GetActiveSource() - if not proxy: - raise RuntimeError, "No active source was found." - - if not query: - # This ends up being true for all cells. - query = "id >= 0" - - # Note, selSource is not registered with the proxy manager. - selSource = servermanager.sources.SelectionQuerySource() - selSource.FieldType = "CELL" - selSource.QueryString = str(query) - proxy.SMProxy.SetSelectionInput(proxy.Port, selSource.SMProxy, 0) - return selSource - -def ClearSelection(proxy=None): - """Clears the selection on the active source.""" - if not proxy: - proxy = GetActiveSource() - if not proxy: - raise RuntimeError, "No active source was found." - proxy.SMProxy.SetSelectionInput(proxy.Port, None, 0) - -class ActiveObjects(object): - """This class manages the active objects (source and view). The active - objects are shared between Python and the user interface. This class - is for internal use. Use the Set/Get methods for setting and getting - active objects.""" - def __get_selection_model(self, name, session=None): - "Internal method." - if session and not servermanager.ActiveConnection.Session.IsSame(session): - raise RuntimeError, "Try to set an active object with invalid active connection." - pxm = servermanager.ProxyManager(session) - model = pxm.GetSelectionModel(name) - if not model: - model = servermanager.vtkSMProxySelectionModel() - pxm.RegisterSelectionModel(name, model) - return model - - def set_view(self, view): - "Sets the active view." - active_view_model = self.__get_selection_model("ActiveView") - if view: - active_view_model = self.__get_selection_model("ActiveView", view.GetSession()) - active_view_model.SetCurrentProxy(view.SMProxy, 0) - else: - active_view_model = self.__get_selection_model("ActiveView") - active_view_model.SetCurrentProxy(None, 0) - - def get_view(self): - "Returns the active view." - return servermanager._getPyProxy( - self.__get_selection_model("ActiveView").GetCurrentProxy()) - - def set_source(self, source): - "Sets the active source." - active_sources_model = self.__get_selection_model("ActiveSources") - if source: - # 3 == CLEAR_AND_SELECT - active_sources_model = self.__get_selection_model("ActiveSources", source.GetSession()) - active_sources_model.SetCurrentProxy(source.SMProxy, 3) - else: - active_sources_model = self.__get_selection_model("ActiveSources") - active_sources_model.SetCurrentProxy(None, 3) - - def __convert_proxy(self, px): - "Internal method." - if not px: - return None - if px.IsA("vtkSMSourceProxy"): - return servermanager._getPyProxy(px) - else: - return servermanager.OutputPort( - servermanager._getPyProxy(px.GetSourceProxy()), - px.GetPortIndex()) - - def get_source(self): - "Returns the active source." - return self.__convert_proxy( - self.__get_selection_model("ActiveSources").GetCurrentProxy()) - - def get_selected_sources(self): - "Returns the set of sources selected in the pipeline browser." - model = self.__get_selection_model("ActiveSources") - proxies = [] - for i in xrange(model.GetNumberOfSelectedProxies()): - proxies.append(self.__convert_proxy(model.GetSelectedProxy(i))) - return proxies - - view = property(get_view, set_view) - source = property(get_source, set_source) - -class _funcs_internals: - """Internal class.""" - first_render = True - view_counter = 0 - rep_counter = 0 - -def demo1(): - """Simple demo that create the following pipeline - sphere - shrink - \ - - append - cone - / - """ - # Create a sphere of radius = 2, theta res. = 32 - # This object becomes the active source. - ss = Sphere(Radius=2, ThetaResolution=32) - # Apply the shrink filter. The Input property is optional. If Input - # is not specified, the filter is applied to the active source. - shr = Shrink(Input=ss) - # Create a cone source. - cs = Cone() - # Append cone and shrink - app = AppendDatasets() - app.Input = [shr, cs] - # Show the output of the append filter. The argument is optional - # as the app filter is now the active object. - Show(app) - # Render the default view. - Render() - -def demo2(fname="/Users/berk/Work/ParaView/ParaViewData/Data/disk_out_ref.ex2"): - """This demo shows the use of readers, data information and display - properties.""" - - # Create the exodus reader and specify a file name - reader = ExodusIIReader(FileName=fname) - # Get the list of point arrays. - avail = reader.PointVariables.Available - print avail - # Select all arrays - reader.PointVariables = avail - - # Turn on the visibility of the reader - Show(reader) - # Set representation to wireframe - SetDisplayProperties(Representation = "Wireframe") - # Black background is not pretty - SetViewProperties(Background = [0.4, 0.4, 0.6]) - Render() - # Change the elevation of the camera. See VTK documentation of vtkCamera - # for camera parameters. - # NOTE: THIS WILL BE SIMPLER - GetActiveCamera().Elevation(45) - Render() - # Now that the reader executed, let's get some information about it's - # output. - pdi = reader[0].PointData - # This prints a list of all read point data arrays as well as their - # value ranges. - print 'Number of point arrays:', len(pdi) - for i in range(len(pdi)): - ai = pdi[i] - print "----------------" - print "Array:", i, " ", ai.Name, ":" - numComps = ai.GetNumberOfComponents() - print "Number of components:", numComps - for j in range(numComps): - print "Range:", ai.GetRange(j) - # White is boring. Let's color the geometry using a variable. - # First create a lookup table. This object controls how scalar - # values are mapped to colors. See VTK documentation for - # details. - # Map min (0.00678) to blue, max (0.0288) to red - SetDisplayProperties(LookupTable = MakeBlueToRedLT(0.00678, 0.0288)) - # Color by point array called Pres - SetDisplayProperties(ColorAttributeType = "POINT_DATA") - SetDisplayProperties(ColorArrayName = "Pres") - Render() - -def PrintTrace(): - print paravisSM.myParavis.GetTrace() - -def SaveTrace(fileName): - paravisSM.myParavis.SaveTrace(fileName) - - -if not servermanager.ActiveConnection: - Connect() -else: - _add_functions(globals()) - -def ImportFile(theFileName): - paravisSM.ImportFile(theFileName) - -active_objects = ActiveObjects() -active_objects.view = GetRenderView() +from paraview import simple + +for name in dir(simple): + if name != "__file__": + globals()[name] = getattr(simple, name) +del simple + +print "Connecting to PVServer ..." +try: + # TODO: this should be improved (retrieval from the engine) + Connect('localhost') +except Exception as e: + print "*******************************************" + print "*******************************************" + print "Could not connect to PVServer on localhost!" + print "*******************************************" + print "*******************************************" + raise e -- 2.30.2 From 101d13f85618ebd9e2f0a7e64542b5e2d8797707 Mon Sep 17 00:00:00 2001 From: bruneton Date: Tue, 22 Oct 2013 13:54:46 +0000 Subject: [PATCH 08/16] CMake: bug fix. Ensure proper build order (.hh from IDL should be generated early enough). --- CMakeLists.txt | 17 +++++++++++++++-- idl/wrap.cmake | 1 - src/VTKWrapping/CMakeLists.txt | 18 ++---------------- src/VTKWrapping/GenerateWrapList.cmake | 3 +++ 4 files changed, 20 insertions(+), 19 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b4b92a77..8ae43981 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -191,14 +191,27 @@ MARK_AS_ADVANCED(SALOME_INSTALL_APPLISKEL_SCRIPTS SALOME_INSTALL_APPLISKEL_PYTH MARK_AS_ADVANCED(SALOME_INSTALL_PYTHON SALOME_INSTALL_PYTHON_SHARED) MARK_AS_ADVANCED(SALOME_INSTALL_AMCONFIG_LOCAL SALOME_INSTALL_DOC SALOME_PARAVIS_INSTALL_RES_DATA) +## Generation of the list of VTK classes (to be wrapped into IDLs) +## ===================================== +IF(NOT SALOME_LIGHT_ONLY) + # TODO: the below requires ParaView in the PYTHONPATH ... not so nice: + MESSAGE(STATUS "Generating list of wrapped VTK classes ...") + LIST(GET PARAVIEW_INCLUDE_DIRS 0 PARAVIEW_INCLUDE_DIR0) + EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${PROJECT_SOURCE_DIR}/src/VTKWrapping/getwrapclasses.py ${PARAVIEW_INCLUDE_DIR0} + RESULT_VARIABLE _res) + IF(NOT _res EQUAL 0) + MESSAGE(FATAL_ERROR "Unable to run the Python script retrieving the list of VTK classes.") + ENDIF() +ENDIF() + + # Sources # ======== -ADD_SUBDIRECTORY(src) - IF(NOT SALOME_LIGHT_ONLY) ADD_SUBDIRECTORY(idl) # Order matters when using the wrapping - to be added AFTER src ENDIF() +ADD_SUBDIRECTORY(src) ADD_SUBDIRECTORY(adm_local) ADD_SUBDIRECTORY(resources) diff --git a/idl/wrap.cmake b/idl/wrap.cmake index 64063d43..401463f4 100755 --- a/idl/wrap.cmake +++ b/idl/wrap.cmake @@ -82,4 +82,3 @@ ENDIF(EXISTS ${CMAKE_BINARY_DIR}/wrapfiles.txt) ADD_CUSTOM_TARGET(generate_txt DEPENDS ${CMAKE_BINARY_DIR}/wrapfiles.txt vtkWrapIDL.h hints) ADD_CUSTOM_TARGET(generate_idl ALL DEPENDS ${CMAKE_BINARY_DIR}/wrapfiles.txt vtkWrapIDL.h hints ${WRAP_IDL}) - diff --git a/src/VTKWrapping/CMakeLists.txt b/src/VTKWrapping/CMakeLists.txt index ca407da1..202f09ea 100644 --- a/src/VTKWrapping/CMakeLists.txt +++ b/src/VTKWrapping/CMakeLists.txt @@ -17,22 +17,6 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # - -## Generation of the list of VTK classes (to be wrapped into IDLs) -## ===================================== -IF(NOT SALOME_LIGHT_ONLY) - # TODO: the below requires ParaView in the PYTHONPATH ... not so nice: - MESSAGE(STATUS "Generating list of wrapped VTK classes ...") - LIST(GET PARAVIEW_INCLUDE_DIRS 0 PARAVIEW_INCLUDE_DIR0) - EXECUTE_PROCESS(COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/getwrapclasses.py ${PARAVIEW_INCLUDE_DIR0} - RESULT_VARIABLE _res) - IF(NOT _res EQUAL 0) - MESSAGE(FATAL_ERROR "Unable to run the Python script retrieving the list of VTK classes.") - ENDIF() -ENDIF() - -INCLUDE(GenerateWrapList.cmake) - ## Parser for VTK header files ## =========================== ## @@ -107,6 +91,8 @@ INCLUDE(wrap.cmake) ## SET(CMAKE_POSITION_INDEPENDENT_CODE ON) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") ADD_LIBRARY(VTK_IDL_Impl OBJECT ${WRAP_IDL_I_CC}) +# Ensure .hh files corresponding to IDL have been generated first: +ADD_DEPENDENCIES(VTK_IDL_Impl omniorb_module_SalomeIDLPARAVIS) # Make the list of wrapped files visible from the top directory (will be used in PVGUI and idl): SET(WRAP_IDL_I_HH "${WRAP_IDL_I_HH}" PARENT_SCOPE) diff --git a/src/VTKWrapping/GenerateWrapList.cmake b/src/VTKWrapping/GenerateWrapList.cmake index c884b5b5..7cf8c488 100644 --- a/src/VTKWrapping/GenerateWrapList.cmake +++ b/src/VTKWrapping/GenerateWrapList.cmake @@ -17,6 +17,9 @@ # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com # +##### +# NOT USED ANYMORE ... to be deleted +#### ADD_CUSTOM_COMMAND( OUTPUT ${PROJECT_BINARY_DIR}/wrapfiles.txt COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/getwrapclasses.py -- 2.30.2 From 2a52a1a6a3b3bfc7b90fef8e49a179605781b3e2 Mon Sep 17 00:00:00 2001 From: vsr Date: Wed, 23 Oct 2013 07:50:29 +0000 Subject: [PATCH 09/16] MEDFile is a first-level dependency of PARAVIS --- CMakeLists.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8ae43981..db190e8c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -146,9 +146,11 @@ FIND_PACKAGE(SalomeCAS REQUIRED) ## IF(SALOME_PARAVIS_BUILD_PLUGINS) SET(MED_ROOT_DIR $ENV{MED_ROOT_DIR} CACHE PATH "Path to the Salome MED module") + FIND_PACKAGE(SalomeMEDFile) + SALOME_LOG_OPTIONAL_PACKAGE(MEDFile SALOME_PARAVIS_BUILD_PLUGINS) IF(EXISTS ${MED_ROOT_DIR}) LIST(APPEND CMAKE_MODULE_PATH "${MED_ROOT_DIR}/adm_local/cmake_files") - FIND_PACKAGE(SalomeMED REQUIRED) # Should load MEDFile too + FIND_PACKAGE(SalomeMED REQUIRED) ELSE() MESSAGE(FATAL_ERROR "We absolutely need the Salome MED module to build plugins, please define MED_ROOT_DIR") ENDIF() -- 2.30.2 From 1b53d3e71cbdc086a559ed4690aee6a2aa897f95 Mon Sep 17 00:00:00 2001 From: bruneton Date: Wed, 23 Oct 2013 09:31:38 +0000 Subject: [PATCH 10/16] CMake: doing proper string comparison in IF clause --- SalomePARAVISConfig.cmake.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SalomePARAVISConfig.cmake.in b/SalomePARAVISConfig.cmake.in index 0266beb6..bb78d0e4 100644 --- a/SalomePARAVISConfig.cmake.in +++ b/SalomePARAVISConfig.cmake.in @@ -78,7 +78,7 @@ MATH(EXPR _range "${_list_len}-1") FOREACH(_p RANGE ${_range}) LIST(GET _PREREQ ${_p} _pkg ) LIST(GET _PREREQ_CONFIG_DIR ${_p} _pkg_dir) - IF(_pkg_dir) + IF(NOT _pkg_dir STREQUAL "") MESSAGE(STATUS "===> Reloading targets from ${_pkg} ...") FIND_PACKAGE(${_pkg} REQUIRED NO_MODULE PATHS "${_pkg_dir}" -- 2.30.2 From df6669e54f0bb1f91bac468a693c8a0dc28ddabc Mon Sep 17 00:00:00 2001 From: vsr Date: Wed, 23 Oct 2013 14:23:37 +0000 Subject: [PATCH 11/16] Rollback previous change --- SalomePARAVISConfig.cmake.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/SalomePARAVISConfig.cmake.in b/SalomePARAVISConfig.cmake.in index bb78d0e4..0266beb6 100644 --- a/SalomePARAVISConfig.cmake.in +++ b/SalomePARAVISConfig.cmake.in @@ -78,7 +78,7 @@ MATH(EXPR _range "${_list_len}-1") FOREACH(_p RANGE ${_range}) LIST(GET _PREREQ ${_p} _pkg ) LIST(GET _PREREQ_CONFIG_DIR ${_p} _pkg_dir) - IF(NOT _pkg_dir STREQUAL "") + IF(_pkg_dir) MESSAGE(STATUS "===> Reloading targets from ${_pkg} ...") FIND_PACKAGE(${_pkg} REQUIRED NO_MODULE PATHS "${_pkg_dir}" -- 2.30.2 From 34e4eb216b8e6a88cbcd12ab0e50f48d384608ad Mon Sep 17 00:00:00 2001 From: vsr Date: Thu, 24 Oct 2013 07:46:37 +0000 Subject: [PATCH 12/16] Fix problem of last improvements: - add missing -DPARAVIS_WITH_FULL_CORBA to Python flags for omniidl - use PARAVIS specific backend instead of standard one --- idl/CMakeLists.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/idl/CMakeLists.txt b/idl/CMakeLists.txt index 3789eb18..6ea44df2 100644 --- a/idl/CMakeLists.txt +++ b/idl/CMakeLists.txt @@ -24,11 +24,15 @@ INCLUDE_DIRECTORIES( ${PROJECT_BINARY_DIR}/idl ) +# we use PARAVIS specific back-end +SET(OMNIORB_IDLPYFLAGS -bpythonIDL -p${CMAKE_CURRENT_SOURCE_DIR}) + IF(NOT SALOME_PARAVIS_MINIMAL_CORBA) INCLUDE(wrap.cmake) # Hack to have a -D on the omniidl command line: # (again, this shouldn't last for long ...) SET(OMNIORB_IDLCXXFLAGS "${OMNIORB_IDLCXXFLAGS};-DPARAVIS_WITH_FULL_CORBA") + SET(OMNIORB_IDLPYFLAGS "${OMNIORB_IDLPYFLAGS};-DPARAVIS_WITH_FULL_CORBA") ADD_DEFINITIONS(-DPARAVIS_WITH_FULL_CORBA) ENDIF() -- 2.30.2 From 4cea330a6ef8eec7b39877da55ea9ac83a371aa7 Mon Sep 17 00:00:00 2001 From: rnc Date: Thu, 24 Oct 2013 11:43:44 +0000 Subject: [PATCH 13/16] BUG: CMake build procedure: Placed the detection of MedFile after the detection of the MED module in order to detect MedFile from what was exposed by the MED module --- CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index db190e8c..e50d4d92 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -146,14 +146,14 @@ FIND_PACKAGE(SalomeCAS REQUIRED) ## IF(SALOME_PARAVIS_BUILD_PLUGINS) SET(MED_ROOT_DIR $ENV{MED_ROOT_DIR} CACHE PATH "Path to the Salome MED module") - FIND_PACKAGE(SalomeMEDFile) - SALOME_LOG_OPTIONAL_PACKAGE(MEDFile SALOME_PARAVIS_BUILD_PLUGINS) IF(EXISTS ${MED_ROOT_DIR}) LIST(APPEND CMAKE_MODULE_PATH "${MED_ROOT_DIR}/adm_local/cmake_files") FIND_PACKAGE(SalomeMED REQUIRED) ELSE() MESSAGE(FATAL_ERROR "We absolutely need the Salome MED module to build plugins, please define MED_ROOT_DIR") ENDIF() + FIND_PACKAGE(SalomeMEDFile) + SALOME_LOG_OPTIONAL_PACKAGE(MEDFile SALOME_PARAVIS_BUILD_PLUGINS) ENDIF() ## Detection summary: -- 2.30.2 From a1fa90265a9547632231586ad5bc760d3762bdbf Mon Sep 17 00:00:00 2001 From: vsr Date: Fri, 25 Oct 2013 08:42:19 +0000 Subject: [PATCH 14/16] Add function to allow execute Python code in embeeded SALOME Python console or in ParaView Python console --- src/PVGUI/PVGUI_Module.cxx | 53 ++++++++++++++++++-------------------- src/PVGUI/PVGUI_Module.h | 3 +++ 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/PVGUI/PVGUI_Module.cxx b/src/PVGUI/PVGUI_Module.cxx index 5aa1d7b9..e2d8bd34 100644 --- a/src/PVGUI/PVGUI_Module.cxx +++ b/src/PVGUI/PVGUI_Module.cxx @@ -66,6 +66,7 @@ #include #include #include +#include #include #include @@ -635,15 +636,16 @@ void PVGUI_Module::onVariableChanged(pqVariableType t, const QString) { } } - -/*! - \brief Launches a tracing of current server -*/ -void PVGUI_Module::timerEvent(QTimerEvent* te ) +void PVGUI_Module::execPythonCommand(const QString& cmd, bool inSalomeConsole) { -#ifndef WNT - PyInterp_Dispatcher* aDispatcher = PyInterp_Dispatcher::Get(); - if ( !aDispatcher->IsBusy() ) { + if ( inSalomeConsole ) { + SalomeApp_Application* app = + dynamic_cast< SalomeApp_Application* >(SUIT_Session::session()->activeApplication()); + PyConsole_Console* pyConsole = app->pythonConsole(); + if (pyConsole) + pyConsole->exec(cmd); + } + else { pqPythonManager* manager = qobject_cast ( pqApplicationCore::instance()->manager( "PYTHON_MANAGER" ) ); if ( manager ) { @@ -651,13 +653,21 @@ void PVGUI_Module::timerEvent(QTimerEvent* te ) if ( pyDiag ) { pqPythonShell* shell = pyDiag->shell(); if ( shell ) { - QString script = "from paraview import smtrace\nsmtrace.start_trace()\n"; - shell->executeScript(script); - killTimer( te->timerId() ); + shell->executeScript(cmd); } } } } +} + +/*! + \brief Launches a tracing of current server +*/ +void PVGUI_Module::timerEvent(QTimerEvent* te ) +{ +#ifndef WNT + execPythonCommand("from paraview import smtrace\nsmtrace.start_trace()\n", false); + killTimer( te->timerId() ); #endif } @@ -1346,23 +1356,10 @@ void PVGUI_Module::onShowTrace() */ void PVGUI_Module::onRestartTrace() { - PyInterp_Dispatcher* aDispatcher = PyInterp_Dispatcher::Get(); - if ( !aDispatcher->IsBusy() ) { - pqPythonManager* manager = qobject_cast - ( pqApplicationCore::instance()->manager( "PYTHON_MANAGER" ) ); - if ( manager ) { - pqPythonDialog* pyDiag = manager->pythonShellDialog(); - if ( pyDiag ) { - pqPythonShell* shell = pyDiag->shell(); - if ( shell ) { - QString script = "from paraview import smtrace\n"; - script += "smtrace.stop_trace()\n"; - script += "smtrace.start_trace()\n"; - shell->executeScript(script); - } - } - } - } + QString script = "from paraview import smtrace\n"; + script += "smtrace.stop_trace()\n"; + script += "smtrace.start_trace()\n"; + execPythonCommand(script, false); } /*! diff --git a/src/PVGUI/PVGUI_Module.h b/src/PVGUI/PVGUI_Module.h index b56bf235..cf760389 100644 --- a/src/PVGUI/PVGUI_Module.h +++ b/src/PVGUI/PVGUI_Module.h @@ -217,6 +217,9 @@ private: //! restore visibility of the common dockable windows (OB, PyConsole, ... etc.) void restoreCommonWindowsState(); + //! run Python command + void execPythonCommand(const QString& cmd, bool inSalomeConsole = false); + private slots: void showHelpForProxy( const QString&, const QString& ); -- 2.30.2 From 52abf0ea49ab72830be4edbc96c9a5c7993424b0 Mon Sep 17 00:00:00 2001 From: bruneton Date: Fri, 25 Oct 2013 15:04:06 +0000 Subject: [PATCH 15/16] Not generating VTK class list when in MINIMAL CORBA mode --- CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index e50d4d92..01ec5895 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -195,7 +195,7 @@ MARK_AS_ADVANCED(SALOME_INSTALL_AMCONFIG_LOCAL SALOME_INSTALL_DOC SALOME_PARAVIS ## Generation of the list of VTK classes (to be wrapped into IDLs) ## ===================================== -IF(NOT SALOME_LIGHT_ONLY) +IF(NOT SALOME_LIGHT_ONLY AND NOT SALOME_PARAVIS_MINIMAL_CORBA) # TODO: the below requires ParaView in the PYTHONPATH ... not so nice: MESSAGE(STATUS "Generating list of wrapped VTK classes ...") LIST(GET PARAVIEW_INCLUDE_DIRS 0 PARAVIEW_INCLUDE_DIR0) -- 2.30.2 From e57e5ae7b810c0a9418f2759905dc42d353c3a2a Mon Sep 17 00:00:00 2001 From: vsr Date: Tue, 29 Oct 2013 05:11:24 +0000 Subject: [PATCH 16/16] 0022327: [CEA 937] Wrong display Incorrect index if it comes negative (reverse) from the file --- src/Plugins/MedReader/IO/vtkMedEntityArray.cxx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Plugins/MedReader/IO/vtkMedEntityArray.cxx b/src/Plugins/MedReader/IO/vtkMedEntityArray.cxx index cbb123c0..0960055c 100644 --- a/src/Plugins/MedReader/IO/vtkMedEntityArray.cxx +++ b/src/Plugins/MedReader/IO/vtkMedEntityArray.cxx @@ -464,13 +464,14 @@ void vtkMedEntityArray::GetCellVertices(vtkIdType index, vtkIdList* ids) this->GetEntity().GeometryType)); for (int sub = 0; subGetValue(nsub*index+sub)-1; + med_int subid = conn->GetValue(nsub*index+sub); bool invert = false; if(subid < 0) { subid = -subid; invert = true; } + subid = subid-1; vtkMedEntity subentity; subentity.GeometryType = vtkMedUtilities::GetSubGeometry( -- 2.30.2