diff --git a/Applications/PluginGenerator/ProjectTemplate/CMakeExternals/MITK.cmake b/Applications/PluginGenerator/ProjectTemplate/CMakeExternals/MITK.cmake index 749f5a71e2..df9d21a5f8 100644 --- a/Applications/PluginGenerator/ProjectTemplate/CMakeExternals/MITK.cmake +++ b/Applications/PluginGenerator/ProjectTemplate/CMakeExternals/MITK.cmake @@ -1,215 +1,211 @@ #----------------------------------------------------------------------------- # MITK #----------------------------------------------------------------------------- set(MITK_DEPENDS) set(proj_DEPENDENCIES) set(proj MITK) if(NOT MITK_DIR) #----------------------------------------------------------------------------- # Create CMake options to customize the MITK build #----------------------------------------------------------------------------- option(MITK_USE_SUPERBUILD "Use superbuild for MITK" ON) option(MITK_USE_BLUEBERRY "Build the BlueBerry platform in MITK" ON) option(MITK_BUILD_EXAMPLES "Build the MITK examples" OFF) option(MITK_BUILD_ALL_PLUGINS "Build all MITK plugins" OFF) option(MITK_BUILD_TESTING "Build the MITK unit tests" OFF) option(MITK_USE_ACVD "Use Approximated Centroidal Voronoi Diagrams" OFF) option(MITK_USE_CTK "Use CTK in MITK" ${MITK_USE_BLUEBERRY}) option(MITK_USE_DCMTK "Use DCMTK in MITK" ON) option(MITK_USE_Qt5 "Use Qt 5 library in MITK" ON) option(MITK_USE_DCMQI "Use dcmqi in MITK" OFF) option(MITK_USE_OpenCV "Use Intel's OpenCV library" OFF) - option(MITK_USE_SOFA "Use Simulation Open Framework Architecture" OFF) - option(MITK_USE_VMTK "Use the Vascular Modeling Toolkit in MITK" OFF) option(MITK_USE_Python "Enable Python wrapping in MITK" OFF) if(MITK_USE_BLUEBERRY AND NOT MITK_USE_CTK) message("Forcing MITK_USE_CTK to ON because of MITK_USE_BLUEBERRY") set(MITK_USE_CTK ON CACHE BOOL "Use CTK in MITK" FORCE) endif() if(MITK_USE_CTK AND NOT MITK_USE_Qt5) message("Forcing MITK_USE_Qt5 to ON because of MITK_USE_CTK") set(MITK_USE_Qt5 ON CACHE BOOL "Use Qt 5 library in MITK" FORCE) endif() set(MITK_USE_CableSwig ${MITK_USE_Python}) set(MITK_USE_GDCM 1) set(MITK_USE_ITK 1) set(MITK_USE_VTK 1) mark_as_advanced(MITK_USE_SUPERBUILD MITK_BUILD_ALL_PLUGINS MITK_BUILD_TESTING ) set(mitk_cmake_boolean_args MITK_USE_SUPERBUILD MITK_USE_BLUEBERRY MITK_BUILD_EXAMPLES MITK_BUILD_ALL_PLUGINS MITK_USE_ACVD MITK_USE_CTK MITK_USE_DCMTK MITK_USE_Qt5 MITK_USE_DCMQI MITK_USE_OpenCV - MITK_USE_SOFA - MITK_USE_VMTK MITK_USE_Python ) if(MITK_USE_Qt5) # Look for Qt at the superbuild level, to catch missing Qt libs early find_package(Qt5Widgets REQUIRED) endif() set(additional_mitk_cmakevars ) # Configure the set of default pixel types set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") foreach(_arg MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES MITK_ACCESSBYITK_DIMENSIONS) mark_as_advanced(${_arg}) list(APPEND additional_mitk_cmakevars "-D${_arg}:STRING=${${_arg}}") endforeach() #----------------------------------------------------------------------------- # Create options to inject pre-build dependencies #----------------------------------------------------------------------------- - foreach(proj CTK DCMTK DCMQI GDCM VTK ACVD ITK OpenCV SOFA VMTK CableSwig) + foreach(proj CTK DCMTK DCMQI GDCM VTK ACVD ITK OpenCV CableSwig) if(MITK_USE_${proj}) set(MITK_${proj}_DIR "${${proj}_DIR}" CACHE PATH "Path to ${proj} build directory") mark_as_advanced(MITK_${proj}_DIR) if(MITK_${proj}_DIR) list(APPEND additional_mitk_cmakevars "-D${proj}_DIR:PATH=${MITK_${proj}_DIR}") endif() endif() endforeach() set(MITK_BOOST_ROOT "${BOOST_ROOT}" CACHE PATH "Path to Boost directory") mark_as_advanced(MITK_BOOST_ROOT) if(MITK_BOOST_ROOT) list(APPEND additional_mitk_cmakevars "-DBOOST_ROOT:PATH=${MITK_BOOST_ROOT}") endif() set(MITK_SOURCE_DIR "" CACHE PATH "MITK source code location. If empty, MITK will be cloned from MITK_GIT_REPOSITORY") set(MITK_GIT_REPOSITORY "https://phabricator.mitk.org/diffusion/MITK/mitk.git" CACHE STRING "The git repository for cloning MITK") set(MITK_GIT_TAG "origin/release/2016-11" CACHE STRING "The git tag/hash to be used when cloning from MITK_GIT_REPOSITORY") mark_as_advanced(MITK_SOURCE_DIR MITK_GIT_REPOSITORY MITK_GIT_TAG) #----------------------------------------------------------------------------- # Create the final variable containing superbuild boolean args #----------------------------------------------------------------------------- set(mitk_boolean_args) foreach(mitk_cmake_arg ${mitk_cmake_boolean_args}) list(APPEND mitk_boolean_args -D${mitk_cmake_arg}:BOOL=${${mitk_cmake_arg}}) endforeach() #----------------------------------------------------------------------------- # Additional MITK CMake variables #----------------------------------------------------------------------------- if(MITK_USE_Qt5) list(APPEND additional_mitk_cmakevars "-DCMAKE_PREFIX_PATH:PATH=${CMAKE_PREFIX_PATH}") endif() if(MITK_USE_CTK) list(APPEND additional_mitk_cmakevars "-DGIT_EXECUTABLE:FILEPATH=${GIT_EXECUTABLE}") endif() if(MITK_INITIAL_CACHE_FILE) list(APPEND additional_mitk_cmakevars "-DMITK_INITIAL_CACHE_FILE:INTERNAL=${MITK_INITIAL_CACHE_FILE}") endif() if(MITK_USE_SUPERBUILD) set(MITK_BINARY_DIR ${proj}-superbuild) else() set(MITK_BINARY_DIR ${proj}-build) endif() set(proj_DEPENDENCIES) set(MITK_DEPENDS ${proj}) # Configure the MITK souce code location if(NOT MITK_SOURCE_DIR) set(mitk_source_location SOURCE_DIR ${CMAKE_BINARY_DIR}/${proj} GIT_REPOSITORY ${MITK_GIT_REPOSITORY} GIT_TAG ${MITK_GIT_TAG} ) else() set(mitk_source_location SOURCE_DIR ${MITK_SOURCE_DIR} ) endif() ExternalProject_Add(${proj} ${mitk_source_location} BINARY_DIR ${MITK_BINARY_DIR} PREFIX ${proj}${ep_suffix} INSTALL_COMMAND "" CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} ${mitk_boolean_args} ${additional_mitk_cmakevars} -DBUILD_SHARED_LIBS:BOOL=ON -DBUILD_TESTING:BOOL=${MITK_BUILD_TESTING} CMAKE_CACHE_ARGS ${ep_common_cache_args} CMAKE_CACHE_DEFAULT_ARGS ${ep_common_cache_default_args} DEPENDS ${proj_DEPENDENCIES} ) if(MITK_USE_SUPERBUILD) set(MITK_DIR "${CMAKE_CURRENT_BINARY_DIR}/${MITK_BINARY_DIR}/MITK-build") else() set(MITK_DIR "${CMAKE_CURRENT_BINARY_DIR}/${MITK_BINARY_DIR}") endif() else() # The project is provided using MITK_DIR, nevertheless since other # projects may depend on MITK, let's add an 'empty' one MacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") # Further, do some sanity checks in the case of a pre-built MITK set(my_itk_dir ${ITK_DIR}) set(my_vtk_dir ${VTK_DIR}) find_package(MITK REQUIRED) if(my_itk_dir AND NOT my_itk_dir STREQUAL ${ITK_DIR}) message(FATAL_ERROR "ITK packages do not match:\n ${MY_PROJECT_NAME}: ${my_itk_dir}\n MITK: ${ITK_DIR}") endif() if(my_vtk_dir AND NOT my_vtk_dir STREQUAL ${VTK_DIR}) message(FATAL_ERROR "VTK packages do not match:\n ${MY_PROJECT_NAME}: ${my_vtk_dir}\n MITK: ${VTK_DIR}") endif() endif() diff --git a/CMake/BuildConfigurations/All.cmake b/CMake/BuildConfigurations/All.cmake index 44485e6a27..3fb1ead7fb 100644 --- a/CMake/BuildConfigurations/All.cmake +++ b/CMake/BuildConfigurations/All.cmake @@ -1,81 +1,73 @@ set(MITK_CONFIG_PACKAGES ) set(_apple_package_excludes) -if(APPLE) - set(_apple_package_excludes - SOFA - ) -endif() - set(_python_excludes ) if(NOT (CMAKE_SIZEOF_VOID_P EQUAL 8) ) set(_python_excludes Python Numpy ) endif() set(_package_excludes ${_apple_package_excludes} ${_python_excludes} Gflags Caffe Caffe2 OpenCL SYSTEM_Boost Boost_LIBRARIES SYSTEM_PYTHON - SOFA_PLUGINS - SOFA_PLUGINS_DIR SUPERBUILD BiophotonicsHardware_SpectroCam POLHEMUS_TRACKER US_DiPhAS_SDK GALIL_HARDWARE OPHIR_PRYO_HARDWARE KWSTYLE MICROBIRD_TRACKER MICROBIRD_TRACKER_INCLUDE_DIR MICROBIRD_TRACKER_LIB MICRON_TRACKER OPTITRACK_TRACKER SPACENAVIGATOR TOF_KINECT TOF_KINECTV2 TOF_MESASR4000 TOF_PMDCAMBOARD TOF_PMDCAMCUBE TOF_PMDO3 US_TELEMED_SDK videoInput WIIMOTE ) get_cmake_property(_cache_vars CACHE_VARIABLES) foreach(_cache_var ${_cache_vars}) string(REGEX REPLACE "MITK_USE_(.+)" "\\1" _package "${_cache_var}") if(_package AND NOT _package STREQUAL _cache_var) list(FIND _package_excludes ${_package} _index) if(_index EQUAL -1) list(APPEND MITK_CONFIG_PACKAGES ${_package}) endif() endif() endforeach() set(MITK_BUILD_ALL_APPS ON CACHE BOOL "Build all MITK applications" FORCE) set(MITK_BUILD_ALL_PLUGINS ON CACHE BOOL "Build all MITK plugins" FORCE) set(MITK_BUILD_EXAMPLES ON CACHE BOOL "Build the MITK examples" FORCE) set(BLUEBERRY_BUILD_ALL_PLUGINS ON CACHE BOOL "Build all BlueBerry plugins" FORCE) set(BUILD_DiffusionCoreCmdApps ON CACHE BOOL "Build commandline tools for diffusion" FORCE) set(BUILD_DiffusionFiberProcessingCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber processing" FORCE) set(BUILD_DiffusionFiberfoxCmdApps ON CACHE BOOL "Build commandline tools for diffusion data simulation (Fiberfox)" FORCE) set(BUILD_DiffusionMiscCmdApps ON CACHE BOOL "Build miscellaneous commandline tools for diffusion" FORCE) set(BUILD_DiffusionQuantificationCmdApps ON CACHE BOOL "Build commandline tools for diffusion quantification (IVIM, ADC, ...)" FORCE) set(BUILD_DiffusionTractographyCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber tractography" FORCE) set(BUILD_DiffusionTractographyEvaluationCmdApps ON CACHE BOOL "Build commandline tools for diffusion fiber tractography evaluation" FORCE) set(BUILD_DiffusionConnectomicsCmdApps ON CACHE BOOL "Build commandline tools for diffusion connectomics" FORCE) diff --git a/CMake/FindVMTK.cmake b/CMake/FindVMTK.cmake deleted file mode 100644 index 0605cd8f15..0000000000 --- a/CMake/FindVMTK.cmake +++ /dev/null @@ -1,47 +0,0 @@ -include(FindPackageHandleStandardArgs) -include(SelectLibraryConfigurations) - -find_path(VMTK_INCLUDE_DIR - NAMES vtkvmtkConfigure.h - PATHS ${MITK_EXTERNAL_PROJECT_PREFIX} - PATH_SUFFIXES include/vmtk -) - -set(VMTK_LIBRARY_DIR "${MITK_EXTERNAL_PROJECT_PREFIX}/lib/vmtk") - -foreach(lib Common ComputationalGeometry DifferentialGeometry IO ITK Misc Segmentation) - string(TOUPPER ${lib} LIB) - if(NOT VMTK_${LIB}_LIBRARIES) - find_library(VMTK_${LIB}_LIBRARY_RELEASE vtkvmtk${lib} ${VMTK_LIBRARY_DIR}) - find_library(VMTK_${LIB}_LIBRARY_DEBUG vtkvmtk${lib}d ${VMTK_LIBRARY_DIR}) - select_library_configurations(VMTK_${LIB}) - endif() -endforeach() - -find_package_handle_standard_args(VMTK DEFAULT_MSG - VMTK_INCLUDE_DIR - VMTK_COMMON_LIBRARIES - VMTK_COMPUTATIONALGEOMETRY_LIBRARIES - VMTK_DIFFERENTIALGEOMETRY_LIBRARIES - VMTK_IO_LIBRARIES - VMTK_ITK_LIBRARIES - VMTK_MISC_LIBRARIES - VMTK_SEGMENTATION_LIBRARIES -) - -if(VMTK_FOUND) - set(VMTK_INCLUDE_DIRS ${VMTK_INCLUDE_DIR}) - set(VMTK_LIBRARIES - ${VMTK_COMMON_LIBRARIES} - ${VMTK_COMPUTATIONALGEOMETRY_LIBRARIES} - ${VMTK_DIFFERENTIALGEOMETRY_LIBRARIES} - ${VMTK_IO_LIBRARIES} - ${VMTK_ITK_LIBRARIES} - ${VMTK_MISC_LIBRARIES} - ${VMTK_SEGMENTATION_LIBRARIES} - ) -endif() - -mark_as_advanced( - VMTK_INCLUDE_DIR -) diff --git a/CMake/MITKDashboardSetup.cmake b/CMake/MITKDashboardSetup.cmake index 34a2f05048..4e6f4c48ce 100644 --- a/CMake/MITKDashboardSetup.cmake +++ b/CMake/MITKDashboardSetup.cmake @@ -1,161 +1,160 @@ # This file is intended to be included at the end of a custom MITKDashboardScript.TEMPLATE.cmake file list(APPEND CTEST_NOTES_FILES "${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}") # # Automatically determined properties # set(MY_OPERATING_SYSTEM ) if(UNIX) # Download a utility script if(IS_PHABRICATOR_URL) set(url "https://phabricator.mitk.org/source/mitk/browse/${GIT_BRANCH}/CMake/mitkDetectOS.sh?view=raw") else() set(url "https://raw.githubusercontent.com/MITK/MITK/master/CMake/mitkDetectOS.sh") endif() set(dest "${CTEST_SCRIPT_DIRECTORY}/mitkDetectOS.sh") downloadFile("${url}" "${dest}") execute_process(COMMAND sh "${dest}" RESULT_VARIABLE _result OUTPUT_VARIABLE _out OUTPUT_STRIP_TRAILING_WHITESPACE) if(NOT _result) set(MY_OPERATING_SYSTEM "${_out}") endif() endif() if(NOT MY_OPERATING_SYSTEM) set(MY_OPERATING_SYSTEM "${CMAKE_HOST_SYSTEM}") # Windows 7, Linux-2.6.32, Darwin... endif() site_name(CTEST_SITE) if(NOT DEFINED MITK_USE_Qt5) set(MITK_USE_Qt5 1) endif() if(MITK_USE_Qt5) if(NOT QT_QMAKE_EXECUTABLE) find_program(QT_QMAKE_EXECUTABLE NAMES qmake qmake-qt5 HINTS ${QT_BINARY_DIR}) endif() execute_process(COMMAND ${QT_QMAKE_EXECUTABLE} --version OUTPUT_VARIABLE MY_QT_VERSION RESULT_VARIABLE qmake_error) if(qmake_error) message(FATAL_ERROR "Error when executing ${QT_QMAKE_EXECUTABLE} --version\n${qmake_error}") endif() string(REGEX REPLACE ".*Qt version ([0-9.]+) .*" "\\1" MY_QT_VERSION ${MY_QT_VERSION}) endif() # # Project specific properties # if(NOT CTEST_BUILD_NAME) if(MITK_USE_Qt5) set(CTEST_BUILD_NAME "${MY_OPERATING_SYSTEM} ${MY_COMPILER} Qt${MY_QT_VERSION} ${CTEST_BUILD_CONFIGURATION}") else() set(CTEST_BUILD_NAME "${MY_OPERATING_SYSTEM} ${MY_COMPILER} ${CTEST_BUILD_CONFIGURATION}") endif() set(CTEST_BUILD_NAME "${CTEST_BUILD_NAME}${CTEST_BUILD_NAME_SUFFIX}") endif() set(PROJECT_BUILD_DIR "MITK-build") set(CTEST_PATH "$ENV{PATH}") if(WIN32) if("${CTEST_CMAKE_GENERATOR}" MATCHES ".*Win64") set(CMAKE_LIBRARY_ARCHITECTURE x64) else() set(CMAKE_LIBRARY_ARCHITECTURE x86) endif() string(SUBSTRING "${MY_COMPILER}" 2 2 vc_version) set(OPENCV_BIN_DIR "${CTEST_BINARY_DIRECTORY}/ep/${CMAKE_LIBRARY_ARCHITECTURE}/vc${vc_version}/bin") - set(SOFA_BINARY_DIR "${CTEST_BINARY_DIRECTORY}/ep/src/SOFA-build/bin/${CTEST_BUILD_CONFIGURATION}") set(BLUEBERRY_RUNTIME_DIR "${CTEST_BINARY_DIRECTORY}/MITK-build/bin/plugins/${CTEST_BUILD_CONFIGURATION}") set(PYTHON_BINARY_DIRS "${CTEST_BINARY_DIRECTORY}/ep/src/CTK-build/CMakeExternals/Install/bin") list(APPEND PYTHON_BINARY_DIRS "${CTEST_BINARY_DIRECTORY}/ep/lib/python2.7/bin") - set(CTEST_PATH "${CTEST_PATH};${CTEST_BINARY_DIRECTORY}/ep/bin;${QT_BINARY_DIR};${SOFA_BINARY_DIR};${BLUEBERRY_RUNTIME_DIR};${OPENCV_BIN_DIR};${PYTHON_BINARY_DIRS}") + set(CTEST_PATH "${CTEST_PATH};${CTEST_BINARY_DIRECTORY}/ep/bin;${QT_BINARY_DIR};${BLUEBERRY_RUNTIME_DIR};${OPENCV_BIN_DIR};${PYTHON_BINARY_DIRS}") endif() set(ENV{PATH} "${CTEST_PATH}") # If the dashscript doesn't define a GIT_REPOSITORY variable, let's define it here. if(NOT DEFINED GIT_REPOSITORY OR GIT_REPOSITORY STREQUAL "") set(GIT_REPOSITORY "https://phabricator.mitk.org/source/mitk.git") endif() # # Display build info # message("Site name: ${CTEST_SITE}") message("Build name: ${CTEST_BUILD_NAME}") message("Script Mode: ${SCRIPT_MODE}") message("Coverage: ${WITH_COVERAGE}, MemCheck: ${WITH_MEMCHECK}") # # Set initial cache options # if(CTEST_CMAKE_GENERATOR MATCHES ".*Makefiles.*") set(CTEST_USE_LAUNCHERS 1) else() set(CTEST_USE_LAUNCHERS 0) endif() set(ENV{CTEST_USE_LAUNCHERS_DEFAULT} ${CTEST_USE_LAUNCHERS}) # Remove this if block after all dartclients work if(DEFINED ADDITIONNAL_CMAKECACHE_OPTION) message(WARNING "Rename ADDITIONNAL to ADDITIONAL in your dartlclient script: ${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}") set(ADDITIONAL_CMAKECACHE_OPTION ${ADDITIONNAL_CMAKECACHE_OPTION}) endif() if(NOT DEFINED MITK_BUILD_CONFIGURATION) set(MITK_BUILD_CONFIGURATION "All") endif() if(NOT DEFINED MITK_VTK_DEBUG_LEAKS) set(MITK_VTK_DEBUG_LEAKS 1) endif() set(INITIAL_CMAKECACHE_OPTIONS " SUPERBUILD_EXCLUDE_MITKBUILD_TARGET:BOOL=TRUE MITK_BUILD_CONFIGURATION:STRING=${MITK_BUILD_CONFIGURATION} MITK_VTK_DEBUG_LEAKS:BOOL=${MITK_VTK_DEBUG_LEAKS} ${ADDITIONAL_CMAKECACHE_OPTION} ") if(MITK_USE_Qt5) set(INITIAL_CMAKECACHE_OPTIONS "${INITIAL_CMAKECACHE_OPTIONS} QT_QMAKE_EXECUTABLE:FILEPATH=${QT_QMAKE_EXECUTABLE}") endif() # Write a cache file for populating the MITK initial cache (not the superbuild cache). # This can be used to provide variables which are not passed through the # superbuild process to the MITK configure step) if(MITK_INITIAL_CACHE) set(mitk_cache_file "${CTEST_SCRIPT_DIRECTORY}/mitk_initial_cache.txt") file(WRITE "${mitk_cache_file}" "${MITK_INITIAL_CACHE}") set(INITIAL_CMAKECACHE_OPTIONS "${INITIAL_CMAKECACHE_OPTIONS} MITK_INITIAL_CACHE_FILE:INTERNAL=${mitk_cache_file} ") endif() # # Download and include dashboard driver script # if(IS_PHABRICATOR_URL) set(url "https://phabricator.mitk.org/source/mitk/browse/${GIT_BRANCH}/CMake/MITKDashboardDriverScript.cmake?view=raw") else() set(url "https://raw.githubusercontent.com/MITK/MITK/master/CMake/MITKDashboardDriverScript.cmake") endif() set(dest ${CTEST_SCRIPT_DIRECTORY}/${CTEST_SCRIPT_NAME}.driver) downloadFile("${url}" "${dest}") include(${dest}) diff --git a/CMake/PackageDepends/MITK_GLEW_Config.cmake b/CMake/PackageDepends/MITK_GLEW_Config.cmake deleted file mode 100644 index 3e14033389..0000000000 --- a/CMake/PackageDepends/MITK_GLEW_Config.cmake +++ /dev/null @@ -1,4 +0,0 @@ -list(APPEND ALL_LIBRARIES ${GLEW_LIBRARIES}) -if(GLEW_INCLUDE_DIRS) - list(APPEND ALL_INCLUDE_DIRECTORIES ${GLEW_INCLUDE_DIRS}) -endif() diff --git a/CMake/PackageDepends/MITK_SOFA_Config.cmake b/CMake/PackageDepends/MITK_SOFA_Config.cmake deleted file mode 100644 index 96c12a5bd2..0000000000 --- a/CMake/PackageDepends/MITK_SOFA_Config.cmake +++ /dev/null @@ -1,2 +0,0 @@ -list(APPEND ALL_INCLUDE_DIRECTORIES ${SOFA_INCLUDE_DIRS}) -list(APPEND ALL_LIBRARIES ${SOFA_LIBRARIES}) diff --git a/CMake/PackageDepends/MITK_VMTK_Config.cmake b/CMake/PackageDepends/MITK_VMTK_Config.cmake deleted file mode 100644 index e0022af2b8..0000000000 --- a/CMake/PackageDepends/MITK_VMTK_Config.cmake +++ /dev/null @@ -1,2 +0,0 @@ -list(APPEND ALL_INCLUDE_DIRECTORIES ${VMTK_INCLUDE_DIRS}) -list(APPEND ALL_LIBRARIES ${VMTK_LIBRARIES}) diff --git a/CMake/mitkFunctionGetLibrarySearchPaths.cmake b/CMake/mitkFunctionGetLibrarySearchPaths.cmake index f172bce679..54b5f12c83 100644 --- a/CMake/mitkFunctionGetLibrarySearchPaths.cmake +++ b/CMake/mitkFunctionGetLibrarySearchPaths.cmake @@ -1,168 +1,161 @@ function(mitkFunctionGetLibrarySearchPaths search_path intermediate_dir) set(_dir_candidates "${MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY}" "${MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY}/plugins" "${MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY}" "${MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY}/plugins" ) if(MITK_EXTERNAL_PROJECT_PREFIX) list(APPEND _dir_candidates "${MITK_EXTERNAL_PROJECT_PREFIX}/bin" "${MITK_EXTERNAL_PROJECT_PREFIX}/lib" ) endif() # Determine the Qt5 library installation prefix set(_qmake_location ) if(MITK_USE_Qt5 AND TARGET ${Qt5Core_QMAKE_EXECUTABLE}) get_property(_qmake_location TARGET ${Qt5Core_QMAKE_EXECUTABLE} PROPERTY IMPORT_LOCATION) endif() if(_qmake_location) if(NOT _qt_install_libs) if(WIN32) execute_process(COMMAND ${_qmake_location} -query QT_INSTALL_BINS OUTPUT_VARIABLE _qt_install_libs OUTPUT_STRIP_TRAILING_WHITESPACE) else() execute_process(COMMAND ${_qmake_location} -query QT_INSTALL_LIBS OUTPUT_VARIABLE _qt_install_libs OUTPUT_STRIP_TRAILING_WHITESPACE) endif() file(TO_CMAKE_PATH "${_qt_install_libs}" _qt_install_libs) set(_qt_install_libs ${_qt_install_libs} CACHE INTERNAL "Qt library installation prefix" FORCE) endif() if(_qt_install_libs) list(APPEND _dir_candidates ${_qt_install_libs}) endif() elseif(MITK_USE_Qt5) message(WARNING "The qmake executable could not be found.") endif() get_property(_additional_paths GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS) if(MITK_USE_HDF5) FIND_PACKAGE(HDF5 COMPONENTS C HL NO_MODULE REQUIRED shared) get_target_property(_location hdf5-shared LOCATION) get_filename_component(_location ${_location} PATH) list(APPEND _additional_paths ${_location}) # This is a work-around. The hdf5-config.cmake file is not robust enough # to be included several times via find_pakcage calls. set(HDF5_LIBRARIES ${HDF5_LIBRARIES} PARENT_SCOPE) endif() if(MITK_USE_Vigra) # we cannot use _find_package(Vigra) here because the vigra-config.cmake file # always includes the target-exports files without using an include guard. This # would lead to errors when another find_package(Vigra) call is processed. The # (bad) assumption here is that for the time being, only the Classification module # is using Vigra. if(UNIX) list(APPEND _additional_paths ${Vigra_DIR}/lib) else() list(APPEND _additional_paths ${Vigra_DIR}/bin) endif() endif() if(_additional_paths) list(APPEND _dir_candidates ${_additional_paths}) endif() # The code below is sub-optimal. It makes assumptions about # the structure of the build directories, pointed to by # the *_DIR variables. Instead, we should rely on package # specific "LIBRARY_DIRS" variables, if they exist. if(WIN32) - if(SOFA_DIR) - list(APPEND _dir_candidates "${SOFA_DIR}/bin") - endif() list(APPEND _dir_candidates "${ITK_DIR}/bin") - else() - if(SOFA_DIR) - list(APPEND _dir_candidates "${SOFA_DIR}/lib") - endif() endif() if(MITK_USE_MatchPoint) if(WIN32) list(APPEND _dir_candidates "${MatchPoint_DIR}/bin") else() list(APPEND _dir_candidates "${MatchPoint_DIR}/lib") endif() endif() if(OpenCV_DIR) set(_opencv_link_directories "${OpenCV_LIB_DIR_DBG}" "${OpenCV_LIB_DIR_OPT}" "${OpenCV_3RDPARTY_LIB_DIR_DBG}" "${OpenCV_3RDPARTY_LIB_DIR_OPT}") list(REMOVE_DUPLICATES _opencv_link_directories) if(WIN32) foreach(_opencv_link_directory ${_opencv_link_directories}) list(APPEND _dir_candidates "${_opencv_link_directory}/../bin") endforeach() else() list(APPEND _dir_candidates ${_opencv_link_directories}) endif() endif() if(MITK_USE_Python) list(APPEND _dir_candidates "${CTK_DIR}/CMakeExternals/Install/bin") list(APPEND _dir_candidates "${MITK_EXTERNAL_PROJECT_PREFIX}/lib/python2.7/bin") endif() if(MITK_USE_TOF_PMDO3 OR MITK_USE_TOF_PMDCAMCUBE OR MITK_USE_TOF_PMDCAMBOARD) list(APPEND _dir_candidates "${MITK_PMD_SDK_DIR}/plugins" "${MITK_PMD_SDK_DIR}/bin") endif() if(MITK_USE_CTK) list(APPEND _dir_candidates "${CTK_LIBRARY_DIRS}") foreach(_ctk_library ${CTK_LIBRARIES}) if(${_ctk_library}_LIBRARY_DIRS) list(APPEND _dir_candidates "${${_ctk_library}_LIBRARY_DIRS}") endif() endforeach() endif() if(MITK_USE_BLUEBERRY) if(DEFINED CTK_PLUGIN_RUNTIME_OUTPUT_DIRECTORY) if(IS_ABSOLUTE "${CTK_PLUGIN_RUNTIME_OUTPUT_DIRECTORY}") list(APPEND _dir_candidates "${CTK_PLUGIN_RUNTIME_OUTPUT_DIRECTORY}") else() list(APPEND _dir_candidates "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${CTK_PLUGIN_RUNTIME_OUTPUT_DIRECTORY}") endif() endif() endif() if(MITK_LIBRARY_DIRS) list(APPEND _dir_candidates ${MITK_LIBRARY_DIRS}) endif() list(REMOVE_DUPLICATES _dir_candidates) set(_search_dirs ) foreach(_dir ${_dir_candidates}) if(EXISTS "${_dir}/${intermediate_dir}") list(APPEND _search_dirs "${_dir}/${intermediate_dir}") else() list(APPEND _search_dirs "${_dir}") endif() endforeach() # Special handling for "internal" search dirs. The intermediate directory # might not have been created yet, so we can't check for its existence. # Hence we just add it for Windows without checking. set(_internal_search_dirs "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}" "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/plugins") if(WIN32) foreach(_dir ${_internal_search_dirs}) set(_search_dirs "${_dir}/${intermediate_dir}" ${_search_dirs}) endforeach() else() set(_search_dirs ${_internal_search_dirs} ${_search_dirs}) endif() list(REMOVE_DUPLICATES _search_dirs) set(${search_path} ${_search_dirs} PARENT_SCOPE) endfunction() diff --git a/CMake/mitkMacroFindDependency.cmake b/CMake/mitkMacroFindDependency.cmake index cf372f1e18..f6c579c176 100644 --- a/CMake/mitkMacroFindDependency.cmake +++ b/CMake/mitkMacroFindDependency.cmake @@ -1,55 +1,53 @@ #! Wraps a find_package call by forwarding QUIET and REQUIRED arguments #! from within the MITKConfig.cmake file. #! #! mitkMacroFindDependency( [args]) #! macro(mitkMacroFindDependency dep) set(_mitk_fd_dep ${dep}) if(NOT _mitk_fd_dep) message(FATAL_ERROR "Missing argument.") endif() string(TOUPPER "${_mitk_fd_dep}" _mitk_fd_dep_uc) if(${CMAKE_FIND_PACKAGE_NAME}_FIND_QUIETLY) set(_mitk_fd_quiet_arg QUIET) endif() set(_mitk_fd_required_arg) if(${CMAKE_FIND_PACKAGE_NAME}_FIND_REQUIRED) set(_mitk_fd_required_arg REQUIRED) endif() get_property(_mitk_fd_is_transitive GLOBAL PROPERTY _CMAKE_${_mitk_fd_dep}_TRANSITIVE_DEPENDENCY ) # Prefer config mode first because it finds external # Config.cmake files pointed at by _DIR variables. # Otherwise, existing Find.cmake files could fail. - # (e.g. in the case of GLEW and the FindGLEW.cmake file shipped - # with CMake). find_package(${_mitk_fd_dep} ${ARGN} QUIET CONFIG ) if(NOT (${_mitk_fd_dep}_FOUND OR ${_mitk_fd_dep_uc}_FOUND)) find_package(${_mitk_fd_dep} ${ARGN} ${cmake_fd_quiet_arg} ${cmake_fd_required_arg} ) endif() if(NOT DEFINED _mitk_fd_is_transitive OR _mitk_fd_is_transitive) set_property(GLOBAL PROPERTY _CMAKE_${_mitk_fd_dep}_TRANSITIVE_DEPENDENCY TRUE) endif() if (NOT (${_mitk_fd_dep}_FOUND OR ${_mitk_fd_dep_uc}_FOUND)) set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE "${CMAKE_FIND_PACKAGE_NAME} could not be found because dependency ${_mitk_fd_dep} could not be found.") set(${CMAKE_FIND_PACKAGE_NAME}_FOUND False) return() endif() set(_mitk_fd_required_arg) set(_mitk_fd_quiet_arg) endmacro() diff --git a/CMakeExternals/Boost.cmake b/CMakeExternals/Boost.cmake index 1cbaaeb88e..fe7c2fdeb9 100644 --- a/CMakeExternals/Boost.cmake +++ b/CMakeExternals/Boost.cmake @@ -1,205 +1,197 @@ #----------------------------------------------------------------------------- # Boost #----------------------------------------------------------------------------- include(mitkFunctionGetMSVCVersion) # Sanity checks if(DEFINED BOOST_ROOT AND NOT EXISTS ${BOOST_ROOT}) message(FATAL_ERROR "BOOST_ROOT variable is defined but corresponds to non-existing directory") endif() string(REPLACE "^^" ";" MITK_USE_Boost_LIBRARIES "${MITK_USE_Boost_LIBRARIES}") set(proj Boost) set(proj_DEPENDENCIES ) set(Boost_DEPENDS ${proj}) if(NOT DEFINED BOOST_ROOT AND NOT MITK_USE_SYSTEM_Boost) set(_boost_version 1_64) set(_boost_install_include_dir include/boost) if(WIN32) set(_boost_install_include_dir include/boost-${_boost_version}/boost) endif() set(_boost_libs ) set(_with_boost_libs ) set(_install_lib_dir ) # Set the boost root to the libraries install directory set(BOOST_ROOT "${ep_prefix}") if(MITK_USE_Boost_LIBRARIES) string(REPLACE ";" "," _boost_libs "${MITK_USE_Boost_LIBRARIES}") foreach(_boost_lib ${MITK_USE_Boost_LIBRARIES}) list(APPEND _with_boost_libs ${_with_boost_libs} --with-${_boost_lib}) endforeach() endif() if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(_boost_address_model "address-model=64") else() set(_boost_address_model "address-model=32") endif() if(WIN32) set(_shell_extension .bat) set(_boost_layout) if(MSVC) mitkFunctionGetMSVCVersion() set(_boost_with_toolset "vc${VISUAL_STUDIO_VERSION_MAJOR}") if(${VISUAL_STUDIO_VERSION_MINOR}) set(_boost_with_toolset "${_boost_with_toolset}${VISUAL_STUDIO_VERSION_MINOR}") endif() set(_boost_toolset "msvc-${VISUAL_STUDIO_VERSION_MAJOR}.${VISUAL_STUDIO_VERSION_MINOR}") endif() set(_install_lib_dir "--libdir=/bin") set(WIN32_CMAKE_SCRIPT ${ep_prefix}/src/${proj}-cmake/MoveBoostLibsToLibDirForWindows.cmake) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/CMakeExternals/MoveBoostLibsToLibDirForWindows.cmake.in ${WIN32_CMAKE_SCRIPT} @ONLY) set(_windows_move_libs_cmd COMMAND ${CMAKE_COMMAND} -P ${WIN32_CMAKE_SCRIPT}) else() set(_shell_extension .sh) set(_boost_layout "--layout=tagged") endif() if(UNIX AND NOT APPLE) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") set(_boost_with_toolset "gcc") elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") set(_boost_with_toolset "clang") else() message(FATAL_ERROR "Compiler '${CMAKE_CXX_COMPILER_ID}' not supported. Use GNU or Clang instead.") endif() get_filename_component(_cxx_compiler_name "${CMAKE_CXX_COMPILER}" NAME) string(REGEX MATCH "^[0-9]+\\.[0-9]+" _compiler_version "${CMAKE_CXX_COMPILER_VERSION}") if(_cxx_compiler_name MATCHES "${_compiler_version}") set(_boost_toolset "${_boost_with_toolset}-${_compiler_version}") endif() endif() if(_boost_toolset) set(_boost_toolset "--toolset=${_boost_toolset}") endif() set (APPLE_SYSROOT_FLAG) if(APPLE) set(APPLE_CMAKE_SCRIPT ${ep_prefix}/src/${proj}-cmake/ChangeBoostLibsInstallNameForMac.cmake) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/CMakeExternals/ChangeBoostLibsInstallNameForMac.cmake.in ${APPLE_CMAKE_SCRIPT} @ONLY) set(_macos_change_install_name_cmd COMMAND ${CMAKE_COMMAND} -P ${APPLE_CMAKE_SCRIPT}) # Set OSX_SYSROOT if (NOT ${CMAKE_OSX_SYSROOT} STREQUAL "") set (APPLE_SYSROOT_FLAG --sysroot=${CMAKE_OSX_SYSROOT}) endif() endif() set(_boost_variant "$<$:debug>$<$:release>") set(_boost_link shared) if(NOT BUILD_SHARED_LIBS) set(_boost_link static) endif() set(_boost_cxxflags ) if(CMAKE_CXX_FLAGS OR MITK_CXX14_FLAG) set(_boost_cxxflags "cxxflags=${MITK_CXX14_FLAG} ${CMAKE_CXX_FLAGS}") endif() set(_boost_linkflags ) if(BUILD_SHARED_LIBS AND _install_rpath_linkflag) set(_boost_linkflags "linkflags=${_install_rpath_linkflag}") endif() set(_build_cmd "/b2" ${APPLE_SYSROOT_FLAG} ${_boost_toolset} ${_boost_layout} "--prefix=" ${_install_lib_dir} ${_with_boost_libs} # Use the option below to view the shell commands (for debugging) #-d+4 variant=${_boost_variant} link=${_boost_link} ${_boost_cxxflags} ${_boost_linkflags} ${_boost_address_model} threading=multi runtime-link=shared # Some distributions site config breaks boost build # For example on Gentoo: http://stackoverflow.com/questions/23013433/how-to-install-modular-boost --ignore-site-config -q ) if(MITK_USE_Boost_LIBRARIES) set(_boost_build_cmd BUILD_COMMAND ${_build_cmd} install ${_macos_change_install_name_cmd} ${_windows_move_libs_cmd}) else() set(_boost_build_cmd BUILD_COMMAND ${CMAKE_COMMAND} -E echo "copying Boost headers..." COMMAND ${CMAKE_COMMAND} -E copy_directory "/boost" "/${_boost_install_include_dir}") endif() - ExternalProject_Add(${proj}-download - URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/boost_${_boost_version}_0.7z - URL_MD5 ace404a1c6be8b74544a77b85f828d40 - CONFIGURE_COMMAND "" - BUILD_COMMAND "" - INSTALL_COMMAND "" - ) - ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} - SOURCE_DIR "${ep_prefix}/src/${proj}-download" - BINARY_DIR "${ep_prefix}/src/${proj}-download" - DOWNLOAD_COMMAND "" + URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/boost_${_boost_version}_0.7z + URL_MD5 ace404a1c6be8b74544a77b85f828d40 + BINARY_DIR "${ep_prefix}/src/${proj}" CONFIGURE_COMMAND "/bootstrap${_shell_extension}" --with-toolset=${_boost_with_toolset} --with-libraries=${_boost_libs} "--prefix=" ${_boost_build_cmd} INSTALL_COMMAND "" # done in BUILD_COMMAND - DEPENDS ${proj}-download ${proj_DEPENDENCIES} + DEPENDS ${proj_DEPENDENCIES} ) ExternalProject_Get_Property(${proj} install_dir) if(WIN32) set(BOOST_LIBRARYDIR "${install_dir}/lib") endif() # Manual install commands (for a MITK super-build install) # until the Boost CMake system is used. # We just copy the include directory install(DIRECTORY "${install_dir}/${_boost_install_include_dir}" DESTINATION "include" COMPONENT dev ) if(MITK_USE_Boost_LIBRARIES) # Copy the boost libraries file(GLOB _boost_libs "${install_dir}/lib/libboost*.so*" "${install_dir}/lib/libboost*.dylib") install(FILES ${_boost_libs} DESTINATION "lib" COMPONENT runtime) file(GLOB _boost_libs "${install_dir}/bin/libboost*.dll") install(FILES ${_boost_libs} DESTINATION "bin" COMPONENT runtime) file(GLOB _boost_libs "${install_dir}/lib/libboost*.lib" "${install_dir}/lib/libboost*.a") install(FILES ${_boost_libs} DESTINATION "lib" COMPONENT dev) endif() else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() diff --git a/CMakeExternals/GLEW.cmake b/CMakeExternals/GLEW.cmake deleted file mode 100644 index 689e0840c1..0000000000 --- a/CMakeExternals/GLEW.cmake +++ /dev/null @@ -1,48 +0,0 @@ -#----------------------------------------------------------------------------- -# GLEW -#----------------------------------------------------------------------------- - -# Sanity checks -if(DEFINED GLEW_DIR AND NOT EXISTS ${GLEW_DIR}) - message(FATAL_ERROR "GLEW_DIR variable is defined but corresponds to non-existing directory") -endif() - -set(proj GLEW) -set(proj_DEPENDENCIES ) -set(GLEW_DEPENDS ${proj}) - -if(NOT DEFINED GLEW_DIR) - - set(additional_args ) - if(CTEST_USE_LAUNCHERS) - list(APPEND additional_args - "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" - ) - endif() - - set(patch_cmd ${CMAKE_COMMAND} -Dproj:STRING=${proj} -Dproj_target:STRING=glew -P ${CMAKE_CURRENT_LIST_DIR}/GenerateDefaultCMakeBuildSystem.cmake) - - ExternalProject_Add(${proj} - LIST_SEPARATOR ${sep} - URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/glew-1.10.0.tgz - URL_MD5 2f09e5e6cb1b9f3611bcac79bc9c2d5d - PATCH_COMMAND ${patch_cmd} - CMAKE_GENERATOR ${gen} - CMAKE_ARGS - ${ep_common_args} - ${additional_args} - CMAKE_CACHE_ARGS - ${ep_common_cache_args} - CMAKE_CACHE_DEFAULT_ARGS - ${ep_common_cache_default_args} - DEPENDS ${proj_DEPENDENCIES} - ) - - set(GLEW_DIR ${ep_prefix}) - mitkFunctionInstallExternalCMakeProject(${proj}) - -else() - - mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") - -endif() diff --git a/CMakeExternals/GLEWCMakeLists.txt b/CMakeExternals/GLEWCMakeLists.txt deleted file mode 100644 index 9d40357764..0000000000 --- a/CMakeExternals/GLEWCMakeLists.txt +++ /dev/null @@ -1,67 +0,0 @@ -cmake_minimum_required(VERSION 2.8.4) - -project(GLEW) - -set(${PROJECT_NAME}_MAJOR_VERSION 1) -set(${PROJECT_NAME}_MINOR_VERSION 10) -set(${PROJECT_NAME}_PATCH_VERSION 0) -set(${PROJECT_NAME}_VERSION ${${PROJECT_NAME}_MAJOR_VERSION}.${${PROJECT_NAME}_MINOR_VERSION}.${${PROJECT_NAME}_PATCH_VERSION}) - -find_package(OpenGL REQUIRED) - -if(BUILD_SHARED_LIBS) - add_definitions(-DGLEW_BUILD) -else() - add_definitions(-DGLEW_STATIC) -endif() - -add_library(glew src/glew.c) - -set(include_dirs ${OPENGL_INCLUDE_DIR} ${GLEW_SOURCE_DIR}/include) -target_include_directories(glew - PUBLIC "$" - "$" -) -target_link_libraries(glew PUBLIC ${OPENGL_gl_LIBRARY}) -set_target_properties(glew PROPERTIES - SOVERSION ${${PROJECT_NAME}_VERSION}) - -set(${PROJECT_NAME}_LIBRARIES glew) - -# Install support - -install(TARGETS ${${PROJECT_NAME}_LIBRARIES} EXPORT ${PROJECT_NAME}_TARGETS - LIBRARY DESTINATION lib - ARCHIVE DESTINATION lib - RUNTIME DESTINATION bin -) -install(DIRECTORY include/GL - DESTINATION include -) - -# Config files -configure_file( - ${PROJECT_NAME}Config.cmake.in - ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake - @ONLY -) -configure_file( - ${CMAKE_CURRENT_SOURCE_DIR}/${PROJECT_NAME}ConfigVersion.cmake.in - ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake - @ONLY -) - -export(EXPORT ${PROJECT_NAME}_TARGETS - FILE ${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Targets.cmake -) - -set(config_package_location lib/cmake/${PROJECT_NAME}) -install(EXPORT ${PROJECT_NAME}_TARGETS - FILE ${PROJECT_NAME}Targets.cmake - DESTINATION ${config_package_location} -) -install(FILES - "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake" - "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake" - DESTINATION ${config_package_location} -) diff --git a/CMakeExternals/PatchSOFA-386a3a7+7568b4.cmake b/CMakeExternals/PatchSOFA-386a3a7+7568b4.cmake deleted file mode 100644 index 65b801ef9d..0000000000 --- a/CMakeExternals/PatchSOFA-386a3a7+7568b4.cmake +++ /dev/null @@ -1,231 +0,0 @@ -# Changes of cmake/dependencies.cmake are commented separately below - -set(path "cmake/dependencies.cmake") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) - -# Comment out add_subdirectory() commands that reference the SOFA applications -# directory - -string(REPLACE "add_subdirectory(\"\${SOFA_A" "#add_subdirectory(\"\${SOFA_A" CONTENTS ${CONTENTS}) - -# Rename tinyxml to SofaTinyXml since MITK has its own version of tinyxml and -# the same name lead to linker or runtime errors in the past - -string(REPLACE "\"tinyxml\"" "\"SofaTinyXml\"" CONTENTS ${CONTENTS}) - -# Use MITK's version of Eigen -string(REPLACE "RegisterProjects(\"eigen\" PATH \"\${SOFA-EXTERNAL_EIGEN_PATH}\" COMPILE_DEFINITIONS SOFA_HAVE_EIGEN2)" "add_library(eigen INTERFACE IMPORTED GLOBAL)\nset_property(TARGET eigen APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES \${SOFA-EXTERNAL_EIGEN_PATH})\nset(GLOBAL_PROJECT_DEPENDENCIES_COMPLETE_eigen 1 CACHE INTERNAL \"\" FORCE)\nlist(APPEND GLOBAL_INCLUDE_DIRECTORIES \"\${SOFA-EXTERNAL_EIGEN_PATH}\")" CONTENTS ${CONTENTS}) - -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -# Adjust tinyxml references (see above) - -set(path "framework/sofa/helper/CMakeLists.txt") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) -string(REPLACE "tinyxml" "SofaTinyXml" CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -set(path "modules/sofa/component/SofaBaseVisual/CMakeLists.txt") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) -string(REPLACE "tinyxml" "SofaTinyXml" CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -set(path "modules/sofa/component/SofaLoader/CMakeLists.txt") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) -string(REPLACE "tinyxml" "SofaTinyXml" CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -set(path "modules/sofa/simulation/common/CMakeLists.txt") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) -string(REPLACE "tinyxml" "SofaTinyXml" CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -# Changes of cmake/environment.cmake are commented separately below - -set(path "cmake/environment.cmake") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) - -# Allow setting SOFA_APPLICATIONS_PLUGINS_DIR from outside - -string(REPLACE "S_DIR}/plugins\" CACHE INTERNAL" "S_DIR}/plugins\" CACHE PATH" CONTENTS ${CONTENTS}) - -# Place binaries and libraries in different subfolders according to the build -# configuration - -string(REPLACE "DEBUG \"\${directory}" "DEBUG \"\${directory}/Debug" CONTENTS ${CONTENTS}) -string(REPLACE "RELEASE \"\${directory}" "RELEASE \"\${directory}/Release" CONTENTS ${CONTENTS}) -string(REPLACE "RELWITHDEBINFO \"\${directory}" "RELWITHDEBINFO \"\${directory}/RelWithDebInfo" CONTENTS ${CONTENTS}) -string(REPLACE "MINSIZEREL \"\${directory}" "MINSIZEREL \"\${directory}/MinSizeRel" CONTENTS ${CONTENTS}) - -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -# Binary directories in add_subdirectory() regarding external plugins have to be explicitly specified - -set(path "cmake/functions.cmake") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) -string(REPLACE "add_subdirectory(\"\${GLOBAL_PROJECT_PATH_\${projectName}}\")" -"if(\${GLOBAL_PROJECT_PATH_\${projectName}} MATCHES ^\${CMAKE_SOURCE_DIR}.*) - add_subdirectory(\"\${GLOBAL_PROJECT_PATH_\${projectName}}\") - else() - string(LENGTH \"\${SOFA_APPLICATIONS_PLUGINS_DIR}\" begin) - string(SUBSTRING \"\${GLOBAL_PROJECT_PATH_\${projectName}}\" \${begin} -1 subdir) - add_subdirectory(\"\${GLOBAL_PROJECT_PATH_\${projectName}}\" \"\${CMAKE_BINARY_DIR}/applications/plugins\${subdir}\") - endif()" -CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -# Remove SOFA's FindGLEW.cmake since we need the official FindGLEW.cmake to -# inject the MITK superbuild version of GLEW into SOFA - -file(REMOVE "cmake/Modules/FindGLEW.cmake") - -# Changes of cmake/externals.cmake are commented separately below - -set(path "cmake/externals.cmake") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) - -# Enhance GLUT and GLEW finding routine to regard externally injected GLUT and -# GLEW libraries - -string(REPLACE "set(GLUT_LIBRARIES \"freeglut\")" "find_package(GLUT REQUIRED)" CONTENTS ${CONTENTS}) -string(REPLACE "set(GLEW_LIBRARIES \"glew32\")" "find_package(GLEW REQUIRED)" CONTENTS ${CONTENTS}) -string(REPLACE "else()\n set(O" " list(APPEND GLOBAL_INCLUDE_DIRECTORIES \"\${GLUT_INCLUDE_DIRS}\" \"\${GLEW_INCLUDE_DIRS}\")\nelse()\n set(O" CONTENTS ${CONTENTS}) -string(REPLACE "GLUT REQUIRED" "GLUT REQUIRED CONFIG" CONTENTS ${CONTENTS}) -string(REPLACE "GLEW REQUIRED" "GLEW REQUIRED CONFIG" CONTENTS ${CONTENTS}) - -# Remove Boost binary graph dependency because it is not straight forward to -# compile on all plattforms and its header-only part is enough - -string(REPLACE "graph " "" CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -# Changes of CMakeLists.txt are commented separately below - -set(path "CMakeLists.txt") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) - -# Set CMake policies to prevent configure warnings - -string(REPLACE "set(SOLUTION_NAME" "if(POLICY CMP0039) - cmake_policy(SET CMP0039 OLD) -endif() - -if(POLICY CMP0043) - cmake_policy(SET CMP0043 OLD) - endif() - -if(POLICY CMP0054) - cmake_policy(SET CMP0054 OLD) -endif() - -set(SOLUTION_NAME" -CONTENTS ${CONTENTS}) - -# Use configure file (see below) - -string(REPLACE "\nendif()" "\nendif()\n\nconfigure_file(SOFAConfig.cmake.in SOFAConfig.cmake @ONLY)" CONTENTS ${CONTENTS}) - -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -# Do not define snprintf starting with Visual Studio 2015. - -set(path "framework/sofa/helper/system/config.h") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) -string(REPLACE "#define snprintf _snprintf" "#if (_MSC_VER < 1900)\n#define snprintf _snprintf\n#endif" CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -set(path "extlibs/miniFlowVR/src/ftlm/type.cpp") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) -string(REPLACE "#define snprintf _snprintf" "#if (_MSC_VER < 1900)\n#define snprintf _snprintf\n#endif" CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -# Include Eigen/Core in RigidMapping.inl. - -set(path "modules/sofa/component/mapping/RigidMapping.inl") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) -string(REPLACE "#include " "#include \n#include " CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -# Use unordered_map instead of hash_map. - -set(path "modules/sofa/component/container/SpatialGridContainer.h") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) -string(REPLACE "hash_map" "unordered_map" CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -set(path "modules/sofa/component/container/SpatialGridContainer.h") -file(STRINGS ${path} CONTENTS NEWLINE_CONSUME) -string(REPLACE "stdext" "std" CONTENTS ${CONTENTS}) -configure_file(${TEMPLATE_FILE} ${path} @ONLY) - -# Create SOFAConfig.cmake.in file to make SOFA findable through the config mode -# of find_package() - -file(WRITE "SOFAConfig.cmake.in" -"add_definitions(-DSOFA_XML_PARSER_TINYXML;-DTIXML_USE_STL;-DMINI_FLOWVR;-DSOFA_HAVE_BOOST;-DSOFA_HAVE_CSPARSE;-DSOFA_HAVE_DAG;-DSOFA_HAVE_EIGEN2;-DSOFA_HAVE_FREEGLUT;-DSOFA_HAVE_GLEW;-DSOFA_HAVE_METIS) - -set(SOFA_INCLUDE_DIRS \"@SOFA_EXTLIBS_DIR@/csparse;@SOFA_EXTLIBS_DIR@/eigen-3.2.1;@SOFA_EXTLIBS_DIR@/metis-5.1.0/include;@SOFA_EXTLIBS_DIR@/miniFlowVR/include;@SOFA_EXTLIBS_DIR@/newmat;@SOFA_EXTLIBS_DIR@/tinyxml;@SOFA_SRC_DIR@/framework;@SOFA_SRC_DIR@/modules\") - -if(WIN32) - set(SOFA_LIBRARY_DIRS \"@SOFA_LIB_DIR@\") - set(version \"_1_0\") -else() - set(SOFA_LIBRARY_DIRS \"@SOFA_LIB_DIR@/@CMAKE_BUILD_TYPE@\") - set(version \"\") -endif() - -set(SOFA_LIBRARIES - debug SofaBaseAnimationLoop\${version}d optimized SofaBaseAnimationLoop\${version} - debug SofaBaseCollision\${version}d optimized SofaBaseCollision\${version} - debug SofaBaseLinearSolver\${version}d optimized SofaBaseLinearSolver\${version} - debug SofaBaseMechanics\${version}d optimized SofaBaseMechanics\${version} - debug SofaBaseTopology\${version}d optimized SofaBaseTopology\${version} - debug SofaBaseVisual\${version}d optimized SofaBaseVisual\${version} - debug SofaBoundaryCondition\${version}d optimized SofaBoundaryCondition\${version} - debug SofaComponentAdvanced\${version}d optimized SofaComponentAdvanced\${version} - debug SofaComponentBase\${version}d optimized SofaComponentBase\${version} - debug SofaComponentCommon\${version}d optimized SofaComponentCommon\${version} - debug SofaComponentGeneral\${version}d optimized SofaComponentGeneral\${version} - debug SofaComponentMain\${version}d optimized SofaComponentMain\${version} - debug SofaComponentMisc\${version}d optimized SofaComponentMisc\${version} - debug SofaConstraint\${version}d optimized SofaConstraint\${version} - debug SofaCore\${version}d optimized SofaCore\${version} - debug SofaDefaultType\${version}d optimized SofaDefaultType\${version} - debug SofaDeformable\${version}d optimized SofaDeformable\${version} - debug SofaDenseSolver\${version}d optimized SofaDenseSolver\${version} - debug SofaEigen2Solver\${version}d optimized SofaEigen2Solver\${version} - debug SofaEngine\${version}d optimized SofaEngine\${version} - debug SofaEulerianFluid\${version}d optimized SofaEulerianFluid\${version} - debug SofaExplicitOdeSolver\${version}d optimized SofaExplicitOdeSolver\${version} - debug SofaExporter\${version}d optimized SofaExporter\${version} - debug SofaGraphComponent\${version}d optimized SofaGraphComponent\${version} - debug SofaHaptics\${version}d optimized SofaHaptics\${version} - debug SofaHelper\${version}d optimized SofaHelper\${version} - debug SofaImplicitOdeSolver\${version}d optimized SofaImplicitOdeSolver\${version} - debug SofaLoader\${version}d optimized SofaLoader\${version} - debug SofaMeshCollision\${version}d optimized SofaMeshCollision\${version} - debug SofaMisc\${version}d optimized SofaMisc\${version} - debug SofaMiscCollision\${version}d optimized SofaMiscCollision\${version} - debug SofaMiscEngine\${version}d optimized SofaMiscEngine\${version} - debug SofaMiscFem\${version}d optimized SofaMiscFem\${version} - debug SofaMiscForceField\${version}d optimized SofaMiscForceField\${version} - debug SofaMiscMapping\${version}d optimized SofaMiscMapping\${version} - debug SofaMiscSolver\${version}d optimized SofaMiscSolver\${version} - debug SofaMiscTopology\${version}d optimized SofaMiscTopology\${version} - debug SofaNonUniformFem\${version}d optimized SofaNonUniformFem\${version} - debug SofaObjectInteraction\${version}d optimized SofaObjectInteraction\${version} - debug SofaOpenglVisual\${version}d optimized SofaOpenglVisual\${version} - debug SofaPreconditioner\${version}d optimized SofaPreconditioner\${version} - debug SofaRigid\${version}d optimized SofaRigid\${version} - debug SofaSimpleFem\${version}d optimized SofaSimpleFem\${version} - debug SofaSimulationCommon\${version}d optimized SofaSimulationCommon\${version} - debug SofaSimulationGraph\${version}d optimized SofaSimulationGraph\${version} - debug SofaSimulationTree\${version}d optimized SofaSimulationTree\${version} - debug SofaSparseSolver\${version}d optimized SofaSparseSolver\${version} - debug SofaSphFluid\${version}d optimized SofaSphFluid\${version} - debug SofaTopologyMapping\${version}d optimized SofaTopologyMapping\${version} - debug SofaUserInteraction\${version}d optimized SofaUserInteraction\${version} - debug SofaValidation\${version}d optimized SofaValidation\${version} - debug SofaVolumetricData\${version}d optimized SofaVolumetricData\${version} - debug SofaTinyXml\${version}d optimized SofaTinyXml\${version} -)") diff --git a/CMakeExternals/SOFA.cmake b/CMakeExternals/SOFA.cmake deleted file mode 100644 index 870944f1f8..0000000000 --- a/CMakeExternals/SOFA.cmake +++ /dev/null @@ -1,114 +0,0 @@ -#----------------------------------------------------------------------------- -# SOFA -#----------------------------------------------------------------------------- - -if(MITK_USE_SOFA) - # Sanity checks - if(DEFINED SOFA_DIR AND NOT EXISTS ${SOFA_DIR}) - message(FATAL_ERROR "SOFA_DIR variable is defined but corresponds to non-existing directory") - endif() - - set(proj SOFA) - set(proj_DEPENDENCIES Boost Eigen GLEW) - set(SOFA_DEPENDS ${proj}) - - set(preconfigure_cmake_args - -DGLEW_DIR:PATH=${GLEW_DIR} - -DSOFA-APPLICATION_GENERATERIGID:BOOL=OFF - -DSOFA-APPLICATION_MODELER:BOOL=OFF - -DSOFA-APPLICATION_RUNSOFA:BOOL=OFF - -DSOFA-EXTERNAL_BOOST:BOOL=ON - -DSOFA-EXTERNAL_BOOST_PATH:PATH=${BOOST_LIBRARYDIR} - -DSOFA-EXTERNAL_CSPARSE:BOOL=ON - -DSOFA-EXTERNAL_EIGEN_PATH:PATH=${ep_prefix}/include/eigen3 - -DSOFA-EXTERNAL_GLEW:BOOL=ON - -DSOFA-EXTERNAL_PNG:BOOL=OFF - -DSOFA-EXTERNAL_ZLIB:BOOL=OFF - -DSOFA-LIB_COMPONENT_SPARSE_SOLVER:BOOL=ON - -DSOFA-LIB_GUI_GLUT:BOOL=OFF - -DSOFA-LIB_GUI_QT:BOOL=OFF - -DSOFA-LIB_GUI_QTVIEWER:BOOL=OFF - -DSOFA-TUTORIAL_COMPOSITE_OBJECT:BOOL=OFF - -DSOFA-TUTORIAL_MIXED_PENDULUM:BOOL=OFF - -DSOFA-TUTORIAL_ONE_PARTICLE:BOOL=OFF - -DSOFA-TUTORIAL_ONE_TETRAHEDRON:BOOL=OFF - ) - - if(NOT APPLE) - list(APPEND proj_DEPENDENCIES GLUT) - - list(APPEND preconfigure_cmake_args - -DSOFA-EXTERNAL_FREEGLUT:BOOL=ON - -DGLUT_DIR:PATH=${GLUT_DIR} - ) - endif() - - if(NOT MITK_USE_SYSTEM_Boost) - list(APPEND preconfigure_cmake_args - -DBoost_NO_SYSTEM_PATHS:BOOL=ON - -DBOOST_ROOT:PATH=${BOOST_ROOT} - -DBOOST_LIBRARYDIR:PATH=${BOOST_LIBRARYDIR} - -DBoost_ADDITIONAL_VERSIONS:STRING=1.64${sep}1.64.0 - ) - endif() - - if(MITK_USE_SOFA_PLUGINS_DIR) - list(APPEND preconfigure_cmake_args - -DSOFA_APPLICATIONS_PLUGINS_DIR:PATH=${MITK_USE_SOFA_PLUGINS_DIR} - ) - - foreach(plugin ${MITK_USE_SOFA_PLUGINS}) - string(TOUPPER ${plugin} plugin) - list(APPEND preconfigure_cmake_args - -DSOFA-PLUGIN_${plugin}:BOOL=ON - ) - endforeach() - endif() - - set(additional_cmake_args ) - if(CTEST_USE_LAUNCHERS) - list(APPEND additional_cmake_args - "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" - ) - endif() - - set(rev "386a3a7+7568b4") - - set(SOFA_PATCH_COMMAND ${CMAKE_COMMAND} -DTEMPLATE_FILE:FILEPATH=${MITK_SOURCE_DIR}/CMakeExternals/EmptyFileForPatching.dummy -P ${MITK_SOURCE_DIR}/CMakeExternals/PatchSOFA-${rev}.cmake) - set(SOFA_PRECONFIGURE_COMMAND ${CMAKE_COMMAND} -G${gen} ${ep_common_args} ${preconfigure_cmake_args} ${boost_cmake_args} ) - - if(NOT DEFINED SOFA_DIR) - ExternalProject_Add(${proj} - LIST_SEPARATOR ${sep} - URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/SOFA-${rev}.tar.gz - URL_MD5 45ba5a931855f06e30405a60229938ca - PATCH_COMMAND ${SOFA_PATCH_COMMAND} - INSTALL_COMMAND "" - CMAKE_GENERATOR ${gen} - CMAKE_ARGS - ${ep_common_args} - ${additional_cmake_args} - CMAKE_CACHE_ARGS - ${ep_common_cache_args} - CMAKE_CACHE_DEFAULT_ARGS - ${ep_common_cache_default_args} - DEPENDS ${proj_DEPENDENCIES} - ) - - ExternalProject_Add_Step(${proj} preconfigure - COMMAND ${SOFA_PRECONFIGURE_COMMAND} - WORKING_DIRECTORY - DEPENDEES patch - DEPENDERS configure - LOG 1 - ) - - # SOFA does not support "make install" yet - # set(SOFA_DIR ${ep_prefix} - ExternalProject_Get_Property(${proj} binary_dir) - set(SOFA_DIR ${binary_dir}) - - else() - mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") - endif() -endif() diff --git a/CMakeExternals/VMTK.cmake b/CMakeExternals/VMTK.cmake deleted file mode 100644 index 2686778d1b..0000000000 --- a/CMakeExternals/VMTK.cmake +++ /dev/null @@ -1,49 +0,0 @@ -#----------------------------------------------------------------------------- -# VMTK -#----------------------------------------------------------------------------- - -if(MITK_USE_VMTK) - set(proj VMTK) - set(proj_DEPENDENCIES ITK VTK) - set(${proj}_DEPENDS ${proj}) - - # Sanity checks - if(DEFINED ${proj}_DIR AND NOT EXISTS ${${proj}_DIR}) - message(FATAL_ERROR "${proj}_DIR variable is defined but corresponds to non-existing directory") - endif() - - if(NOT DEFINED ${proj}_DIR) - set(additional_cmake_args) - - if(CTEST_USE_LAUNCHERS) - list(APPEND additional_cmake_args - "-DCMAKE_PROJECT_VTK_VMTK_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" - ) - endif() - - ExternalProject_Add(${proj} - LIST_SEPARATOR ${sep} - URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/vtkVmtk-7fa3faf6.tar.bz2 - URL_MD5 278725a50a18591cc8e24f8aa81a6fc5 - PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/VMTK.patch - CMAKE_GENERATOR ${gen} - CMAKE_ARGS - ${ep_common_args} - ${additional_cmake_args} - -DVTK_VMTK_BUILD_STREAMTRACER:BOOL=OFF - -DVTK_VMTK_BUILD_TETGEN:BOOL=OFF - -DVTK_VMTK_WRAP_PYTHON:BOOL=OFF - -DHDF5_DIR:PATH=${HDF5_DIR} - CMAKE_CACHE_ARGS - ${ep_common_cache_args} - CMAKE_CACHE_DEFAULT_ARGS - ${ep_common_cache_default_args} - DEPENDS ${proj_DEPENDENCIES} - ) - - set(${proj}_DIR ${ep_prefix}) - mitkFunctionInstallExternalCMakeProject(${proj}) - else() - mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") - endif() -endif() diff --git a/CMakeExternals/VMTK.patch b/CMakeExternals/VMTK.patch deleted file mode 100644 index c08a57a223..0000000000 --- a/CMakeExternals/VMTK.patch +++ /dev/null @@ -1,25 +0,0 @@ -diff --git a/CMakeOptions.cmake b/CMakeOptions.cmake -index 17fc5b8..f788274 100644 ---- a/CMakeOptions.cmake -+++ b/CMakeOptions.cmake -@@ -16,6 +16,20 @@ IF ( NOT VTK_FOUND ) - ENDIF ( NOT VTK_FOUND ) - - # -+# Try to find GDCM and include its settings (otherwise complain) -+# -+IF ( NOT GDCM_FOUND ) -+ FIND_PACKAGE(GDCM REQUIRED) -+ INCLUDE(${GDCM_USE_FILE}) -+ENDIF ( NOT GDCM_FOUND ) -+ -+# -+# Try to find OpenCV which possibly is a dependency of ITK -+# -+FIND_PACKAGE(OpenCV) -+FIND_PACKAGE(HDF5) -+ -+# - # Try to find ITK and include its settings (otherwise complain) - # - IF ( NOT ITK_FOUND ) diff --git a/CMakeExternals/VTK.cmake b/CMakeExternals/VTK.cmake index 1e27a03e16..e1c02d0d21 100644 --- a/CMakeExternals/VTK.cmake +++ b/CMakeExternals/VTK.cmake @@ -1,117 +1,113 @@ #----------------------------------------------------------------------------- # VTK #----------------------------------------------------------------------------- if(WIN32) option(VTK_USE_SYSTEM_FREETYPE OFF) else(WIN32) option(VTK_USE_SYSTEM_FREETYPE ON) endif(WIN32) # Sanity checks if(DEFINED VTK_DIR AND NOT EXISTS ${VTK_DIR}) message(FATAL_ERROR "VTK_DIR variable is defined but corresponds to non-existing directory") endif() set(proj VTK) set(proj_DEPENDENCIES ) set(VTK_DEPENDS ${proj}) if(MITK_USE_HDF5) list(APPEND proj_DEPENDENCIES HDF5) endif() if(NOT DEFINED VTK_DIR) set(additional_cmake_args ) if(MINGW) set(additional_cmake_args -DCMAKE_USE_WIN32_THREADS:BOOL=ON -DCMAKE_USE_PTHREADS:BOOL=OFF -DVTK_USE_VIDEO4WINDOWS:BOOL=OFF # no header files provided by MinGW ) endif() # Optionally enable memory leak checks for any objects derived from vtkObject. This # will force unit tests to fail if they have any of these memory leaks. option(MITK_VTK_DEBUG_LEAKS OFF) mark_as_advanced(MITK_VTK_DEBUG_LEAKS) list(APPEND additional_cmake_args -DVTK_DEBUG_LEAKS:BOOL=${MITK_VTK_DEBUG_LEAKS} ) if(MITK_USE_Python) if(NOT MITK_USE_SYSTEM_PYTHON) list(APPEND proj_DEPENDENCIES Python) set(_vtk_install_python_dir -DVTK_INSTALL_PYTHON_MODULE_DIR:FILEPATH=${MITK_PYTHON_SITE_DIR}) else() set(_vtk_install_python_dir -DVTK_INSTALL_PYTHON_MODULE_DIR:PATH=${ep_prefix}/lib/python${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}/site-packages) endif() list(APPEND additional_cmake_args -DVTK_WRAP_PYTHON:BOOL=ON -DVTK_USE_TK:BOOL=OFF -DVTK_WINDOWS_PYTHON_DEBUGGABLE:BOOL=OFF -DPYTHON_EXECUTABLE:FILEPATH=${PYTHON_EXECUTABLE} -DPYTHON_INCLUDE_DIR:PATH=${PYTHON_INCLUDE_DIR} -DPYTHON_INCLUDE_DIR2:PATH=${PYTHON_INCLUDE_DIR2} -DPYTHON_LIBRARY:FILEPATH=${PYTHON_LIBRARY} ${_vtk_install_python_dir} ) else() list(APPEND additional_cmake_args -DVTK_WRAP_PYTHON:BOOL=OFF -DVTK_WINDOWS_PYTHON_DEBUGGABLE:BOOL=OFF ) endif() if(MITK_USE_Qt5) list(APPEND additional_cmake_args -DVTK_QT_VERSION:STRING=5 -DVTK_Group_Qt:BOOL=ON -DVTK_INSTALL_NO_QT_PLUGIN:BOOL=ON ) endif() if(CTEST_USE_LAUNCHERS) list(APPEND additional_cmake_args "-DCMAKE_PROJECT_${proj}_INCLUDE:FILEPATH=${CMAKE_ROOT}/Modules/CTestUseLaunchers.cmake" ) endif() - set(VTK_URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/VTK-7.0.0.tar.gz) - set(VTK_URL_MD5 5fe35312db5fb2341139b8e4955c367d) - ExternalProject_Add(${proj} LIST_SEPARATOR ${sep} - URL ${VTK_URL} - URL_MD5 ${VTK_URL_MD5} - PATCH_COMMAND ${PATCH_COMMAND} -N -p1 -i ${CMAKE_CURRENT_LIST_DIR}/VTK.patch + URL ${MITK_THIRDPARTY_DOWNLOAD_PREFIX_URL}/VTK-8.0.0.tar.gz + URL_MD5 8de89b8c7a729016ab7128da5e881cf4 CMAKE_GENERATOR ${gen} CMAKE_ARGS ${ep_common_args} -DVTK_WRAP_TCL:BOOL=OFF -DVTK_WRAP_PYTHON:BOOL=OFF -DVTK_WRAP_JAVA:BOOL=OFF -DVTK_USE_SYSTEM_FREETYPE:BOOL=${VTK_USE_SYSTEM_FREETYPE} -DVTK_LEGACY_REMOVE:BOOL=ON -DModule_vtkTestingRendering:BOOL=ON -DVTK_MAKE_INSTANTIATORS:BOOL=ON -DVTK_USE_CXX11_FEATURES:BOOL=ON - -DVTK_RENDERING_BACKEND:STRING=OpenGL + -DVTK_RENDERING_BACKEND:STRING=OpenGL2 ${additional_cmake_args} CMAKE_CACHE_ARGS ${ep_common_cache_args} CMAKE_CACHE_DEFAULT_ARGS ${ep_common_cache_default_args} DEPENDS ${proj_DEPENDENCIES} ) set(VTK_DIR ${ep_prefix}) mitkFunctionInstallExternalCMakeProject(${proj}) else() mitkMacroEmptyExternalProject(${proj} "${proj_DEPENDENCIES}") endif() diff --git a/CMakeExternals/VTK.patch b/CMakeExternals/VTK.patch deleted file mode 100644 index 26692c93c5..0000000000 --- a/CMakeExternals/VTK.patch +++ /dev/null @@ -1,60 +0,0 @@ -diff --git a/CMake/GenerateExportHeader.cmake b/CMake/GenerateExportHeader.cmake -index ecfae31..11e7fad 100644 ---- a/CMake/GenerateExportHeader.cmake -+++ b/CMake/GenerateExportHeader.cmake -@@ -163,10 +163,10 @@ endmacro() - macro(_test_compiler_hidden_visibility) - - if(CMAKE_COMPILER_IS_GNUCXX) -- execute_process(COMMAND ${CMAKE_C_COMPILER} ARGS --version -+ execute_process(COMMAND ${CMAKE_C_COMPILER} --version - OUTPUT_VARIABLE _gcc_version_info - ERROR_VARIABLE _gcc_version_info) -- string(REGEX MATCH "[345]\\.[0-9]\\.[0-9]*" -+ string(REGEX MATCH "[3456]\\.[0-9]\\.[0-9]*" - _gcc_version "${_gcc_version_info}") - # gcc on mac just reports: "gcc (GCC) 3.3 20030304 ..." without the - # patch level, handle this here: -@@ -175,13 +175,13 @@ macro(_test_compiler_hidden_visibility) - _gcc_version "${_gcc_version_info}") - endif() - -- if(${_gcc_version} VERSION_LESS "4.2") -+ if(_gcc_version VERSION_LESS "4.2") - set(GCC_TOO_OLD TRUE) - endif() - endif() - - if(CMAKE_CXX_COMPILER_ID MATCHES "Intel") -- execute_process(COMMAND ${CMAKE_CXX_COMPILER} ARGS -V -+ execute_process(COMMAND ${CMAKE_CXX_COMPILER} -V - OUTPUT_VARIABLE _intel_version_info - ERROR_VARIABLE _intel_version_info) - string(REGEX REPLACE ".*Version ([0-9]+(\\.[0-9]+)+).*" "\\1" -diff --git a/CMake/vtkCompilerExtras.cmake b/CMake/vtkCompilerExtras.cmake -index e39bd30..68c5980 100644 ---- a/CMake/vtkCompilerExtras.cmake -+++ b/CMake/vtkCompilerExtras.cmake -@@ -28,11 +28,11 @@ if(CMAKE_COMPILER_IS_GNUCXX) - endif() - - # Now check if we can use visibility to selectively export symbols -- execute_process(COMMAND ${CMAKE_C_COMPILER} ARGS --version -+ execute_process(COMMAND ${CMAKE_C_COMPILER} --version - OUTPUT_VARIABLE _gcc_version_info - ERROR_VARIABLE _gcc_version_info) - -- string (REGEX MATCH "[345]\\.[0-9]\\.[0-9]*" -+ string (REGEX MATCH "[3456]\\.[0-9]\\.[0-9]*" - _gcc_version "${_gcc_version_info}") - if(NOT _gcc_version) - string (REGEX REPLACE ".*\\(GCC\\).*([34]\\.[0-9]).*" "\\1.0" -@@ -44,7 +44,7 @@ if(CMAKE_COMPILER_IS_GNUCXX) - option(VTK_USE_GCC_VISIBILITY "Use GCC visibility support if available." OFF) - mark_as_advanced(VTK_USE_GCC_VISIBILITY) - -- if(${_gcc_version} VERSION_GREATER 4.2.0 AND BUILD_SHARED_LIBS -+ if(_gcc_version VERSION_GREATER 4.2.0 AND BUILD_SHARED_LIBS - AND HAVE_GCC_VISIBILITY AND VTK_USE_GCC_VISIBILITY - AND NOT MINGW AND NOT CYGWIN) - # Should only be set if GCC is newer than 4.2.0 diff --git a/CMakeLists.txt b/CMakeLists.txt index 1f470d2880..0d13b06d8e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,1397 +1,1356 @@ set(MITK_CMAKE_MINIMUM_REQUIRED_VERSION 3.5) cmake_minimum_required(VERSION ${MITK_CMAKE_MINIMUM_REQUIRED_VERSION}) #----------------------------------------------------------------------------- # See http://www.cmake.org/cmake/help/v3.5/manual/cmake-policies.7.html for details #----------------------------------------------------------------------------- set(project_policies ) foreach(policy ${project_policies}) if(POLICY ${policy}) cmake_policy(SET ${policy} NEW) endif() endforeach() #----------------------------------------------------------------------------- # Superbuild Option - Enabled by default #----------------------------------------------------------------------------- option(MITK_USE_SUPERBUILD "Build MITK and the projects it depends on via SuperBuild.cmake." ON) if(MITK_USE_SUPERBUILD) project(MITK-superbuild) set(MITK_SOURCE_DIR ${PROJECT_SOURCE_DIR}) set(MITK_BINARY_DIR ${PROJECT_BINARY_DIR}) else() project(MITK VERSION 2016.11.99) endif() #----------------------------------------------------------------------------- # Update CMake module path #------------------------------------------------------------------------------ set(MITK_CMAKE_DIR ${MITK_SOURCE_DIR}/CMake) set(CMAKE_MODULE_PATH ${MITK_CMAKE_DIR} ${CMAKE_MODULE_PATH} ) #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- # Standard CMake macros include(FeatureSummary) include(CTestUseLaunchers) include(CMakeParseArguments) include(FindPackageHandleStandardArgs) # MITK macros include(mitkFunctionGetGccVersion) include(mitkFunctionCheckCompilerFlags) include(mitkFunctionSuppressWarnings) # includes several functions include(mitkMacroEmptyExternalProject) include(mitkFunctionGenerateProjectXml) include(mitkFunctionEnableBuildConfiguration) include(mitkFunctionWhitelists) include(mitkFunctionAddExternalProject) SUPPRESS_VC_DEPRECATED_WARNINGS() #----------------------------------------------------------------------------- # Set a default build type if none was specified #----------------------------------------------------------------------------- if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) message(STATUS "Setting build type to 'Debug' as none was specified.") set(CMAKE_BUILD_TYPE Debug CACHE STRING "Choose the type of build." FORCE) # Set the possible values of build type for cmake-gui set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release" "MinSizeRel" "RelWithDebInfo") endif() #----------------------------------------------------------------------------- # Check miminum Mac OS X version #----------------------------------------------------------------------------- # The minimum supported Mac OS X version is 10.9. If you use a version less than 10.9, there is no guarantee that the build still works. if(APPLE) exec_program(sw_vers ARGS -productVersion OUTPUT_VARIABLE osx_version) if (osx_version VERSION_LESS "10.9") message(WARNING "Detected OS X version \"${osx_version}\" is not supported anymore. Minimum required OS X version is 10.9 or greater.") endif() if (CMAKE_OSX_DEPLOYMENT_TARGET AND CMAKE_OSX_DEPLOYMENT_TARGET VERSION_LESS 10.9) message(WARNING "Detected OS X deployment target \"${CMAKE_OSX_DEPLOYMENT_TARGET}\" is not supported anymore. Minimum required OS X version is 10.9 or greater.") endif() endif() #----------------------------------------------------------------------------- # Check miminum compiler versions #----------------------------------------------------------------------------- if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") # require at least gcc 4.9 as provided by ppa:ubuntu-toolchain-r/test for Ubuntu 14.04 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 4.9) message(FATAL_ERROR "GCC version must be at least 4.9 If you are using Ubuntu 14.04, you can easily install gcc and g++ 4.9 (or any later version available) in addition to your version ${CMAKE_CXX_COMPILER_VERSION}: sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt-get update sudo apt-get install gcc-4.9 g++-4.9 Make sure to explicitly specify these compilers when configuring MITK: CMAKE_C_COMPILER:FILEPATH=/usr/bin/gcc-4.9 CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/g++-4.9 For more information on the proposed PPA see the Toolchain Updates section of https://wiki.ubuntu.com/ToolChain.") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") # require at least clang 3.4 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 3.4) message(FATAL_ERROR "Clang version must be at least 3.4") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "AppleClang") # require at least clang 5.0 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0) message(FATAL_ERROR "Apple Clang version must be at least 5.0") endif() elseif("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") # require at least Visual Studio 2013 if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 18.0.40629.0) message(FATAL_ERROR "Microsoft Visual Studio 2013 Update 5 or newer required (MSVC 18.0.40629.0)") endif() else() message(WARNING "You are using an unsupported compiler! Compilation has only been tested with Clang (Linux or Apple), GCC and MSVC.") endif() if(CMAKE_COMPILER_IS_GNUCXX) mitkFunctionGetGccVersion(${CMAKE_CXX_COMPILER} GCC_VERSION) else() set(GCC_VERSION 0) endif() set(MITK_CXX_STANDARD 14) set(CMAKE_CXX_EXTENSIONS 0) set(CMAKE_CXX_STANDARD ${MITK_CXX_STANDARD}) set(CMAKE_CXX_STANDARD_REQUIRED 1) # This is necessary to avoid problems with compile feature checks. # CMAKE_CXX_STANDARD seems to only set the -std=c++14 flag for targets. # However, compile flag checks also need to be done with -std=c++14. # The MITK_CXX14_FLAG variable is also used for external projects # build during the MITK super-build. mitkFunctionCheckCompilerFlags("-std=c++14" MITK_CXX14_FLAG) #----------------------------------------------------------------------------- # Warn if source or build path is too long #----------------------------------------------------------------------------- if(WIN32) set(_src_dir_length_max 50) set(_bin_dir_length_max 50) if(MITK_USE_SUPERBUILD) set(_src_dir_length_max 34) # _src_dir_length_max - strlen(ep/src/ITK-build) set(_bin_dir_length_max 40) # _bin_dir_length_max - strlen(MITK-build) endif() string(LENGTH "${MITK_SOURCE_DIR}" _src_n) string(LENGTH "${MITK_BINARY_DIR}" _bin_n) # The warnings should be converted to errors if(_src_n GREATER _src_dir_length_max) message(WARNING "MITK source code directory path length is too long (${_src_n} > ${_src_dir_length_max})." "Please move the MITK source code directory to a directory with a shorter path." ) endif() if(_bin_n GREATER _bin_dir_length_max) message(WARNING "MITK build directory path length is too long (${_bin_n} > ${_bin_dir_length_max})." "Please move the MITK build directory to a directory with a shorter path." ) endif() endif() #----------------------------------------------------------------------------- # Additional MITK Options (also shown during superbuild) #----------------------------------------------------------------------------- macro(env_option name doc value) set(_value $ENV{${name}}) if("${_value}" STREQUAL "") set(_value ${value}) endif() option(${name} "${doc}" ${_value}) endmacro() # ----------------------------------------- # General build options option(BUILD_SHARED_LIBS "Build MITK with shared libraries" ON) option(WITH_COVERAGE "Enable/Disable coverage" OFF) option(BUILD_TESTING "Test the project" ON) env_option(MITK_BUILD_ALL_APPS "Build all MITK applications" OFF) env_option(MITK_BUILD_EXAMPLES "Build the MITK Examples" OFF) option(MITK_ENABLE_PIC_READER "Enable support for reading the DKFZ pic file format." ON) mark_as_advanced(MITK_BUILD_ALL_APPS MITK_ENABLE_PIC_READER ) # ----------------------------------------- # Qt version related variables env_option(MITK_USE_Qt5 "Use Qt 5 library" ON) env_option(MITK_USE_Qt5_WebEngine "Use Qt 5 WebEngine library" ON) if(MITK_USE_Qt5) set(MITK_QT5_MINIMUM_VERSION 5.6.0) set(MITK_QT5_COMPONENTS Concurrent OpenGL PrintSupport Script Sql Svg Widgets Xml XmlPatterns UiTools Help LinguistTools) if(MITK_USE_Qt5_WebEngine) set(MITK_QT5_COMPONENTS ${MITK_QT5_COMPONENTS} WebEngineWidgets) endif() if(APPLE) set(MITK_QT5_COMPONENTS ${MITK_QT5_COMPONENTS} DBus) endif() find_package(Qt5 ${MITK_QT5_MINIMUM_VERSION} COMPONENTS ${MITK_QT5_COMPONENTS} REQUIRED) if(Qt5_DIR) get_filename_component(_Qt5_DIR "${Qt5_DIR}/../../../" ABSOLUTE) list(FIND CMAKE_PREFIX_PATH "${_Qt5_DIR}" _result) if(_result LESS 0) set(CMAKE_PREFIX_PATH "${_Qt5_DIR};${CMAKE_PREFIX_PATH}" CACHE PATH "" FORCE) endif() endif() elseif(MITK_USE_Qt5_WebEngine) set(MITK_USE_Qt5_WebEngine OFF) endif() # ------------------------------------------------------------------------ # Register external projects which can be build with the MITK superbuild # system. Each mitkFunctionAddExternalProject() call registers an external # project for which a CMakeExternals/.cmake file must exist. The # call also creates a MITK_USE_ variable (appearing in the CMake # UI if the NO_CACHE option is *not* given). # ----------------------------------------- # Optional external projects with no # inter-dependencies set_property(GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS "") mitkFunctionAddExternalProject(NAME Poco ON COMPONENTS Foundation Net Util XML Zip) mitkFunctionAddExternalProject(NAME DCMTK ON DOC "EXPERIMENTAL, superbuild only: Use DCMTK in MITK") mitkFunctionAddExternalProject(NAME OpenIGTLink OFF) mitkFunctionAddExternalProject(NAME tinyxml ON ADVANCED) mitkFunctionAddExternalProject(NAME GDCM ON ADVANCED) mitkFunctionAddExternalProject(NAME GLUT OFF ADVANCED) mitkFunctionAddExternalProject(NAME Raptor2 OFF ADVANCED) mitkFunctionAddExternalProject(NAME Eigen ON ADVANCED DOC "Use the Eigen library") -mitkFunctionAddExternalProject(NAME GLEW ON ADVANCED DOC "Use the GLEW library") mitkFunctionAddExternalProject(NAME ANN ON ADVANCED DOC "Use Approximate Nearest Neighbor Library") mitkFunctionAddExternalProject(NAME CppUnit ON ADVANCED DOC "Use CppUnit for unit tests") mitkFunctionAddExternalProject(NAME PCRE OFF ADVANCED NO_PACKAGE) mitkFunctionAddExternalProject(NAME ZLIB OFF ADVANCED NO_PACKAGE NO_CACHE) mitkFunctionAddExternalProject(NAME HDF5 ON ADVANCED) # ----------------------------------------- # The following external projects must be # ordered according to their # inter-dependencies mitkFunctionAddExternalProject(NAME SWIG OFF ADVANCED NO_PACKAGE DEPENDS PCRE) mitkFunctionAddExternalProject(NAME Python OFF NO_PACKAGE DEPENDS SWIG DOC "Use Python wrapping in MITK") mitkFunctionAddExternalProject(NAME Numpy OFF ADVANCED NO_PACKAGE) mitkFunctionAddExternalProject(NAME OpenCV OFF) mitkFunctionAddExternalProject(NAME Vigra OFF DEPENDS HDF5) # These are "hard" dependencies and always set to ON mitkFunctionAddExternalProject(NAME ITK ON NO_CACHE DEPENDS HDF5) mitkFunctionAddExternalProject(NAME VTK ON NO_CACHE) mitkFunctionAddExternalProject(NAME Boost ON NO_CACHE) mitkFunctionAddExternalProject(NAME SimpleITK OFF DEPENDS ITK GDCM SWIG) mitkFunctionAddExternalProject(NAME ACVD OFF DOC "Use Approximated Centroidal Voronoi Diagrams") mitkFunctionAddExternalProject(NAME CTK ON DEPENDS Qt5 DCMTK DOC "Use CTK in MITK") mitkFunctionAddExternalProject(NAME Rasqal OFF DEPENDS Raptor2 PCRE ADVANCED) mitkFunctionAddExternalProject(NAME Redland OFF DEPENDS Rasqal DOC "Use the Redland RDF library") -mitkFunctionAddExternalProject(NAME SOFA OFF DEPENDS GLUT Eigen Boost DOC "Use Simulation Open Framework Architecture") -mitkFunctionAddExternalProject(NAME VMTK OFF DEPENDS ITK VTK) mitkFunctionAddExternalProject(NAME DCMQI OFF DEPENDS DCMTK ITK DOC "Use dcmqi in MITK") mitkFunctionAddExternalProject(NAME MatchPoint OFF ADVANCED DEPENDS ITK DOC "Use the MatchPoint translation image registration library") if(MITK_USE_Qt5) mitkFunctionAddExternalProject(NAME Qwt ON ADVANCED DEPENDS Qt5) endif() if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") mitkFunctionAddExternalProject(NAME Gflags OFF ADVANCED DOC "Experimental. Only available on Linux systems. Needed for Caffe.") mitkFunctionAddExternalProject(NAME Caffe OFF ADVANCED DEPENDS HDF5 OpenCV Gflags DOC "Experimental. Only available on Linux systems.") mitkFunctionAddExternalProject(NAME Caffe2 OFF ADVANCED DOC "Experimental. Only available on Linux systems.") endif() # ----------------------------------------- # Other MITK_USE_* options not related to # external projects build via the # MITK superbuild env_option(MITK_USE_BLUEBERRY "Build the BlueBerry platform" ON) env_option(MITK_USE_OpenCL "Use OpenCL GPU-Computing library" OFF) #----------------------------------------------------------------------------- # Build configurations #----------------------------------------------------------------------------- set(_buildConfigs "Custom") file(GLOB _buildConfigFiles CMake/BuildConfigurations/*.cmake) foreach(_buildConfigFile ${_buildConfigFiles}) get_filename_component(_buildConfigFile ${_buildConfigFile} NAME_WE) list(APPEND _buildConfigs ${_buildConfigFile}) endforeach() set(MITK_BUILD_CONFIGURATION "Custom" CACHE STRING "Use pre-defined MITK configurations") set_property(CACHE MITK_BUILD_CONFIGURATION PROPERTY STRINGS ${_buildConfigs}) mitkFunctionEnableBuildConfiguration() mitkFunctionCreateWhitelistPaths(MITK) mitkFunctionFindWhitelists(MITK) # ----------------------------------------- # Custom dependency logic option(MITK_USE_SYSTEM_Boost "Use the system Boost" OFF) set(MITK_USE_Boost_LIBRARIES "" CACHE STRING "A semi-colon separated list of required Boost libraries") -if(MITK_USE_SOFA) - # SOFA requires boost system library - list(FIND MITK_USE_Boost_LIBRARIES system _result) - if(_result LESS 0) - message("> Adding 'system' to MITK_USE_Boost_LIBRARIES.") - list(APPEND MITK_USE_Boost_LIBRARIES system) - endif() - # SOFA requires boost thread library - list(FIND MITK_USE_Boost_LIBRARIES thread _result) - if(_result LESS 0) - message("> Adding 'thread' to MITK_USE_Boost_LIBRARIES.") - list(APPEND MITK_USE_Boost_LIBRARIES thread) - endif() - # Simulation plugin requires boost chrono library - list(FIND MITK_USE_Boost_LIBRARIES chrono _result) - if(_result LESS 0) - message("> Adding 'chrono' to MITK_USE_Boost_LIBRARIES.") - list(APPEND MITK_USE_Boost_LIBRARIES chrono) - endif() - set(MITK_USE_Boost_LIBRARIES ${MITK_USE_Boost_LIBRARIES} CACHE STRING "" FORCE) - # Allow setting external SOFA plugins directory and SOFA plugins - set(MITK_USE_SOFA_PLUGINS_DIR ${MITK_USE_SOFA_PLUGINS_DIR} CACHE PATH "External SOFA plugins directory" FORCE) - set(MITK_USE_SOFA_PLUGINS ${MITK_USE_SOFA_PLUGINS} CACHE PATH "List of semicolon-separated plugin names" FORCE) -endif() - # only windows can't build python in debug mode if(MITK_USE_Python AND "${CMAKE_BUILD_TYPE}" STREQUAL "Debug" AND WIN32) message(WARNING "Disabling Python support. Building MITK Python in debug mode on Windowsis not supported!") set(MITK_USE_Python OFF CACHE BOOL "Use python wrapping in MITK" FORCE) set(MITK_USE_Numpy OFF CACHE BOOL "Use Numpy" FORCE) set(MITK_USE_SimpleITK OFF CACHE BOOL "Use SimpleITK" FORCE) elseif(MITK_USE_Python) set(MITK_USE_ZLIB ON) if(NOT MITK_USE_Numpy) message("> Forcing MITK_USE_Numpy to ON because of MITK_USE_Python") set(MITK_USE_Numpy ON CACHE BOOL "Use Numpy" FORCE) endif() if(NOT MITK_USE_SimpleITK) message("> Forcing MITK_USE_SimpleITK to ON because of MITK_USE_Python") set(MITK_USE_SimpleITK ON CACHE BOOL "Use SimpleITK" FORCE) endif() option(MITK_USE_SYSTEM_PYTHON "Use the system python runtime" OFF) if(MITK_USE_SYSTEM_PYTHON) find_package(PythonLibs REQUIRED) find_package(PythonInterp REQUIRED) endif() elseif(MITK_USE_Python AND "${CMAKE_BUILD_TYPE}" STREQUAL "Debug" AND WIN32) message(WARNING "Disabling Python support. Building MITK Python in debug mode on Windowsis not supported!") set(MITK_USE_Python OFF CACHE BOOL "Use python wrapping in MITK" FORCE) endif() if(BUILD_TESTING AND NOT MITK_USE_CppUnit) message("> Forcing MITK_USE_CppUnit to ON because BUILD_TESTING=ON") set(MITK_USE_CppUnit ON CACHE BOOL "Use CppUnit for unit tests" FORCE) endif() if(MITK_USE_BLUEBERRY) option(MITK_BUILD_ALL_PLUGINS "Build all MITK plugins" OFF) mark_as_advanced(MITK_BUILD_ALL_PLUGINS) if(NOT MITK_USE_CTK) message("> Forcing MITK_USE_CTK to ON because of MITK_USE_BLUEBERRY") set(MITK_USE_CTK ON CACHE BOOL "Use CTK in MITK" FORCE) endif() endif() #----------------------------------------------------------------------------- # Pixel type multiplexing #----------------------------------------------------------------------------- # Customize the default pixel types for multiplex macros set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "itk::RGBPixel, itk::RGBAPixel" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros") set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") mark_as_advanced(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES MITK_ACCESSBYITK_DIMENSIONS ) # consistency checks if(NOT MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES) set(MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES "int, unsigned int, short, unsigned short, char, unsigned char" CACHE STRING "List of integral pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES) set(MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES "double, float" CACHE STRING "List of floating pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES) set(MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES "itk::RGBPixel, itk::RGBAPixel" CACHE STRING "List of composite pixel types used in AccessByItk and InstantiateAccessFunction macros" FORCE) endif() if(NOT MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES) string(REPLACE "," ";" _integral_types ${MITK_ACCESSBYITK_INTEGRAL_PIXEL_TYPES}) string(REPLACE "," ";" _floating_types ${MITK_ACCESSBYITK_FLOATING_PIXEL_TYPES}) foreach(_scalar_type ${_integral_types} ${_floating_types}) set(MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}itk::VariableLengthVector<${_scalar_type}>,") endforeach() string(LENGTH "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}" _length) math(EXPR _length "${_length} - 1") string(SUBSTRING "${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES}" 0 ${_length} MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES) set(MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES ${MITK_ACCESSBYITK_VECTOR_PIXEL_TYPES} CACHE STRING "List of vector pixel types used in AccessByItk and InstantiateAccessFunction macros for itk::VectorImage types" FORCE) endif() if(NOT MITK_ACCESSBYITK_DIMENSIONS) set(MITK_ACCESSBYITK_DIMENSIONS "2,3" CACHE STRING "List of dimensions used in AccessByItk and InstantiateAccessFunction macros") endif() #----------------------------------------------------------------------------- # Project.xml #----------------------------------------------------------------------------- # A list of topologically ordered targets set(CTEST_PROJECT_SUBPROJECTS) list(APPEND CTEST_PROJECT_SUBPROJECTS MITK-Core MITK-CoreUI MITK-IGT MITK-ToF MITK-DTI MITK-Modules # all modules not contained in a specific subproject MITK-Plugins # all plugins not contained in a specific subproject MITK-Examples Unlabeled # special "subproject" catching all unlabeled targets and tests ) # Configure CTestConfigSubProject.cmake that could be used by CTest scripts configure_file(${MITK_SOURCE_DIR}/CTestConfigSubProject.cmake.in ${MITK_BINARY_DIR}/CTestConfigSubProject.cmake) if(CTEST_PROJECT_ADDITIONAL_TARGETS) # those targets will be executed at the end of the ctest driver script # and they also get their own subproject label set(subproject_list "${CTEST_PROJECT_SUBPROJECTS};${CTEST_PROJECT_ADDITIONAL_TARGETS}") else() set(subproject_list "${CTEST_PROJECT_SUBPROJECTS}") endif() # Generate Project.xml file expected by the CTest driver script mitkFunctionGenerateProjectXml(${MITK_BINARY_DIR} MITK "${subproject_list}" ${MITK_USE_SUPERBUILD}) #----------------------------------------------------------------------------- # Superbuild script #----------------------------------------------------------------------------- if(MITK_USE_SUPERBUILD) include("${CMAKE_CURRENT_SOURCE_DIR}/SuperBuild.cmake") # Print configuration summary message("\n\n") feature_summary( DESCRIPTION "------- FEATURE SUMMARY FOR ${PROJECT_NAME} -------" WHAT ALL) return() endif() #***************************************************************************** #**************************** END OF SUPERBUILD **************************** #***************************************************************************** #----------------------------------------------------------------------------- # CMake function(s) and macro(s) #----------------------------------------------------------------------------- include(WriteBasicConfigVersionFile) include(CheckCXXSourceCompiles) include(GenerateExportHeader) include(mitkFunctionAddCustomModuleTest) include(mitkFunctionCheckModuleDependencies) include(mitkFunctionCompileSnippets) include(mitkFunctionConfigureVisualStudioUserProjectFile) include(mitkFunctionConvertXPSchema) include(mitkFunctionCreateBlueBerryApplication) include(mitkFunctionCreateCommandLineApp) include(mitkFunctionCreateModule) include(mitkFunctionCreatePlugin) include(mitkFunctionCreateProvisioningFile) include(mitkFunctionGetLibrarySearchPaths) include(mitkFunctionGetVersion) include(mitkFunctionGetVersionDescription) include(mitkFunctionInstallAutoLoadModules) include(mitkFunctionInstallCTKPlugin) include(mitkFunctionInstallProvisioningFiles) include(mitkFunctionInstallThirdPartyCTKPlugins) include(mitkFunctionOrganizeSources) include(mitkFunctionTestPlugin) include(mitkFunctionUseModules) if( ${MITK_USE_MatchPoint} ) include(mitkFunctionCreateMatchPointDeployedAlgorithm) endif() include(mitkMacroConfigureItkPixelTypes) include(mitkMacroCreateExecutable) include(mitkMacroCreateModuleTests) include(mitkMacroGenerateToolsLibrary) include(mitkMacroGetLinuxDistribution) include(mitkMacroGetPMDPlatformString) include(mitkMacroInstall) include(mitkMacroInstallHelperApp) include(mitkMacroInstallTargets) include(mitkMacroMultiplexPicType) # Deprecated include(mitkMacroCreateCTKPlugin) #----------------------------------------------------------------------------- # Global CMake variables #----------------------------------------------------------------------------- # Required and enabled C++14 features for all MITK code. # These are added as PUBLIC compile features to all MITK modules. set(MITK_CXX_FEATURES cxx_auto_type cxx_decltype cxx_enum_forward_declarations cxx_extended_friend_declarations cxx_extern_templates cxx_final cxx_lambdas cxx_local_type_template_args cxx_long_long_type cxx_nullptr cxx_override cxx_range_for cxx_right_angle_brackets cxx_rvalue_references cxx_static_assert cxx_strong_enums cxx_template_template_parameters cxx_trailing_return_types cxx_variadic_macros ) if(NOT DEFINED CMAKE_DEBUG_POSTFIX) # We can't do this yet because the CTK Plugin Framework # cannot cope with a postfix yet. #set(CMAKE_DEBUG_POSTFIX d) endif() #----------------------------------------------------------------------------- # Output directories. #----------------------------------------------------------------------------- set(_default_LIBRARY_output_dir lib) set(_default_RUNTIME_output_dir bin) set(_default_ARCHIVE_output_dir lib) foreach(type LIBRARY RUNTIME ARCHIVE) # Make sure the directory exists if(MITK_CMAKE_${type}_OUTPUT_DIRECTORY AND NOT EXISTS ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) message("Creating directory MITK_CMAKE_${type}_OUTPUT_DIRECTORY: ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") file(MAKE_DIRECTORY "${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}") endif() if(MITK_CMAKE_${type}_OUTPUT_DIRECTORY) set(CMAKE_${type}_OUTPUT_DIRECTORY ${MITK_CMAKE_${type}_OUTPUT_DIRECTORY}) else() set(CMAKE_${type}_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/${_default_${type}_output_dir}) set(MITK_CMAKE_${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY}) endif() set(CMAKE_${type}_OUTPUT_DIRECTORY ${CMAKE_${type}_OUTPUT_DIRECTORY} CACHE INTERNAL "Output directory for ${type} files.") mark_as_advanced(CMAKE_${type}_OUTPUT_DIRECTORY) endforeach() #----------------------------------------------------------------------------- # Set MITK specific options and variables (NOT available during superbuild) #----------------------------------------------------------------------------- # Look for optional Doxygen package find_package(Doxygen) option(BLUEBERRY_DEBUG_SMARTPOINTER "Enable code for debugging smart pointers" OFF) mark_as_advanced(BLUEBERRY_DEBUG_SMARTPOINTER) # ASK THE USER TO SHOW THE CONSOLE WINDOW FOR CoreApp and mitkWorkbench option(MITK_SHOW_CONSOLE_WINDOW "Use this to enable or disable the console window when starting MITK GUI Applications" ON) mark_as_advanced(MITK_SHOW_CONSOLE_WINDOW) # TODO: check if necessary option(USE_ITKZLIB "Use the ITK zlib for pic compression." ON) mark_as_advanced(USE_ITKZLIB) if(NOT MITK_FAST_TESTING) if(DEFINED MITK_CTEST_SCRIPT_MODE AND (MITK_CTEST_SCRIPT_MODE STREQUAL "continuous" OR MITK_CTEST_SCRIPT_MODE STREQUAL "experimental") ) set(MITK_FAST_TESTING 1) endif() endif() if(NOT UNIX AND NOT MINGW) set(MITK_WIN32_FORCE_STATIC "STATIC" CACHE INTERNAL "Use this variable to always build static libraries on non-unix platforms") endif() if(MITK_BUILD_ALL_PLUGINS) set(MITK_BUILD_ALL_PLUGINS_OPTION "FORCE_BUILD_ALL") endif() # Configure pixel types used for ITK image access multiplexing mitkMacroConfigureItkPixelTypes() # Configure module naming conventions set(MITK_MODULE_NAME_REGEX_MATCH "^[A-Z].*$") set(MITK_MODULE_NAME_REGEX_NOT_MATCH "^[Mm][Ii][Tt][Kk].*$") set(MITK_MODULE_NAME_PREFIX "Mitk") set(MITK_MODULE_NAME_DEFAULTS_TO_DIRECTORY_NAME 1) #----------------------------------------------------------------------------- # Get MITK version info #----------------------------------------------------------------------------- mitkFunctionGetVersion(${MITK_SOURCE_DIR} MITK) mitkFunctionGetVersionDescription(${MITK_SOURCE_DIR} MITK) # MITK_VERSION set(MITK_VERSION_STRING "${MITK_VERSION_MAJOR}.${MITK_VERSION_MINOR}.${MITK_VERSION_PATCH}") if(MITK_VERSION_PATCH STREQUAL "99") set(MITK_VERSION_STRING "${MITK_VERSION_STRING}-${MITK_REVISION_SHORTID}") endif() #----------------------------------------------------------------------------- # Installation preparation # # These should be set before any MITK install macros are used #----------------------------------------------------------------------------- # on Mac OSX all BlueBerry plugins get copied into every # application bundle (.app directory) specified here if(MITK_USE_BLUEBERRY AND APPLE) include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/AppList.cmake") foreach(mitk_app ${MITK_APPS}) # extract option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 1 option_name) list(GET target_info_list 0 app_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) set(MACOSX_BUNDLE_NAMES ${MACOSX_BUNDLE_NAMES} Mitk${app_name}) endif() endforeach() endif() #----------------------------------------------------------------------------- # Set coverage Flags #----------------------------------------------------------------------------- if(WITH_COVERAGE) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") set(coverage_flags "-g -fprofile-arcs -ftest-coverage -O0 -DNDEBUG") set(COVERAGE_CXX_FLAGS ${coverage_flags}) set(COVERAGE_C_FLAGS ${coverage_flags}) endif() endif() #----------------------------------------------------------------------------- # MITK C/CXX Flags #----------------------------------------------------------------------------- set(MITK_C_FLAGS "${COVERAGE_C_FLAGS}") set(MITK_C_FLAGS_DEBUG ) set(MITK_C_FLAGS_RELEASE ) set(MITK_CXX_FLAGS "${COVERAGE_CXX_FLAGS} ${MITK_CXX14_FLAG}") set(MITK_CXX_FLAGS_DEBUG ) set(MITK_CXX_FLAGS_RELEASE ) set(MITK_EXE_LINKER_FLAGS ) set(MITK_SHARED_LINKER_FLAGS ) find_package(OpenMP) if (OPENMP_FOUND) set(MITK_C_FLAGS "${MITK_C_FLAGS} ${OpenMP_C_FLAGS}") set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") endif() if(WIN32) set(MITK_CXX_FLAGS "${MITK_CXX_FLAGS} -D_WIN32_WINNT=0x0501 -DPOCO_NO_UNWINDOWS -DWIN32_LEAN_AND_MEAN -DNOMINMAX") mitkFunctionCheckCompilerFlags("/wd4005" MITK_CXX_FLAGS) # warning C4005: macro redefinition mitkFunctionCheckCompilerFlags("/wd4231" MITK_CXX_FLAGS) # warning C4231: nonstandard extension used : 'extern' before template explicit instantiation # the following line should be removed after fixing bug 17637 mitkFunctionCheckCompilerFlags("/wd4316" MITK_CXX_FLAGS) # warning C4316: object alignment on heap mitkFunctionCheckCompilerFlags("/wd4180" MITK_CXX_FLAGS) # warning C4180: qualifier applied to function type has no meaning endif() if(NOT MSVC_VERSION) foreach(_flag -Wall -Wextra -Wpointer-arith -Winvalid-pch -Wcast-align -Wwrite-strings -Wno-error=gnu -Wno-error=unknown-pragmas # The strict-overflow warning is generated by ITK template code -Wno-error=strict-overflow -Woverloaded-virtual -Wstrict-null-sentinel #-Wold-style-cast #-Wsign-promo -Wno-array-bounds -fdiagnostics-show-option ) mitkFunctionCheckCAndCXXCompilerFlags(${_flag} MITK_C_FLAGS MITK_CXX_FLAGS) endforeach() endif() if(CMAKE_COMPILER_IS_GNUCXX AND NOT APPLE) mitkFunctionCheckCompilerFlags("-Wl,--no-undefined" MITK_SHARED_LINKER_FLAGS) mitkFunctionCheckCompilerFlags("-Wl,--as-needed" MITK_SHARED_LINKER_FLAGS) endif() if(CMAKE_COMPILER_IS_GNUCXX) mitkFunctionCheckCAndCXXCompilerFlags("-fstack-protector-all" MITK_C_FLAGS MITK_CXX_FLAGS) if(MINGW) # suppress warnings about auto imported symbols set(MITK_SHARED_LINKER_FLAGS "-Wl,--enable-auto-import ${MITK_SHARED_LINKER_FLAGS}") endif() set(MITK_CXX_FLAGS_RELEASE "-U_FORTIFY_SOURCES -D_FORTIFY_SOURCE=2 ${MITK_CXX_FLAGS_RELEASE}") endif() set(MITK_MODULE_LINKER_FLAGS ${MITK_SHARED_LINKER_FLAGS}) set(MITK_EXE_LINKER_FLAGS ${MITK_SHARED_LINKER_FLAGS}) #----------------------------------------------------------------------------- # MITK Packages #----------------------------------------------------------------------------- set(MITK_MODULES_PACKAGE_DEPENDS_DIR ${MITK_SOURCE_DIR}/CMake/PackageDepends) set(MODULES_PACKAGE_DEPENDS_DIRS ${MITK_MODULES_PACKAGE_DEPENDS_DIR}) if(NOT MITK_USE_SYSTEM_Boost) set(Boost_NO_SYSTEM_PATHS 1) endif() set(Boost_USE_MULTITHREADED 1) set(Boost_USE_STATIC_LIBS 0) set(Boost_USE_STATIC_RUNTIME 0) set(Boost_ADDITIONAL_VERSIONS "1.64" "1.64.0") # We need this later for a DCMTK workaround set(_dcmtk_dir_orig ${DCMTK_DIR}) # This property is populated at the top half of this file get_property(MITK_EXTERNAL_PROJECTS GLOBAL PROPERTY MITK_EXTERNAL_PROJECTS) foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_package GLOBAL PROPERTY MITK_${ep}_PACKAGE) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) if(MITK_USE_${ep} AND _package) if(_components) find_package(${_package} COMPONENTS ${_components} REQUIRED CONFIG) else() # Prefer config mode first because it finds external # Config.cmake files pointed at by _DIR variables. # Otherwise, existing Find.cmake files could fail. - # (e.g. in the case of GLEW and the FindGLEW.cmake file shipped - # with CMake). find_package(${_package} QUIET CONFIG) string(TOUPPER "${_package}" _package_uc) if(NOT (${_package}_FOUND OR ${_package_uc}_FOUND)) find_package(${_package} REQUIRED) endif() endif() endif() endforeach() # Ensure that the MITK CMake module path comes first set(CMAKE_MODULE_PATH ${MITK_CMAKE_DIR} ${CMAKE_MODULE_PATH} ) if(MITK_USE_DCMTK) # Due to the preferred CONFIG mode in find_package calls above, # the DCMTKConfig.cmake file is read, which does not provide useful # package information. We explictly need MODULE mode to find DCMTK. if(${_dcmtk_dir_orig} MATCHES "${MITK_EXTERNAL_PROJECT_PREFIX}.*") # Help our FindDCMTK.cmake script find our super-build DCMTK set(DCMTK_DIR ${MITK_EXTERNAL_PROJECT_PREFIX}) else() # Use the original value set(DCMTK_DIR ${_dcmtk_dir_orig}) endif() find_package(DCMTK REQUIRED MODULE) endif() if(MITK_USE_DCMQI) # Due to the preferred CONFIG mode in find_package calls above, # the DCMQIConfig.cmake file is read, which does not provide useful # package information. We explictly need MODULE mode to find DCMQI. # Help our FindDCMQI.cmake script find our super-build DCMQI set(DCMQI_DIR ${MITK_EXTERNAL_PROJECT_PREFIX}) find_package(DCMQI REQUIRED) endif() if(MITK_USE_Python) find_package(PythonLibs REQUIRED) find_package(PythonInterp REQUIRED) if(MITK_USE_Numpy) find_package(Numpy REQUIRED) endif() endif() -if(MITK_USE_SOFA) - # The SOFAConfig.cmake file does not provide exported targets or - # libraries with absolute paths, hence we need to make the link - # directories globally available until the SOFAConfig.cmake file - # supports a proper mechanism for handling targets. - # The same code is needed in MITKConfig.cmake. - link_directories(${SOFA_LIBRARY_DIRS}) -endif() - -# Same as SOFA above link_directories(${Boost_LIBRARY_DIRS}) if(MITK_USE_OpenIGTLink) - # Same as SOFA above link_directories(${OpenIGTLink_LIBRARY_DIRS}) endif() if(MITK_USE_SimpleITK) link_directories(${SimpleITK_LIBRARY_DIRS}) endif() if(MITK_USE_OpenCL) find_package(OpenCL REQUIRED) endif() # Qt support if(MITK_USE_Qt5) find_package(Qt5Core ${MITK_QT5_MINIMUM_VERSION} REQUIRED) # at least Core required get_target_property(_qmake_exec Qt5::qmake LOCATION) execute_process(COMMAND ${_qmake_exec} -query QT_INSTALL_BINS RESULT_VARIABLE _result OUTPUT_VARIABLE QT_BINARY_DIR ERROR_VARIABLE _error ) string(STRIP "${QT_BINARY_DIR}" QT_BINARY_DIR) if(_result OR NOT EXISTS "${QT_BINARY_DIR}") message(FATAL_ERROR "Could not determine Qt binary directory: ${_result} ${QT_BINARY_DIR} ${_error}") endif() find_program(QT_HELPGENERATOR_EXECUTABLE NAMES qhelpgenerator qhelpgenerator-qt5 qhelpgenerator5 PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) find_program(QT_COLLECTIONGENERATOR_EXECUTABLE NAMES qcollectiongenerator qcollectiongenerator-qt5 qcollectiongenerator5 PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) find_program(QT_ASSISTANT_EXECUTABLE NAMES assistant assistant-qt5 assistant5 PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) find_program(QT_XMLPATTERNS_EXECUTABLE NAMES xmlpatterns PATHS ${QT_BINARY_DIR} NO_DEFAULT_PATH ) mark_as_advanced(QT_HELPGENERATOR_EXECUTABLE QT_COLLECTIONGENERATOR_EXECUTABLE QT_ASSISTANT_EXECUTABLE QT_XMLPATTERNS_EXECUTABLE ) if(MITK_USE_BLUEBERRY) option(BLUEBERRY_USE_QT_HELP "Enable support for integrating plugin documentation into Qt Help" ${DOXYGEN_FOUND}) mark_as_advanced(BLUEBERRY_USE_QT_HELP) # Sanity checks for in-application BlueBerry plug-in help generation if(BLUEBERRY_USE_QT_HELP) set(_force_blueberry_use_qt_help_to_off 0) if(NOT DOXYGEN_FOUND) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because Doxygen was not found.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(DOXYGEN_FOUND AND DOXYGEN_VERSION VERSION_LESS 1.8.7) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because Doxygen version 1.8.7 or newer not found.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT QT_HELPGENERATOR_EXECUTABLE) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because QT_HELPGENERATOR_EXECUTABLE is empty.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT MITK_USE_Qt5_WebEngine) message("> Forcing BLUEBERRY_USE_QT_HELP to OFF because MITK_USE_Qt5_WebEngine is OFF.") set(_force_blueberry_use_qt_help_to_off 1) endif() if(NOT QT_XMLPATTERNS_EXECUTABLE) message("You have enabled Qt Help support, but QT_XMLPATTERNS_EXECUTABLE is empty") set(_force_blueberry_use_qt_help_to_off 1) endif() if(_force_blueberry_use_qt_help_to_off) set(BLUEBERRY_USE_QT_HELP OFF CACHE BOOL "Enable support for integrating plugin documentation into Qt Help" FORCE) endif() endif() if(BLUEBERRY_QT_HELP_REQUIRED AND NOT BLUEBERRY_USE_QT_HELP) message(FATAL_ERROR "BLUEBERRY_USE_QT_HELP is required to be set to ON") endif() endif() endif() #----------------------------------------------------------------------------- # Testing #----------------------------------------------------------------------------- if(BUILD_TESTING) enable_testing() include(CTest) mark_as_advanced(TCL_TCLSH DART_ROOT) option(MITK_ENABLE_RENDERING_TESTING OFF "Enable the MITK rendering tests. Requires x-server in Linux.") #Rendering testing does not work for Linux nightlies, thus it is disabled per default #and activated for Mac and Windows. if(WIN32 OR APPLE) set(MITK_ENABLE_RENDERING_TESTING ON) endif() mark_as_advanced( MITK_ENABLE_RENDERING_TESTING ) # Setup file for setting custom ctest vars configure_file( CMake/CTestCustom.cmake.in ${MITK_BINARY_DIR}/CTestCustom.cmake @ONLY ) # Initial cache for ProjectTemplate and PluginGenerator tests configure_file( CMake/mitkTestInitialCache.txt.in ${MITK_BINARY_DIR}/mitkTestInitialCache.txt @ONLY ) # Configuration for the CMake-generated test driver set(CMAKE_TESTDRIVER_EXTRA_INCLUDES "#include ") set(CMAKE_TESTDRIVER_BEFORE_TESTMAIN " try {") set(CMAKE_TESTDRIVER_AFTER_TESTMAIN " } catch( std::exception & excp ) { fprintf(stderr,\"%s\\n\",excp.what()); return EXIT_FAILURE; } catch( ... ) { printf(\"Exception caught in the test driver\\n\"); return EXIT_FAILURE; } ") set(MITK_TEST_OUTPUT_DIR "${MITK_BINARY_DIR}/test_output") if(NOT EXISTS ${MITK_TEST_OUTPUT_DIR}) file(MAKE_DIRECTORY ${MITK_TEST_OUTPUT_DIR}) endif() # Test the external project template if(MITK_USE_BLUEBERRY) include(mitkTestProjectTemplate) endif() # Test the package target include(mitkPackageTest) endif() configure_file(mitkTestingConfig.h.in ${MITK_BINARY_DIR}/mitkTestingConfig.h) #----------------------------------------------------------------------------- # MITK_SUPERBUILD_BINARY_DIR #----------------------------------------------------------------------------- # If MITK_SUPERBUILD_BINARY_DIR isn't defined, it means MITK is *NOT* build using Superbuild. # In that specific case, MITK_SUPERBUILD_BINARY_DIR should default to MITK_BINARY_DIR if(NOT DEFINED MITK_SUPERBUILD_BINARY_DIR) set(MITK_SUPERBUILD_BINARY_DIR ${MITK_BINARY_DIR}) endif() #----------------------------------------------------------------------------- # Set C/CXX and linker flags for MITK code #----------------------------------------------------------------------------- set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${MITK_CXX_FLAGS}") set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} ${MITK_CXX_FLAGS_DEBUG}") set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${MITK_CXX_FLAGS_RELEASE}") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${MITK_C_FLAGS}") set(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} ${MITK_C_FLAGS_DEBUG}") set(CMAKE_C_FLAGS_RELEASE "${CMAKE_C_FLAGS_RELEASE} ${MITK_C_FLAGS_RELEASE}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${MITK_EXE_LINKER_FLAGS}") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} ${MITK_SHARED_LINKER_FLAGS}") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} ${MITK_MODULE_LINKER_FLAGS}") #----------------------------------------------------------------------------- # Add custom targets representing CDash subprojects #----------------------------------------------------------------------------- foreach(subproject ${CTEST_PROJECT_SUBPROJECTS}) if(NOT TARGET ${subproject} AND NOT subproject MATCHES "Unlabeled") add_custom_target(${subproject}) endif() endforeach() #----------------------------------------------------------------------------- # Add subdirectories #----------------------------------------------------------------------------- add_subdirectory(Utilities) add_subdirectory(Modules) if(MITK_USE_BLUEBERRY) set(BLUEBERRY_XPDOC_OUTPUT_DIR ${MITK_DOXYGEN_OUTPUT_DIR}/html/extension-points/html/) set(MITK_DEFAULT_SUBPROJECTS MITK-Plugins) # Plug-in testing (needs some work to be enabled again) if(BUILD_TESTING) set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp") if(TARGET CoreApp) get_target_property(_is_macosx_bundle CoreApp MACOSX_BUNDLE) if(APPLE AND _is_macosx_bundle) set(BLUEBERRY_UI_TEST_APP "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/CoreApp.app/Contents/MacOS/CoreApp") endif() endif() set(BLUEBERRY_TEST_APP_ID "org.mitk.qt.coreapplication") endif() include("${CMAKE_CURRENT_SOURCE_DIR}/Plugins/PluginList.cmake") mitkFunctionWhitelistPlugins(MITK MITK_PLUGINS) set(mitk_plugins_fullpath "") foreach(mitk_plugin ${MITK_PLUGINS}) list(APPEND mitk_plugins_fullpath Plugins/${mitk_plugin}) endforeach() if(EXISTS ${MITK_PRIVATE_MODULES}/PluginList.cmake) include(${MITK_PRIVATE_MODULES}/PluginList.cmake) foreach(mitk_plugin ${MITK_PRIVATE_PLUGINS}) list(APPEND mitk_plugins_fullpath ${MITK_PRIVATE_MODULES}/${mitk_plugin}) endforeach() endif() if(MITK_BUILD_EXAMPLES) include("${CMAKE_CURRENT_SOURCE_DIR}/Examples/Plugins/PluginList.cmake") set(mitk_example_plugins_fullpath ) foreach(mitk_example_plugin ${MITK_EXAMPLE_PLUGINS}) list(APPEND mitk_example_plugins_fullpath Examples/Plugins/${mitk_example_plugin}) list(APPEND mitk_plugins_fullpath Examples/Plugins/${mitk_example_plugin}) endforeach() endif() # Specify which plug-ins belong to this project macro(GetMyTargetLibraries all_target_libraries varname) set(re_ctkplugin_mitk "^org_mitk_[a-zA-Z0-9_]+$") set(re_ctkplugin_bb "^org_blueberry_[a-zA-Z0-9_]+$") set(_tmp_list) list(APPEND _tmp_list ${all_target_libraries}) ctkMacroListFilter(_tmp_list re_ctkplugin_mitk re_ctkplugin_bb OUTPUT_VARIABLE ${varname}) endmacro() # Get infos about application directories and build options include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/AppList.cmake") set(mitk_apps_fullpath ) foreach(mitk_app ${MITK_APPS}) # extract option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 directory_name) list(GET target_info_list 1 option_name) if(${option_name}) list(APPEND mitk_apps_fullpath "${CMAKE_CURRENT_SOURCE_DIR}/Applications/${directory_name}^^${option_name}") endif() endforeach() if (mitk_plugins_fullpath) ctkMacroSetupPlugins(${mitk_plugins_fullpath} BUILD_OPTION_PREFIX MITK_BUILD_ APPS ${mitk_apps_fullpath} BUILD_ALL ${MITK_BUILD_ALL_PLUGINS} COMPACT_OPTIONS) endif() set(MITK_PLUGIN_USE_FILE "${MITK_BINARY_DIR}/MitkPluginUseFile.cmake") if(${PROJECT_NAME}_PLUGIN_LIBRARIES) ctkFunctionGeneratePluginUseFile(${MITK_PLUGIN_USE_FILE}) else() file(REMOVE ${MITK_PLUGIN_USE_FILE}) set(MITK_PLUGIN_USE_FILE ) endif() endif() #----------------------------------------------------------------------------- # Documentation #----------------------------------------------------------------------------- if(DOXYGEN_FOUND) add_subdirectory(Documentation) endif() #----------------------------------------------------------------------------- # Installation #----------------------------------------------------------------------------- # set MITK cpack variables # These are the default variables, which can be overwritten ( see below ) include(mitkSetupCPack) set(use_default_config ON) # MITK_APPS is set in Applications/AppList.cmake (included somewhere above # if MITK_USE_BLUEBERRY is set to ON). if(MITK_APPS) set(activated_apps_no 0) list(LENGTH MITK_APPS app_count) # Check how many apps have been enabled # If more than one app has been activated, the we use the # default CPack configuration. Otherwise that apps configuration # will be used, if present. foreach(mitk_app ${MITK_APPS}) # extract option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 1 option_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) MATH(EXPR activated_apps_no "${activated_apps_no} + 1") endif() endforeach() if(app_count EQUAL 1 AND (activated_apps_no EQUAL 1 OR MITK_BUILD_ALL_APPS)) # Corner case if there is only one app in total set(use_project_cpack ON) elseif(activated_apps_no EQUAL 1 AND NOT MITK_BUILD_ALL_APPS) # Only one app is enabled (no "build all" flag set) set(use_project_cpack ON) else() # Less or more then one app is enabled set(use_project_cpack OFF) endif() foreach(mitk_app ${MITK_APPS}) # extract target_dir and option_name string(REPLACE "^^" "\\;" target_info ${mitk_app}) set(target_info_list ${target_info}) list(GET target_info_list 0 target_dir) list(GET target_info_list 1 option_name) list(GET target_info_list 2 executable_name) # check if the application is enabled if(${option_name} OR MITK_BUILD_ALL_APPS) # check whether application specific configuration files will be used if(use_project_cpack) # use files if they exist if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/CPackOptions.cmake") include("${CMAKE_CURRENT_SOURCE_DIR}/Applications/${target_dir}/CPackOptions.cmake") endif() if(EXISTS "${PROJECT_SOURCE_DIR}/Applications/${target_dir}/CPackConfig.cmake.in") set(CPACK_PROJECT_CONFIG_FILE "${PROJECT_BINARY_DIR}/Applications/${target_dir}/CPackConfig.cmake") configure_file(${PROJECT_SOURCE_DIR}/Applications/${target_dir}/CPackConfig.cmake.in ${CPACK_PROJECT_CONFIG_FILE} @ONLY) set(use_default_config OFF) endif() endif() # add link to the list list(APPEND CPACK_CREATE_DESKTOP_LINKS "${executable_name}") endif() endforeach() endif() # if no application specific configuration file was used, use default if(use_default_config) configure_file(${MITK_SOURCE_DIR}/MITKCPackOptions.cmake.in ${MITK_BINARY_DIR}/MITKCPackOptions.cmake @ONLY) set(CPACK_PROJECT_CONFIG_FILE "${MITK_BINARY_DIR}/MITKCPackOptions.cmake") endif() # include CPack model once all variables are set include(CPack) # Additional installation rules include(mitkInstallRules) #----------------------------------------------------------------------------- # Last configuration steps #----------------------------------------------------------------------------- # ---------------- Export targets ----------------- set(MITK_EXPORTS_FILE "${MITK_BINARY_DIR}/MitkExports.cmake") file(REMOVE ${MITK_EXPORTS_FILE}) set(targets_to_export) get_property(module_targets GLOBAL PROPERTY MITK_MODULE_TARGETS) if(module_targets) list(APPEND targets_to_export ${module_targets}) endif() if(MITK_USE_BLUEBERRY) if(MITK_PLUGIN_LIBRARIES) list(APPEND targets_to_export ${MITK_PLUGIN_LIBRARIES}) endif() endif() export(TARGETS ${targets_to_export} APPEND FILE ${MITK_EXPORTS_FILE}) set(MITK_EXPORTED_TARGET_PROPERTIES ) foreach(target_to_export ${targets_to_export}) get_target_property(autoload_targets ${target_to_export} MITK_AUTOLOAD_TARGETS) if(autoload_targets) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_AUTOLOAD_TARGETS \"${autoload_targets}\")") endif() get_target_property(autoload_dir ${target_to_export} MITK_AUTOLOAD_DIRECTORY) if(autoload_dir) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_AUTOLOAD_DIRECTORY \"${autoload_dir}\")") endif() get_target_property(deprecated_module ${target_to_export} MITK_MODULE_DEPRECATED_SINCE) if(deprecated_module) set(MITK_EXPORTED_TARGET_PROPERTIES "${MITK_EXPORTED_TARGET_PROPERTIES} set_target_properties(${target_to_export} PROPERTIES MITK_MODULE_DEPRECATED_SINCE \"${deprecated_module}\")") endif() endforeach() # ---------------- External projects ----------------- get_property(MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS_CONFIG GLOBAL PROPERTY MITK_ADDITIONAL_LIBRARY_SEARCH_PATHS) set(MITK_CONFIG_EXTERNAL_PROJECTS ) #string(REPLACE "^^" ";" _mitk_external_projects ${MITK_EXTERNAL_PROJECTS}) foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) set(MITK_CONFIG_EXTERNAL_PROJECTS "${MITK_CONFIG_EXTERNAL_PROJECTS} set(MITK_USE_${ep} ${MITK_USE_${ep}}) set(MITK_${ep}_DIR \"${${ep}_DIR}\") set(MITK_${ep}_COMPONENTS ${_components}) ") endforeach() foreach(ep ${MITK_EXTERNAL_PROJECTS}) get_property(_package GLOBAL PROPERTY MITK_${ep}_PACKAGE) get_property(_components GLOBAL PROPERTY MITK_${ep}_COMPONENTS) if(_components) set(_components_arg COMPONENTS \${_components}) else() set(_components_arg) endif() if(_package) set(MITK_CONFIG_EXTERNAL_PROJECTS "${MITK_CONFIG_EXTERNAL_PROJECTS} if(MITK_USE_${ep}) set(${ep}_DIR \${MITK_${ep}_DIR}) if(MITK_${ep}_COMPONENTS) mitkMacroFindDependency(${_package} COMPONENTS \${MITK_${ep}_COMPONENTS}) else() mitkMacroFindDependency(${_package}) endif() endif()") endif() endforeach() # ---------------- Tools ----------------- configure_file(${MITK_SOURCE_DIR}/CMake/ToolExtensionITKFactory.cpp.in ${MITK_BINARY_DIR}/ToolExtensionITKFactory.cpp.in COPYONLY) configure_file(${MITK_SOURCE_DIR}/CMake/ToolExtensionITKFactoryLoader.cpp.in ${MITK_BINARY_DIR}/ToolExtensionITKFactoryLoader.cpp.in COPYONLY) configure_file(${MITK_SOURCE_DIR}/CMake/ToolGUIExtensionITKFactory.cpp.in ${MITK_BINARY_DIR}/ToolGUIExtensionITKFactory.cpp.in COPYONLY) # ---------------- Configure files ----------------- configure_file(mitkVersion.h.in ${MITK_BINARY_DIR}/mitkVersion.h) configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) set(IPFUNC_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities/ipFunc) set(UTILITIES_DIR ${CMAKE_CURRENT_SOURCE_DIR}/Utilities) configure_file(mitkConfig.h.in ${MITK_BINARY_DIR}/mitkConfig.h) configure_file(MITKConfig.cmake.in ${MITK_BINARY_DIR}/MITKConfig.cmake @ONLY) write_basic_config_version_file(${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake VERSION ${MITK_VERSION_STRING} COMPATIBILITY AnyNewerVersion) #----------------------------------------------------------------------------- # MITK Applications #----------------------------------------------------------------------------- # This must come after MITKConfig.h was generated, since applications # might do a find_package(MITK REQUIRED). add_subdirectory(Applications) #----------------------------------------------------------------------------- # MITK Examples #----------------------------------------------------------------------------- if(MITK_BUILD_EXAMPLES) # This must come after MITKConfig.h was generated, since applications # might do a find_package(MITK REQUIRED). add_subdirectory(Examples) endif() #----------------------------------------------------------------------------- # Print configuration summary #----------------------------------------------------------------------------- message("\n\n") feature_summary( DESCRIPTION "------- FEATURE SUMMARY FOR ${PROJECT_NAME} -------" WHAT ALL ) diff --git a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/BuildInstructions.dox b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/BuildInstructions.dox index 3d47cc93d6..685d278bb9 100644 --- a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/BuildInstructions.dox +++ b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/BuildInstructions.dox @@ -1,219 +1,217 @@ /** \page BuildInstructionsPage Build Instructions \tableofcontents \section BuildInstructions_Introduction Introduction The CMake-based build system of MITK supports a "superbuild" process, meaning that it will download, configure, and build all required third-party libraries (except Qt) automatically. These instructions will show you how to use the MITK superbuild. \note This page explains explicitly how to build MITK itself. If you want to create your own project based on MITK, the process described below is completely automated. Please see \ref HowToNewProject. For more advanced users, the last sections explains how to inject custom build libraries into the superbuild process. \section BuildInstructions_Prerequisites Prerequisites You need: -# Git from http://git-scm.com (there are also numerous third-party graphical clients available). We recomment using Git, but see below for a way how to get the current source code without using it. -# CMake (version \minimumCMakeVersion or higher) -# Qt 5.6 or 5.7.1 if you plan to develop Qt-based applications -# If you are using Mac OS X you need an XCode installation as it provides the neccessary compilers and SDKs \section BuildInstructions_Qt A note about Qt As we do not provide Qt in the MITK superbuild you need to install Qt manually. Installing Qt dramatically improved since Qt 5, as The Qt Company provides sophisticated online installers for all supported platforms. \section BuildInstructions_Get_Source Get a source tree Since MITK is under active development we recommend to use Git to check out the latest stable release from the homepage. If you decide to use the most current nightly release, make sure to get a stable tree: Check the MITK dashboard before checking out. If the build tree is not clean, you can specify an older revision for the checkout or get a stable tar ball from www.mitk.org. To clone MITK's current Git repository do: \code git clone https://phabricator.mitk.org/source/mitk.git MITK \endcode \section BuildInstructions_Build_With_CMake Build MITK with CMake Create a new directory for the superbuild binary tree, change to it and call CMake: In the shell (assuming your current directory is the same as the one where you issued the git clone command): \code mkdir MITK-superbuild cd MITK-superbuild ccmake ../MITK \endcode If you use Windows or prefer to use the CMake GUI, start the CMake GUI and enter the location of the source tree and binary tree, choose a suitable generator and configure the project. CMake will present you a couple of options, these are the most important ones: - CMAKE_PREFIX_PATH The path to your Qt installation, e.g., C:/Qt/5.6/msvc2013_64 or /home/user/Qt/5.6/gcc_64 - MITK_USE_ACVD Build MITK code which depends on ACVD (this will download and build ACVD) - MITK_USE_BLUEBERRY Build the BlueBerry application framework - MITK_USE_Boost_LIBRARIES If you need binary Boost libraries, specify them here. - MITK_USE_OpenCV Build MITK code which depends on OpenCV (this will download and build OpenCV 2.4) - MITK_USE_Python Enables Python wrapping in MITK. This will also configure ITK, VTK, and OpenCV (if enabled) to build Python wrappers. - MITK_USE_Qt5 Build MITK code which depends on Qt 5 - - MITK_USE_SOFA Build MITK code which depends on SOFA (this will - download and build SOFA) If you are satisfied with the configuration of your MITK superbuild, generate the project files with CMake by pressing "Generate". Linux and Mac OS X users usually just enter "make" (optionally supplying the number threads to be used for a parallel build): \code make -j6 \endcode Windows users using Visual Studio can open the generated MITK-superbuild.sln solution file in the MITK-superbuild directory and start the build by building the BUILD_ALL project. \section BuildInstructions_Customize Customize your MITK superbuild The MITK superbuild configures MITK as well as all external libraries. The build directories of these libraries, and of MITK itself are located inside the MITK-superbuild directory. For example, the directory layout may look like: \code MITK-superbuild |- ep "external projects" |-bin |-lib |-include |-src |- MITK-build \endcode To change the configuration of the MITK build itself, choose the MITK-build directory as the binary directory in the CMake GUI (not the MITK-superbuild directory). After generating the project files, build the MITK project by either issuing "make" in the MITK-build directory (Linux, Mac OS X), or by opening MITK-build/MITK.sln (Windows). You may also change the configuration of any project configured via the superbuild process. Make sure to also build the changed project and also the projects which depend on it. \section BuildInstructions_Running Running Applications On Linux, just execute the application you want to run. MITK executables are located in MITK-superbuild/MITK-build/bin On Windows, the PATH environment variable must contain the directories containing the third-party libraries. This is automatically done from Visual Studio. For running the applications directly use the generated batch files in the MITK-superbuild/MITK-build/bin. \section BuildInstructions_Documentation Documentation If you have the Doxygen documentation tool installed, you get a new project (Visual Studio) or "make" target named "doc". You can build this to generate the HTML documentation of MITK in the Documentation/Doxygen directory of your MITK-build binary tree or in the MITK_DOXYGEN_OUTPUT_DIR CMake variable (if specified). \section BuildInstructions_Extending Extend MITK on your own (using the application framework BlueBerry) Please see \ref NewPluginPage \section BuildInstructions_As_Toolkit Use MITK in your own project (as a toolkit) To use MITK in your external project, add the CMake command find_package(MITK REQUIRED) to your CMakeLists.txt and make use of the CMake macros mitk_create_module() and mitk_create_executable() provided by MITK. Here is a very basic example CMakeLists.txt including MITK as a project: \code cmake_minimum_required(VERSION 3.5 FATAL_ERROR) project(MyProject) find_package(MITK 2016.11 REQUIRED) add_executable(MyApp main.cpp) target_link_libraries(MyApp MitkCore) \endcode with the main.ccp being \code #include #include int main() { MITK_INFO << "Hello world!"; return 0; } \endcode \section BuildInstructions_Advanced_Customization Superbuild customization You can inject pre-build third-party libraries into the MITK superbuild by setting certain CMake variables before the first configure step. MITK will then use these third-party libraries instead of downloading and building them by itself. Note that you must take care of configuring those libraries with all options MITK requires. The variables listed below are provided for injecting third-party libraries. Their occurrence in the CMake GUI or in ccmake may depend on specific MITK_USE_* options set to ON. You may also use the variable names below without the EXTERNAL_ prefix, for example when providing their values on a command line call to CMake. - EXTERNAL_BOOST_ROOT Set this variable to your custom Boost installation - EXTERNAL_CTK_DIR Set this variable to your CTK binary tree (the directory containing the CTKConfig.cmake file) - EXTERNAL_CableSwig_DIR Set this variable to your CableSwig binary tree for Python wrapping (the directory containing the CableSwigConfig.cmake file) - EXTERNAL_DCMTK_DIR Set this variable to your DCMTK binary tree (the directory containing the DCMTKConfig.cmake file) - EXTERNAL_GDCM_DIR Set this variable to your GDCM binary tree (the directory containing the GDCMConfig.cmake file) - EXTERNAL_ITK_DIR Set this variable to your ITK binary tree (the directory containing the ITKConfig.cmake file) - EXTERNAL_OpenCV_DIR Set this variable to your OpenCV binary tree (the directory containing the OpenCVConfig.cmake file) - EXTERNAL_VTK_DIR Set this variable to your VTK binary tree (the directory containing the VTKConfig.cmake file) To set CMake options before the first configure step is invoked, supply them on the command line, i.e. \code ccmake -DITK_DIR:PATH=/opt/ITK-release ../MITK \endcode */ diff --git a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/ThirdPartyLibs.dox b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/ThirdPartyLibs.dox index 5c2f464af7..3d4507df5c 100644 --- a/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/ThirdPartyLibs.dox +++ b/Documentation/Doxygen/3-DeveloperManual/Starting/SettingUpMITK/ThirdPartyLibs.dox @@ -1,143 +1,131 @@ /** \page thirdpartylibs Third-party libraries The following third-party libraries can be used with MITK by default and can, in part, be automatically downloaded during superbuild. \par ACVD http://www.creatis.insa-lyon.fr/site/en/acvd \par ANN http://www.cs.umd.edu/~mount/ANN/ \par Boost http://www.boost.org/ \par CppUnit http://sourceforge.net/projects/cppunit/ \par CTK http://www.commontk.org/ \par DCMTK http://dicom.offis.de/dcmtk.php.en \par Eigen http://eigen.tuxfamily.org/index.php?title=Main_Page \par GDCM http://gdcm.sourceforge.net/ -\par GLEW - -http://glew.sourceforge.net/ - \par GLUT https://www.opengl.org/resources/libraries/glut/ \par HDF5 https://support.hdfgroup.org/HDF5/ \par ITK http://www.itk.org/ \par MatchPoint https://www.dkfz.de/en/sidt/projects/matchpoint/info.html \par NumPy http://www.numpy.org/ \par OpenCL https://www.khronos.org/opencl/ \par OpenCV http://opencv.willowgarage.com/wiki/Welcome \par OpenIGTLink http://openigtlink.org/ \par PCRE http://www.pcre.org/ \par POCO http://pocoproject.org \par Python https://www.python.org/ \par Qt http://www.qt.io/ \par Qwt http://qwt.sourceforge.net/ \par Rasqal http://librdf.org/rasqal/ \par Raptor2 http://librdf.org/raptor/ \par Redland http://librdf.org/ \par SimpleITK http://www.simpleitk.org/ -\par SOFA - -http://www.sofa-framework.org/ - \par SWIG http://swig.org/ \par tinyxml http://sourceforge.net/projects/tinyxml/ \par VIGRA http://ukoethe.github.io/vigra/ -\par VMTK - -http://www.vmtk.org/ - \par VTK http://www.vtk.org/ \par zlib https://github.com/commontk/zlib \par libSVM http://www.csie.ntu.edu.tw/~cjlin/libsvm/ For copyright information on any of the above toolkits see the corresponding home page or the corresponding source folder. */ diff --git a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simpleexample/QmitkSimpleExampleView.cpp b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simpleexample/QmitkSimpleExampleView.cpp index 6dcaf57bd7..cf87964511 100644 --- a/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simpleexample/QmitkSimpleExampleView.cpp +++ b/Examples/Plugins/org.mitk.example.gui.imaging/src/internal/simpleexample/QmitkSimpleExampleView.cpp @@ -1,422 +1,423 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkSimpleExampleView.h" #include "QmitkRenderWindow.h" #include "QmitkStepperAdapter.h" #include "QmitkFFmpegWriter.h" #include "mitkNodePredicateNot.h" #include "mitkNodePredicateProperty.h" #include "mitkProperties.h" #include #include #include #include #include #include #include #include #include #include +#include const std::string QmitkSimpleExampleView::VIEW_ID = "org.mitk.views.simpleexample"; QmitkSimpleExampleView::QmitkSimpleExampleView() : m_Controls(nullptr), m_NavigatorsInitialized(false), m_Parent(nullptr) { } QmitkSimpleExampleView::~QmitkSimpleExampleView() { } void QmitkSimpleExampleView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { m_Parent = parent; // create GUI widgets m_Controls = new Ui::QmitkSimpleExampleViewControls; m_Controls->setupUi(parent); this->CreateConnections(); this->RenderWindowPartActivated(this->GetRenderWindowPart()); } } void QmitkSimpleExampleView::SetFocus() { m_Controls->renderWindowComboBox->setFocus(); } void QmitkSimpleExampleView::RenderWindowPartActivated(mitk::IRenderWindowPart *renderWindowPart) { if (renderWindowPart == nullptr) { m_Parent->setEnabled(false); return; } QHashIterator renderIter(renderWindowPart->GetQmitkRenderWindows()); while (renderIter.hasNext()) { renderIter.next(); m_Controls->renderWindowComboBox->addItem(renderIter.key()); } RenderWindowSelected(m_Controls->renderWindowComboBox->currentText()); m_TimeStepper.reset(new QmitkStepperAdapter(m_Controls->sliceNavigatorTime, renderWindowPart->GetTimeNavigationController()->GetTime(), "sliceNavigatorTimeFromSimpleExample")); m_MovieStepper.reset(new QmitkStepperAdapter(m_Controls->movieNavigatorTime, renderWindowPart->GetTimeNavigationController()->GetTime(), "movieNavigatorTimeFromSimpleExample")); m_Parent->setEnabled(true); } void QmitkSimpleExampleView::RenderWindowPartDeactivated(mitk::IRenderWindowPart * /*renderWindowPart*/) { m_Parent->setEnabled(false); m_SliceStepper.reset(); m_TimeStepper.reset(); m_MovieStepper.reset(); m_Controls->renderWindowComboBox->clear(); } void QmitkSimpleExampleView::CreateConnections() { if (m_Controls) { connect(m_Controls->renderWindowComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(RenderWindowSelected(QString))); connect(m_Controls->stereoSelect, SIGNAL(activated(int)), this, SLOT(StereoSelectionChanged(int))); connect(m_Controls->reInitializeNavigatorsButton, SIGNAL(clicked()), this, SLOT(InitNavigators())); connect(m_Controls->genMovieButton, SIGNAL(clicked()), this, SLOT(GenerateMovie())); connect(m_Controls->m_TakeScreenshotBtn, SIGNAL(clicked()), this, SLOT(OnTakeScreenshot())); connect(m_Controls->m_TakeHighResScreenShotBtn, SIGNAL(clicked()), this, SLOT(OnTakeHighResolutionScreenshot())); } } void QmitkSimpleExampleView::InitNavigators() { /* get all nodes that have not set "includeInBoundingBox" to false */ mitk::NodePredicateNot::Pointer pred = mitk::NodePredicateNot::New( mitk::NodePredicateProperty::New("includeInBoundingBox", mitk::BoolProperty::New(false))); mitk::DataStorage::SetOfObjects::ConstPointer rs = this->GetDataStorage()->GetSubset(pred); /* calculate bounding geometry of these nodes */ mitk::TimeGeometry::Pointer bounds = this->GetDataStorage()->ComputeBoundingGeometry3D(rs); /* initialize the views to the bounding geometry */ m_NavigatorsInitialized = mitk::RenderingManager::GetInstance()->InitializeViews(bounds); } /** * Returns path to the ffmpeg lib if configured in preferences. * * This implementation has been reused from MovieMaker view. * * @return The path to ffmpeg lib or empty string if not configured. */ QString QmitkSimpleExampleView::GetFFmpegPath() const { berry::IPreferences::Pointer preferences = berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.gui.qt.ext.externalprograms"); return preferences.IsNotNull() ? preferences->Get("ffmpeg", "") : ""; } /** * Reads pixels from specified render window. * * This implementation has been reused from MovieMaker view. * * @param renderWindow * @param x * @param y * @param width * @param height * @return */ static unsigned char *ReadPixels(vtkRenderWindow *renderWindow, int x, int y, int width, int height) { if (renderWindow == nullptr) return nullptr; unsigned char *frame = new unsigned char[width * height * 3]; renderWindow->MakeCurrent(); glReadPixels(x, y, width, height, GL_RGB, GL_UNSIGNED_BYTE, frame); return frame; } /** * Records a movie from the selected render window with a default frame rate of 30 Hz. * * Parts of this implementation have been reused from MovieMaker view. */ void QmitkSimpleExampleView::GenerateMovie() { QmitkRenderWindow *movieRenderWindow = GetSelectedRenderWindow(); mitk::Stepper::Pointer stepper = movieRenderWindow->GetSliceNavigationController()->GetSlice(); QmitkFFmpegWriter *movieWriter = new QmitkFFmpegWriter(m_Parent); const QString ffmpegPath = GetFFmpegPath(); if (ffmpegPath.isEmpty()) { QMessageBox::information( nullptr, "Movie Maker", "

Set path to FFmpeg1 or Libav2 (avconv) in preferences (Window -> Preferences... " "(Ctrl+P) -> External Programs) to be able to record your movies to video files.

" "

If you are using Linux, chances are good that either FFmpeg or Libav is included in the official package " "repositories.

" "

[1] Download FFmpeg from ffmpeg.org
" "[2] Download Libav from libav.org

"); return; } movieWriter->SetFFmpegPath(GetFFmpegPath()); vtkRenderWindow *renderWindow = movieRenderWindow->GetRenderWindow(); if (renderWindow == nullptr) return; const int border = 3; const int x = border; const int y = border; int width = renderWindow->GetSize()[0] - border * 2; int height = renderWindow->GetSize()[1] - border * 2; if (width & 1) --width; if (height & 1) --height; if (width < 16 || height < 16) return; movieWriter->SetSize(width, height); movieWriter->SetFramerate(30); QString saveFileName = QFileDialog::getSaveFileName(nullptr, "Specify a filename", "", "Movie (*.mp4)"); if (saveFileName.isEmpty()) return; if (!saveFileName.endsWith(".mp4")) saveFileName += ".mp4"; movieWriter->SetOutputPath(saveFileName); const unsigned int numberOfFrames = stepper->GetSteps() - stepper->GetPos(); try { movieWriter->Start(); for (unsigned int currentFrame = 0; currentFrame < numberOfFrames; ++currentFrame) { mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); renderWindow->MakeCurrent(); unsigned char *frame = ReadPixels(renderWindow, x, y, width, height); movieWriter->WriteFrame(frame); delete[] frame; stepper->Next(); } movieWriter->Stop(); mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); } catch (const mitk::Exception &exception) { mitk::RenderingManager::GetInstance()->ForceImmediateUpdateAll(); QMessageBox::critical(nullptr, "Generate Movie", exception.GetDescription()); } } void QmitkSimpleExampleView::StereoSelectionChanged(int id) { /* From vtkRenderWindow.h tells us about stereo rendering: Set/Get what type of stereo rendering to use. CrystalEyes mode uses frame-sequential capabilities available in OpenGL to drive LCD shutter glasses and stereo projectors. RedBlue mode is a simple type of stereo for use with red-blue glasses. Anaglyph mode is a superset of RedBlue mode, but the color output channels can be configured using the AnaglyphColorMask and the color of the original image can be (somewhat maintained using AnaglyphColorSaturation; the default colors for Anaglyph mode is red-cyan. Interlaced stereo mode produces a composite image where horizontal lines alternate between left and right views. StereoLeft and StereoRight modes choose one or the other stereo view. Dresden mode is yet another stereoscopic interleaving. */ mitk::IRenderWindowPart *renderWindowPart = this->GetRenderWindowPart(); vtkRenderWindow *vtkrenderwindow = renderWindowPart->GetQmitkRenderWindow("3d")->GetVtkRenderWindow(); // note: foreground vtkRenderers (at least the department logo renderer) produce errors in stereoscopic visualization. // Therefore, we disable the logo visualization during stereo rendering. switch (id) { case 0: vtkrenderwindow->StereoRenderOff(); break; case 1: vtkrenderwindow->SetStereoTypeToRedBlue(); vtkrenderwindow->StereoRenderOn(); renderWindowPart->EnableDecorations(false, QStringList(mitk::IRenderWindowPart::DECORATION_LOGO)); break; case 2: vtkrenderwindow->SetStereoTypeToDresden(); vtkrenderwindow->StereoRenderOn(); renderWindowPart->EnableDecorations(false, QStringList(mitk::IRenderWindowPart::DECORATION_LOGO)); break; } mitk::BaseRenderer::GetInstance(vtkrenderwindow)->SetMapperID(mitk::BaseRenderer::Standard3D); renderWindowPart->RequestUpdate(); } QmitkRenderWindow *QmitkSimpleExampleView::GetSelectedRenderWindow() const { QString id = m_Controls->renderWindowComboBox->currentText(); if (id.isEmpty()) { return nullptr; } else { return this->GetRenderWindowPart()->GetQmitkRenderWindow(id); } } void QmitkSimpleExampleView::OnTakeHighResolutionScreenshot() { QString filter; QString fileName = QFileDialog::getSaveFileName( nullptr, "Save screenshot to...", QDir::currentPath(), m_PNGExtension + ";;" + m_JPGExtension, &filter); vtkRenderer *renderer = this->GetSelectedRenderWindow()->GetRenderer()->GetVtkRenderer(); if (renderer == nullptr) return; this->TakeScreenshot(renderer, 4, fileName, filter); } void QmitkSimpleExampleView::OnTakeScreenshot() { QString filter; QString fileName = QFileDialog::getSaveFileName( nullptr, "Save screenshot to...", QDir::currentPath(), m_PNGExtension + ";;" + m_JPGExtension, &filter); QmitkRenderWindow *renWin = this->GetSelectedRenderWindow(); if (renWin == nullptr) return; vtkRenderer *renderer = renWin->GetRenderer()->GetVtkRenderer(); if (renderer == nullptr) return; this->TakeScreenshot(renderer, 1, fileName, filter); } void QmitkSimpleExampleView::TakeScreenshot(vtkRenderer *renderer, unsigned int magnificationFactor, QString fileName, QString filter) { if ((renderer == nullptr) || (magnificationFactor < 1) || fileName.isEmpty()) return; bool doubleBuffering(renderer->GetRenderWindow()->GetDoubleBuffer()); renderer->GetRenderWindow()->DoubleBufferOff(); vtkImageWriter *fileWriter = nullptr; QFileInfo fi(fileName); QString suffix = fi.suffix().toLower(); if (suffix.isEmpty() || (suffix != "png" && suffix != "jpg" && suffix != "jpeg")) { if (filter == m_PNGExtension) { suffix = "png"; } else if (filter == m_JPGExtension) { suffix = "jpg"; } fileName += "." + suffix; } if (suffix.compare("jpg", Qt::CaseInsensitive) == 0 || suffix.compare("jpeg", Qt::CaseInsensitive) == 0) { vtkJPEGWriter *w = vtkJPEGWriter::New(); w->SetQuality(100); w->ProgressiveOff(); fileWriter = w; } else // default is png { fileWriter = vtkPNGWriter::New(); } vtkRenderLargeImage *magnifier = vtkRenderLargeImage::New(); magnifier->SetInput(renderer); magnifier->SetMagnification(magnificationFactor); fileWriter->SetInputConnection(magnifier->GetOutputPort()); fileWriter->SetFileName(fileName.toLatin1()); // vtkRenderLargeImage has problems with different layers, therefore we have to // temporarily deactivate all other layers. // we set the background to white, because it is nicer than black... double oldBackground[3]; renderer->GetBackground(oldBackground); double white[] = {1.0, 1.0, 1.0}; renderer->SetBackground(white); mitk::IRenderWindowPart *renderWindowPart = this->GetRenderWindowPart(); renderWindowPart->EnableDecorations(false); fileWriter->Write(); fileWriter->Delete(); renderWindowPart->EnableDecorations(true); renderer->SetBackground(oldBackground); renderer->GetRenderWindow()->SetDoubleBuffer(doubleBuffering); } void QmitkSimpleExampleView::RenderWindowSelected(const QString &id) { if (!id.isEmpty()) { m_SliceStepper.reset(new QmitkStepperAdapter( m_Controls->sliceNavigator, this->GetRenderWindowPart()->GetQmitkRenderWindow(id)->GetSliceNavigationController()->GetSlice(), "sliceNavigatorFromSimpleExample")); } } diff --git a/MITKConfig.cmake.in b/MITKConfig.cmake.in index e26525b752..b2d7018bc1 100644 --- a/MITKConfig.cmake.in +++ b/MITKConfig.cmake.in @@ -1,338 +1,316 @@ if(CMAKE_VERSION VERSION_LESS @MITK_CMAKE_MINIMUM_REQUIRED_VERSION@) message(FATAL_ERROR "MITK requires at least CMake Version @MITK_CMAKE_MINIMUM_REQUIRED_VERSION@") endif() # The MITK version number set(MITK_VERSION_MAJOR "@MITK_VERSION_MAJOR@") set(MITK_VERSION_MINOR "@MITK_VERSION_MINOR@") set(MITK_VERSION_PATCH "@MITK_VERSION_PATCH@") set(MITK_VERSION_STRING "@MITK_VERSION_STRING@") #----------------------------------------------------------------------------- # C++ language standard #----------------------------------------------------------------------------- set(MITK_CXX_STANDARD @MITK_CXX_STANDARD@) #----------------------------------------------------------------------------- # Include required CMake scripts #----------------------------------------------------------------------------- # Update the CMake module path set(MITK_CMAKE_MODULE_PATH "@MITK_SOURCE_DIR@/CMake") list(APPEND CMAKE_MODULE_PATH ${MITK_CMAKE_MODULE_PATH}) # Standard CMake macros include(CMakeParseArguments) include(FeatureSummary) include(FindPackageHandleStandardArgs) include(GenerateExportHeader) # Include MITK macros include(MacroParseArguments) include(mitkFunctionAddCustomModuleTest) include(mitkFunctionCheckMitkCompatibility) include(mitkFunctionCheckModuleDependencies) include(mitkFunctionConfigureVisualStudioUserProjectFile) include(mitkFunctionCreateBlueBerryApplication) include(mitkFunctionCreateCommandLineApp) include(mitkFunctionCreateModule) include(mitkFunctionCreatePlugin) include(mitkFunctionCreateProvisioningFile) include(mitkFunctionCreateWindowsBatchScript) include(mitkFunctionGetLibrarySearchPaths) include(mitkFunctionInstallAutoLoadModules) include(mitkFunctionInstallCTKPlugin) include(mitkFunctionInstallProvisioningFiles) include(mitkFunctionInstallThirdPartyCTKPlugins) include(mitkFunctionOrganizeSources) include(mitkFunctionUseModules) include(mitkMacroCreateExecutable) include(mitkMacroCreateModuleTests) include(mitkMacroFindDependency) include(mitkMacroGenerateToolsLibrary) include(mitkMacroGetPMDPlatformString) include(mitkMacroInstall) include(mitkMacroInstallHelperApp) include(mitkMacroInstallTargets) include(mitkMacroMultiplexPicType) #----------------------------------------------------------------------------- # MITK flags and directories #----------------------------------------------------------------------------- # MITK compiler flags set(MITK_C_FLAGS "@MITK_C_FLAGS@") set(MTTK_C_FLAGS_DEBUG "@MITK_C_FLAGS_DEBUG@") set(MITK_C_FLAGS_RELEASE "@MITK_C_FLAGS_RELEASE@") set(MITK_CXX_FLAGS "@MITK_CXX_FLAGS@") set(MTTK_CXX_FLAGS_DEBUG "@MITK_CXX_FLAGS_DEBUG@") set(MITK_CXX_FLAGS_RELEASE "@MITK_CXX_FLAGS_RELEASE@") # MITK linker flags set(MITK_EXE_LINKER_FLAGS "@MITK_EXE_LINKER_FLAGS@") set(MITK_SHARED_LINKER_FLAGS "@MITK_SHARED_LINKER_FLAGS@") set(MITK_MODULE_LINKER_FLAGS "@MITK_MODULE_LINKER_FLAGS@") # MITK specific directories set(MITK_SOURCE_DIR "@MITK_SOURCE_DIR@") set(MITK_BINARY_DIR "@MITK_BINARY_DIR@") set(MITK_CMAKE_DIR "@MITK_CMAKE_DIR@") # MITK output directories set(MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY "@MITK_CMAKE_RUNTIME_OUTPUT_DIRECTORY@") set(MITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY "@MITK_CMAKE_ARCHIVE_OUTPUT_DIRECTORY@") set(MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY "@MITK_CMAKE_LIBRARY_OUTPUT_DIRECTORY@") #----------------------------------------------------------------------------- # Miscellaneous variables #----------------------------------------------------------------------------- # Internal version numbers, used for approximate compatibility checks # of a MITK development version (non-release). set(MITK_VERSION_PLUGIN_SYSTEM 2) # dropped legacy BlueBerry plug-in CMake support set(MITK_DATA_DIR "@MITK_DATA_DIR@") set(UTILITIES_DIR "@UTILITIES_DIR@") set(REGISTER_QFUNCTIONALITY_CPP_IN "@REGISTER_QFUNCTIONALITY_CPP_IN@") set(MITK_DOXYGEN_TAGFILE_NAME "@MITK_DOXYGEN_TAGFILE_NAME@") set(MITK_LEGACY_EXPORT_MACRO_NAME 1) set(DCMTK_CMAKE_DEBUG_POSTFIX @DCMTK_CMAKE_DEBUG_POSTFIX@) # Get the canonical name of the directory to avoid potential case mismatch, # e.g. in the drive letter on Windows. get_filename_component(CMAKE_CURRENT_LIST_DIR_REALPATH ${CMAKE_CURRENT_LIST_DIR} REALPATH) if(CMAKE_CURRENT_LIST_DIR_REALPATH STREQUAL MITK_BINARY_DIR) set(MITK_EXTERNAL_PROJECT_PREFIX @MITK_EXTERNAL_PROJECT_PREFIX@) endif() set(MITK_MODULES_PACKAGE_DEPENDS_DIR "@MITK_MODULES_PACKAGE_DEPENDS_DIR@") if(MODULES_PACKAGE_DEPENDS_DIRS) list(APPEND MODULES_PACKAGE_DEPENDS_DIRS ${MITK_MODULES_PACKAGE_DEPENDS_DIR}) list(REMOVE_DUPLICATES MODULES_PACKAGE_DEPENDS_DIRS) else() set(MODULES_PACKAGE_DEPENDS_DIRS ${MITK_MODULES_PACKAGE_DEPENDS_DIR}) endif() #----------------------------------------------------------------------------- # External dependencies #----------------------------------------------------------------------------- list(APPEND CMAKE_PREFIX_PATH "@MITK_EXTERNAL_PROJECT_PREFIX@") # ----------------------------------------- # Qt variables and dependencies set(MITK_USE_Qt5 @MITK_USE_Qt5@) set(MITK_USE_Qt5_WebEngine @MITK_USE_Qt5_WebEngine@) if(MITK_USE_Qt5) set(MITK_QT5_MINIMUM_VERSION @MITK_QT5_MINIMUM_VERSION@) set(MITK_QT5_COMPONENTS @MITK_QT5_COMPONENTS@) mitkMacroFindDependency(Qt5 ${MITK_QT5_MINIMUM_VERSION} COMPONENTS ${MITK_QT5_COMPONENTS}) endif() # ----------------------------------------- # Special Python variables set(MITK_USE_Python @MITK_USE_Python@) set(MITK_USE_SYSTEM_PYTHON @MITK_USE_SYSTEM_PYTHON@) if(MITK_USE_Python) set(PYTHON_EXECUTABLE "@PYTHON_EXECUTABLE@" CACHE FILEPATH "") set(PYTHON_INCLUDE_DIR "@PYTHON_INCLUDE_DIR@" CACHE PATH "") set(PYTHON_LIBRARY "@PYTHON_LIBRARY@" CACHE FILEPATH "") set(PYTHON_INCLUDE_DIR2 "@PYTHON_INCLUDE_DIR2@" CACHE PATH "") mitkMacroFindDependency(PythonLibs) mitkMacroFindDependency(PythonInterp) endif() # ----------------------------------------- # Special Boost variables set(MITK_USE_Boost_LIBRARIES @MITK_USE_Boost_LIBRARIES@) set(MITK_USE_SYSTEM_Boost @MITK_USE_SYSTEM_Boost@) set(BOOST_ROOT "@BOOST_ROOT@" CACHE PATH "") set(BOOST_LIBRARYDIR "@BOOST_LIBRARYDIR@" CACHE PATH "") set(Boost_ADDITIONAL_VERSIONS "1.64" "1.64.0") # We need this later for a DCMTK workaround set(_dcmtk_dir_orig "@DCMTK_DIR@") # ----------------------------------------- # External dependencies from the superbuild # or injected from somewhere else via # _DIR variables. @MITK_CONFIG_EXTERNAL_PROJECTS@ # Ensure the MITK module path comes first set(CMAKE_MODULE_PATH ${MITK_CMAKE_MODULE_PATH} ${CMAKE_MODULE_PATH}) # ----------------------------------------- # Special handling for DCMTK if(MITK_USE_DCMTK) # Due to the preferred CONFIG mode in find_package calls above, # the DCMTKConfig.cmake file is read, which does not provide useful # package information. We explictly need MODULE mode to find DCMTK. if(${_dcmtk_dir_orig} MATCHES "${MITK_EXTERNAL_PROJECT_PREFIX}.*") # Help our FindDCMTK.cmake script find our super-build DCMTK set(DCMTK_DIR ${MITK_EXTERNAL_PROJECT_PREFIX}) else() # Use the original value set(DCMTK_DIR ${_dcmtk_dir_orig}) endif() find_package(DCMTK REQUIRED MODULE) endif() # ----------------------------------------- # Special handling for DCMQI if(MITK_USE_DCMQI) # Due to the preferred CONFIG mode in find_package calls above, # the DCMQIConfig.cmake file is read, which does not provide useful # package information. We explictly need MODULE mode to find DCMQI. # Help our FindDCMQI.cmake script find our super-build DCMQI set(DCMQI_DIR ${MITK_EXTERNAL_PROJECT_PREFIX}) find_package(DCMQI REQUIRED) endif() -# ----------------------------------------- -# Special handling for SOFA - -if(MITK_USE_SOFA) - # The SOFAConfig.cmake file does not provide exported targets or - # libraries with absolute paths, hence we need to make the link - # directories globally available until the SOFAConfig.cmake file - # supports a proper mechanism for handling targets. -# find_package(SOFA PATHS ${SOFA_DIR} CONFIG REQUIRED) - link_directories(${SOFA_LIBRARY_DIRS}) -endif() - -# ----------------------------------------- -# Special handling for VMTK - -if(MITK_USE_VMTK) - # Same as SOFA above - link_directories(${VMTK_LIBRARY_DIRS}) -endif() - # ----------------------------------------- # Special handling for Boost if(MITK_USE_Boost) - # Same as SOFA above link_directories(${Boost_LIBRARY_DIRS}) endif() # ----------------------------------------- # Special handling for OpenIGTLink if(MITK_USE_OpenIGTLink) - # Same as SOFA above link_directories(${OpenIGTLink_LIBRARY_DIRS}) endif() # ----------------------------------------- # Internal project dependencies set(CppMicroServices_DIR "@CppMicroServices_DIR@") mitkMacroFindDependency(CppMicroServices) set(MITK_USE_BLUEBERRY @MITK_USE_BLUEBERRY@) if(MITK_USE_BLUEBERRY) set(MITK_PLUGIN_USE_FILE "@MITK_PLUGIN_USE_FILE@") if(MITK_PLUGIN_USE_FILE) if(EXISTS "${MITK_PLUGIN_USE_FILE}") include("${MITK_PLUGIN_USE_FILE}") endif() endif() set(MITK_PLUGIN_PROVISIONING_FILE "@MITK_EXTAPP_PROVISIONING_FILE@") set(MITK_PROVISIONING_FILES "${BLUEBERRY_PLUGIN_PROVISIONING_FILE}" "${MITK_PLUGIN_PROVISIONING_FILE}") endif() set(BLUEBERRY_USE_QT_HELP @BLUEBERRY_USE_QT_HELP@) if(BLUEBERRY_USE_QT_HELP AND DOXYGEN_VERSION VERSION_LESS "1.8.7") message("Setting BLUEBERRY_USE_QT_HELP to OFF because Doxygen version 1.8.7 or newer not found.") set(BLUEBERRY_USE_QT_HELP OFF) endif() set(BLUEBERRY_QTPLUGIN_PATH "@BLUEBERRY_QTPLUGIN_PATH@") set(QT_HELPGENERATOR_EXECUTABLE "@QT_HELPGENERATOR_EXECUTABLE@") set(QT_COLLECTIONGENERATOR_EXECUTABLE "@QT_COLLECTIONGENERATOR_EXECUTABLE@") set(QT_ASSISTANT_EXECUTABLE "@QT_ASSISTANT_EXECUTABLE@") set(QT_XMLPATTERNS_EXECUTABLE "@QT_XMLPATTERNS_EXECUTABLE@") #----------------------------------------------------------------------------- # MITK sub-project variables #----------------------------------------------------------------------------- # External SDK directories set(MITK_PMD_SDK_DIR @MITK_PMD_SDK_DIR@) # MITK ToF use variables set(MITK_TOF_PMDCAMCUBE_AVAILABLE @MITK_USE_TOF_PMDCAMCUBE@) if(MITK_TOF_PMDCAMCUBE_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK") option(MITK_USE_TOF_PMDCAMCUBE "Enable support for PMD Cam Cube" @MITK_USE_TOF_PMDCAMCUBE@) mark_as_advanced(MITK_USE_TOF_PMDCAMCUBE) endif() set(MITK_TOF_PMDCAMBOARD_AVAILABLE @MITK_USE_TOF_PMDCAMBOARD@) if(MITK_TOF_PMDCAMBOARD_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK") option(MITK_USE_TOF_PMDCAMBOARD "Enable support for PMD Cam Board" @MITK_USE_TOF_PMDCAMBOARD@) mark_as_advanced(MITK_USE_TOF_PMDCAMBOARD) endif() set(MITK_TOF_PMDO3_AVAILABLE @MITK_USE_TOF_PMDO3@) if(MITK_TOF_PMDO3_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK") option(MITK_USE_TOF_PMDO3 "Enable support for PMD =3" @MITK_USE_TOF_PMDO3@) mark_as_advanced(MITK_USE_TOF_PMDO3) endif() set(MITK_TOF_KINECT_AVAILABLE @MITK_USE_TOF_KINECT@) if(MITK_TOF_KINECT_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK") option(MITK_USE_TOF_KINECT "Enable support for Kinect" @MITK_USE_TOF_KINECT@) mark_as_advanced(MITK_USE_TOF_KINECT) endif() set(MITK_TOF_MESASR4000_AVAILABLE @MITK_USE_TOF_MESASR4000@) if(MITK_TOF_MESASR4000_AVAILABLE AND NOT ${PROJECT_NAME} STREQUAL "MITK") option(MITK_USE_TOF_MESASR4000 "Enable support for MESA SR4000" @MITK_USE_TOF_MESASR4000@) mark_as_advanced(MITK_USE_TOF_MESASR4000) endif() if(MITK_USE_IGT) #include("${MITK_DIR}/mitkIGTConfig.cmake") endif() #----------------------------------------------------------------------------- # Import MITK targets and set custom properties #----------------------------------------------------------------------------- if(NOT MITK_EXPORTS_FILE_INCLUDED) if(EXISTS "@MITK_EXPORTS_FILE@") set(MITK_EXPORTS_FILE_INCLUDED 1) include("@MITK_EXPORTS_FILE@") endif() endif() # Set properties on exported targets @MITK_EXPORTED_TARGET_PROPERTIES@ #----------------------------------------------------------------------------- # Install rules #----------------------------------------------------------------------------- # Install rules for ToF libraries loaded at runtime if(EXISTS "@MITK_BINARY_DIR@/mitkToFHardwareInstallRules.cmake") include("@MITK_BINARY_DIR@/mitkToFHardwareInstallRules.cmake") endif() diff --git a/Modules/AlgorithmsExt/src/mitkMovieGenerator.cpp b/Modules/AlgorithmsExt/src/mitkMovieGenerator.cpp index 97932560ca..f52cd1cbd6 100755 --- a/Modules/AlgorithmsExt/src/mitkMovieGenerator.cpp +++ b/Modules/AlgorithmsExt/src/mitkMovieGenerator.cpp @@ -1,143 +1,143 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkMovieGenerator.h" #include "mitkConfig.h" -#include "mitkGL.h" #include +#include "vtk_glew.h" #if WIN32 #ifndef __GNUC__ //#if ! (_MSC_VER >= 1400) #include "mitkMovieGeneratorWin32.h" //#endif #else #include "GL/glext.h" #endif #endif #ifndef GL_BGR #define GL_BGR GL_BGR_EXT #endif mitk::MovieGenerator::MovieGenerator() : m_stepper(nullptr), m_renderer(nullptr), m_width(0), m_height(0), m_initialized(false), m_FrameRate(20) { m_fileName[0] = 0; } mitk::MovieGenerator::Pointer mitk::MovieGenerator::New() { Pointer smartPtr; MovieGenerator *rawPtr = ::itk::ObjectFactory::Create(); if (rawPtr == nullptr) { #ifdef WIN32 #ifndef __GNUC__ //#if ! (_MSC_VER >= 1400) mitk::MovieGenerator::Pointer wp = static_cast(mitk::MovieGeneratorWin32::New()); return wp; //#endif #endif #endif } smartPtr = rawPtr; if (rawPtr != nullptr) rawPtr->UnRegister(); return smartPtr; } bool mitk::MovieGenerator::WriteMovie() { bool ok = false; if (m_stepper) { if (m_renderer) m_renderer->GetRenderWindow()->MakeCurrent(); // m_stepper->First(); RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow()); ok = InitGenerator(); if (!ok) { TerminateGenerator(); return false; } int imgSize = 3 * m_width * m_height; printf("Video size = %i x %i\n", m_width, m_height); GLbyte *data = new GLbyte[imgSize]; // duplicate steps if pingPong option is switched to on. unsigned int numOfSteps = m_stepper->GetSteps(); if (m_stepper->GetPingPong()) numOfSteps *= 2; for (unsigned int i = 0; i < numOfSteps; i++) { if (m_renderer) m_renderer->GetRenderWindow()->MakeCurrent(); RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow()); glReadPixels(5, 5, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void *)data); AddFrame(data); m_stepper->Next(); } ok = TerminateGenerator(); delete[] data; } return ok; } bool mitk::MovieGenerator::WriteCurrentFrameToMovie() { if (m_renderer) { m_renderer->GetRenderWindow()->MakeCurrent(); if (!m_initialized) { RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow()); m_initialized = InitGenerator(); } if (!m_initialized) { TerminateGenerator(); return false; } int imgSize = 3 * m_width * m_height; GLbyte *data = new GLbyte[imgSize]; RenderingManager::GetInstance()->ForceImmediateUpdate(m_renderer->GetRenderWindow()); glReadPixels(5, 5, m_width, m_height, GL_BGR, GL_UNSIGNED_BYTE, (void *)data); AddFrame(data); delete[] data; } return true; } void mitk::MovieGenerator::ReleaseMovieWriter() { TerminateGenerator(); m_initialized = false; } void mitk::MovieGenerator::SetFrameRate(unsigned int rate) { m_FrameRate = rate; } unsigned int mitk::MovieGenerator::GetFrameRate() { return m_FrameRate; } diff --git a/Modules/Annotation/src/mitkVtkLogoRepresentation.cxx b/Modules/Annotation/src/mitkVtkLogoRepresentation.cxx index bce367bb24..ad4e2a2639 100644 --- a/Modules/Annotation/src/mitkVtkLogoRepresentation.cxx +++ b/Modules/Annotation/src/mitkVtkLogoRepresentation.cxx @@ -1,189 +1,190 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkVtkLogoRepresentation.h" #include "vtkActor2D.h" #include "vtkCallbackCommand.h" #include "vtkCellArray.h" #include "vtkFloatArray.h" #include "vtkImageData.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper2D.h" #include "vtkPolyDataMapper2D.h" #include "vtkPropCollection.h" #include "vtkProperty2D.h" #include "vtkRenderer.h" #include "vtkTexture.h" #include "vtkWindow.h" vtkStandardNewMacro(mitkVtkLogoRepresentation); //---------------------------------------------------------------------- inline void mitkVtkLogoRepresentation::AdjustImageSize(double /*o*/[2], double borderSize[2], double imageSize[2]) { // Scale the image to fit with in the border. // Also update the origin so the image is centered. double r0 = borderSize[0] / imageSize[0]; double r1 = borderSize[1] / imageSize[1]; if (r0 > r1) { imageSize[0] *= r1; imageSize[1] *= r1; } else { imageSize[0] *= r0; imageSize[1] *= r0; } } //------------------------------------------------------------------------- void mitkVtkLogoRepresentation::BuildRepresentation() { if (this->GetMTime() > this->BuildTime || (this->Renderer && this->Renderer->GetVTKWindow() && this->Renderer->GetVTKWindow()->GetMTime() > this->BuildTime)) { // Determine and adjust the size of the image if (this->Image) { double imageSize[2], borderSize[2], o[2]; imageSize[0] = 0.0; imageSize[1] = 0.0; // this->Image->Update(); if (this->Image->GetDataDimension() == 2) { int dims[3]; this->Image->GetDimensions(dims); imageSize[0] = static_cast(dims[0]); imageSize[1] = static_cast(dims[1]); } int *p1 = this->PositionCoordinate->GetComputedDisplayValue(this->Renderer); int *p2 = this->Position2Coordinate->GetComputedDisplayValue(this->Renderer); borderSize[0] = p2[0]; borderSize[1] = p2[1]; o[0] = static_cast(p1[0]); o[1] = static_cast(p1[1]); // this preserves the image aspect ratio. The image is // centered around the center of the bordered ragion. this->AdjustImageSize(o, borderSize, imageSize); // Update the points this->Texture->SetInputData(this->Image); int *size = this->Renderer->GetSize(); switch (this->cornerPosition) { case 0: { this->TexturePoints->SetPoint(0, o[0], o[1], 0.0); this->TexturePoints->SetPoint(1, o[0] + imageSize[0], o[1], 0.0); this->TexturePoints->SetPoint(2, o[0] + imageSize[0], o[1] + imageSize[1], 0.0); this->TexturePoints->SetPoint(3, o[0], o[1] + imageSize[1], 0.0); break; } case 1: { o[0] = size[0] - o[0]; this->TexturePoints->SetPoint(0, o[0] - imageSize[0], o[1], 0.0); this->TexturePoints->SetPoint(1, o[0], o[1], 0.0); this->TexturePoints->SetPoint(2, o[0], o[1] + imageSize[1], 0.0); this->TexturePoints->SetPoint(3, o[0] - imageSize[0], o[1] + imageSize[1], 0.0); break; } case 2: { o[0] = size[0] - o[0]; o[1] = size[1] - o[1]; this->TexturePoints->SetPoint(0, o[0] - imageSize[0], o[1] - imageSize[1], 0.0); this->TexturePoints->SetPoint(1, o[0], o[1] - imageSize[1], 0.0); this->TexturePoints->SetPoint(2, o[0], o[1], 0.0); this->TexturePoints->SetPoint(3, o[0] - imageSize[0], o[1], 0.0); break; } case 3: { o[1] = size[1] - o[1]; this->TexturePoints->SetPoint(0, o[0], o[1] - imageSize[1], 0.0); this->TexturePoints->SetPoint(1, o[0] + imageSize[0], o[1] - imageSize[1], 0.0); this->TexturePoints->SetPoint(2, o[0] + imageSize[0], o[1], 0.0); this->TexturePoints->SetPoint(3, o[0], o[1], 0.0); break; } case 4: { double ish[2]; // ish = middle of the image ish[0] = imageSize[0] / 2.0; ish[1] = imageSize[1] / 2.0; // o = middle of the window o[0] = (size[0]) / 2.0; o[1] = (size[1]) / 2.0; this->TexturePoints->SetPoint(0, o[0] - ish[0], o[1] - ish[1], 0.0); this->TexturePoints->SetPoint(1, o[0] + ish[0], o[1] - ish[1], 0.0); this->TexturePoints->SetPoint(2, o[0] + ish[0], o[1] + ish[1], 0.0); this->TexturePoints->SetPoint(3, o[0] - ish[0], o[1] + ish[1], 0.0); break; } default: { this->TexturePoints->SetPoint(0, o[0], o[1], 0.0); this->TexturePoints->SetPoint(1, o[0] + imageSize[0], o[1], 0.0); this->TexturePoints->SetPoint(2, o[0] + imageSize[0], o[1] + imageSize[1], 0.0); this->TexturePoints->SetPoint(3, o[0], o[1] + imageSize[1], 0.0); } } } } + this->TexturePoints->Modified(); } mitkVtkLogoRepresentation::mitkVtkLogoRepresentation() : cornerPosition(0) { } mitkVtkLogoRepresentation::~mitkVtkLogoRepresentation() { } //------------------------------------------------------------------------- void mitkVtkLogoRepresentation::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); if (this->Image) { os << indent << "Image:\n"; this->Image->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "Image: (none)\n"; } if (this->ImageProperty) { os << indent << "Image Property:\n"; this->ImageProperty->PrintSelf(os, indent.GetNextIndent()); } else { os << indent << "Image Property: (none)\n"; } } diff --git a/Modules/ContourModel/Algorithms/mitkContourObjectFactory.cpp b/Modules/ContourModel/Algorithms/mitkContourObjectFactory.cpp index 3018b181e8..9682361546 100644 --- a/Modules/ContourModel/Algorithms/mitkContourObjectFactory.cpp +++ b/Modules/ContourModel/Algorithms/mitkContourObjectFactory.cpp @@ -1,149 +1,148 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourObjectFactory.h" #include "mitkBaseRenderer.h" #include "mitkCoreObjectFactory.h" #include "mitkDataNode.h" #include "mitkProperties.h" #include "mitkContourModel.h" #include "mitkContourModelGLMapper2D.h" #include "mitkContourModelMapper2D.h" #include "mitkContourModelMapper3D.h" #include "mitkContourModelSet.h" #include "mitkContourModelSetGLMapper2D.h" #include "mitkContourModelSetMapper3D.h" #include "mitkContourModelSetWriter.h" #include "mitkContourModelWriter.h" -#include "mitkVtkGLMapperWrapper.h" mitk::ContourObjectFactory::ContourObjectFactory() : CoreObjectFactoryBase() { static bool alreadyDone = false; if (!alreadyDone) { MITK_DEBUG << "ContourObjectFactory c'tor" << std::endl; alreadyDone = true; } } mitk::ContourObjectFactory::~ContourObjectFactory() { } mitk::Mapper::Pointer mitk::ContourObjectFactory::CreateMapper(mitk::DataNode *node, MapperSlotId id) { mitk::Mapper::Pointer newMapper = nullptr; if (id == mitk::BaseRenderer::Standard2D) { std::string classname("ContourModel"); if (dynamic_cast(node->GetData()) != nullptr) { - newMapper = mitk::VtkGLMapperWrapper::New(mitk::ContourModelGLMapper2D::New().GetPointer()); + newMapper = mitk::ContourModelGLMapper2D::New(); newMapper->SetDataNode(node); } else if (dynamic_cast(node->GetData()) != nullptr) { - newMapper = mitk::VtkGLMapperWrapper::New(mitk::ContourModelSetGLMapper2D::New().GetPointer()); + newMapper = mitk::ContourModelSetGLMapper2D::New(); newMapper->SetDataNode(node); } } else if (id == mitk::BaseRenderer::Standard3D) { if (dynamic_cast(node->GetData()) != nullptr) { newMapper = mitk::ContourModelMapper3D::New(); newMapper->SetDataNode(node); } else if (dynamic_cast(node->GetData()) != nullptr) { newMapper = mitk::ContourModelSetMapper3D::New(); newMapper->SetDataNode(node); } } return newMapper; } void mitk::ContourObjectFactory::SetDefaultProperties(mitk::DataNode *node) { if (node == nullptr) return; mitk::DataNode::Pointer nodePointer = node; if (node->GetData() == nullptr) return; if (dynamic_cast(node->GetData()) != nullptr) { mitk::ContourModelGLMapper2D::SetDefaultProperties(node); mitk::ContourModelMapper3D::SetDefaultProperties(node); } else if (dynamic_cast(node->GetData()) != nullptr) { mitk::ContourModelSetGLMapper2D::SetDefaultProperties(node); mitk::ContourModelSetMapper3D::SetDefaultProperties(node); } } const char *mitk::ContourObjectFactory::GetFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_FileExtensionsMap, fileExtension); return fileExtension.c_str(); }; mitk::CoreObjectFactoryBase::MultimapType mitk::ContourObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } mitk::CoreObjectFactoryBase::MultimapType mitk::ContourObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } void mitk::ContourObjectFactory::CreateFileExtensionsMap() { } const char *mitk::ContourObjectFactory::GetSaveFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); return fileExtension.c_str(); } void mitk::ContourObjectFactory::RegisterIOFactories() { } struct RegisterContourObjectFactory { RegisterContourObjectFactory() : m_Factory(mitk::ContourObjectFactory::New()) { mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(m_Factory); } ~RegisterContourObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory(m_Factory); } mitk::ContourObjectFactory::Pointer m_Factory; }; static RegisterContourObjectFactory registerContourObjectFactory; diff --git a/Modules/ContourModel/Rendering/mitkContourModelGLMapper2D.cpp b/Modules/ContourModel/Rendering/mitkContourModelGLMapper2D.cpp index f58e07f0ae..2a459e7c33 100644 --- a/Modules/ContourModel/Rendering/mitkContourModelGLMapper2D.cpp +++ b/Modules/ContourModel/Rendering/mitkContourModelGLMapper2D.cpp @@ -1,105 +1,105 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourModelGLMapper2D.h" #include "mitkBaseRenderer.h" #include "mitkColorProperty.h" #include "mitkContourModel.h" #include "mitkContourModelSubDivisionFilter.h" #include "mitkPlaneGeometry.h" #include "mitkProperties.h" #include #include "mitkGL.h" mitk::ContourModelGLMapper2D::ContourModelGLMapper2D() : m_SubdivisionContour(mitk::ContourModel::New()), m_InitSubdivisionCurve(true) { } mitk::ContourModelGLMapper2D::~ContourModelGLMapper2D() { } -void mitk::ContourModelGLMapper2D::Paint(mitk::BaseRenderer *renderer) +void mitk::ContourModelGLMapper2D::MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType /*type*/) { BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer); mitk::DataNode *dataNode = this->GetDataNode(); bool visible = true; dataNode->GetVisibility(visible, renderer, "visible"); if (!visible) return; mitk::ContourModel *input = this->GetInput(); mitk::ContourModel::Pointer renderingContour = input; bool subdivision = false; dataNode->GetBoolProperty("subdivision curve", subdivision, renderer); if (subdivision) { if (this->m_SubdivisionContour->GetMTime() < renderingContour->GetMTime() || m_InitSubdivisionCurve) { // mitk::ContourModel::Pointer subdivContour = mitk::ContourModel::New(); mitk::ContourModelSubDivisionFilter::Pointer subdivFilter = mitk::ContourModelSubDivisionFilter::New(); subdivFilter->SetInput(input); subdivFilter->Update(); this->m_SubdivisionContour = subdivFilter->GetOutput(); m_InitSubdivisionCurve = false; } renderingContour = this->m_SubdivisionContour; } this->DrawContour(renderingContour, renderer); ls->UpdateGenerateDataTime(); } mitk::ContourModel *mitk::ContourModelGLMapper2D::GetInput(void) { return const_cast(static_cast(GetDataNode()->GetData())); } void mitk::ContourModelGLMapper2D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { node->AddProperty("contour.color", ColorProperty::New(0.9, 1.0, 0.1), renderer, overwrite); node->AddProperty("contour.points.color", ColorProperty::New(1.0, 0.0, 0.1), renderer, overwrite); node->AddProperty("contour.points.show", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contour.segments.show", mitk::BoolProperty::New(true), renderer, overwrite); node->AddProperty("contour.controlpoints.show", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contour.width", mitk::FloatProperty::New(1.0), renderer, overwrite); node->AddProperty("contour.hovering.width", mitk::FloatProperty::New(3.0), renderer, overwrite); node->AddProperty("contour.hovering", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contour.points.text", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contour.controlpoints.text", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("subdivision curve", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contour.project-onto-plane", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("opacity", mitk::FloatProperty::New(1.0f), renderer, overwrite); Superclass::SetDefaultProperties(node, renderer, overwrite); } diff --git a/Modules/ContourModel/Rendering/mitkContourModelGLMapper2D.h b/Modules/ContourModel/Rendering/mitkContourModelGLMapper2D.h index 91332cbf5c..4fde9f2bd4 100644 --- a/Modules/ContourModel/Rendering/mitkContourModelGLMapper2D.h +++ b/Modules/ContourModel/Rendering/mitkContourModelGLMapper2D.h @@ -1,69 +1,69 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITK_ContourModelGLMapper2D_H_ #define MITK_ContourModelGLMapper2D_H_ #include "mitkCommon.h" #include "mitkContourModel.h" #include "mitkContourModelGLMapper2DBase.h" #include namespace mitk { class BaseRenderer; class ContourModel; /** * @brief OpenGL-based mapper to display a mitk::Contour object in a 2D render window * * * @ingroup MitkContourModelModule */ class MITKCONTOURMODEL_EXPORT ContourModelGLMapper2D : public ContourModelGLMapper2DBase { public: mitkClassMacro(ContourModelGLMapper2D, ContourModelGLMapper2DBase); itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** * reimplemented from Baseclass */ - virtual void Paint(BaseRenderer *renderer) override; + virtual void MitkRender(BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type) override; static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); LocalStorageHandler m_LSH; protected: ContourModelGLMapper2D(); virtual ~ContourModelGLMapper2D(); mitk::ContourModel::Pointer m_SubdivisionContour; bool m_InitSubdivisionCurve; private: /** * return a refernce of the rendered data object */ ContourModel *GetInput(void); }; } // namespace mitk #endif diff --git a/Modules/ContourModel/Rendering/mitkContourModelGLMapper2DBase.cpp b/Modules/ContourModel/Rendering/mitkContourModelGLMapper2DBase.cpp index 912e0806d8..df2fc88426 100644 --- a/Modules/ContourModel/Rendering/mitkContourModelGLMapper2DBase.cpp +++ b/Modules/ContourModel/Rendering/mitkContourModelGLMapper2DBase.cpp @@ -1,370 +1,396 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourModelSetGLMapper2D.h" #include "mitkColorProperty.h" #include "mitkContourModelSet.h" #include "mitkPlaneGeometry.h" #include "mitkProperties.h" #include +#include "vtkPen.h" +#include "vtkContext2D.h" +#include "vtkContextDevice2D.h" +#include "vtkOpenGLContextDevice2D.h" #include "mitkManualPlacementAnnotationRenderer.h" #include "mitkBaseRenderer.h" #include "mitkContourModel.h" #include "mitkTextAnnotation2D.h" -#include "mitkGL.h" - -mitk::ContourModelGLMapper2DBase::ContourModelGLMapper2DBase() +mitk::ContourModelGLMapper2DBase::ContourModelGLMapper2DBase(): m_Initialized(false) { m_PointNumbersAnnotation = mitk::TextAnnotation2D::New(); m_ControlPointNumbersAnnotation = mitk::TextAnnotation2D::New(); } mitk::ContourModelGLMapper2DBase::~ContourModelGLMapper2DBase() { } +void mitk::ContourModelGLMapper2DBase::Initialize(mitk::BaseRenderer *) +{ + vtkOpenGLContextDevice2D *device = NULL; + device = vtkOpenGLContextDevice2D::New(); + if (device) + { + this->m_Context->Begin(device); + device->Delete(); + this->m_Initialized = true; + } + else + { + } +} + +void mitk::ContourModelGLMapper2DBase::ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor * /*actor*/) +{ + float rgba[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; + // check for color prop and use it for rendering if it exists + GetDataNode()->GetColor(rgba, renderer, "color"); + // check for opacity prop and use it for rendering if it exists + GetDataNode()->GetOpacity(rgba[3], renderer, "opacity"); + + this->m_Context->GetPen()->SetColorF((double)rgba[0], (double)rgba[1], (double)rgba[2], (double)rgba[3]); +} + void mitk::ContourModelGLMapper2DBase::DrawContour(mitk::ContourModel *renderingContour, mitk::BaseRenderer *renderer) { if (std::find(m_RendererList.begin(), m_RendererList.end(), renderer) == m_RendererList.end()) { m_RendererList.push_back(renderer); } mitk::ManualPlacementAnnotationRenderer::AddAnnotation(m_PointNumbersAnnotation.GetPointer(), renderer); m_PointNumbersAnnotation->SetVisibility(false); mitk::ManualPlacementAnnotationRenderer::AddAnnotation(m_ControlPointNumbersAnnotation.GetPointer(), renderer); m_ControlPointNumbersAnnotation->SetVisibility(false); InternalDrawContour(renderingContour, renderer); } void mitk::ContourModelGLMapper2DBase::InternalDrawContour(mitk::ContourModel *renderingContour, mitk::BaseRenderer *renderer) { if (!renderingContour) return; + if (!this->m_Initialized) + { + this->Initialize(renderer); + } + vtkOpenGLContextDevice2D::SafeDownCast( + this->m_Context->GetDevice())->Begin(renderer->GetVtkRenderer()); mitk::DataNode *dataNode = this->GetDataNode(); renderingContour->UpdateOutputInformation(); unsigned int timestep = renderer->GetTimeStep(); if (!renderingContour->IsEmptyTimeStep(timestep)) { // apply color and opacity read from the PropertyList ApplyColorAndOpacityProperties(renderer); mitk::ColorProperty::Pointer colorprop = dynamic_cast(dataNode->GetProperty("contour.color", renderer)); float opacity = 0.5; dataNode->GetFloatProperty("opacity", opacity, renderer); if (colorprop) { // set the color of the contour double red = colorprop->GetColor().GetRed(); double green = colorprop->GetColor().GetGreen(); double blue = colorprop->GetColor().GetBlue(); - glColor4f(red, green, blue, opacity); + this->m_Context->GetPen()->SetColorF(red, green, blue, opacity); } mitk::ColorProperty::Pointer selectedcolor = dynamic_cast(dataNode->GetProperty("contour.points.color", renderer)); if (!selectedcolor) { selectedcolor = mitk::ColorProperty::New(1.0, 0.0, 0.1); } vtkLinearTransform *transform = dataNode->GetVtkTransform(); // ContourModel::OutputType point; mitk::Point3D point; mitk::Point3D p; float vtkp[3]; float lineWidth = 3.0; bool drawit = false; bool isHovering = false; dataNode->GetBoolProperty("contour.hovering", isHovering); if (isHovering) dataNode->GetFloatProperty("contour.hovering.width", lineWidth); else dataNode->GetFloatProperty("contour.width", lineWidth); bool showSegments = false; dataNode->GetBoolProperty("contour.segments.show", showSegments); bool showControlPoints = false; dataNode->GetBoolProperty("contour.controlpoints.show", showControlPoints); bool showPoints = false; dataNode->GetBoolProperty("contour.points.show", showPoints); bool showPointsNumbers = false; dataNode->GetBoolProperty("contour.points.text", showPointsNumbers); bool showControlPointsNumbers = false; dataNode->GetBoolProperty("contour.controlpoints.text", showControlPointsNumbers); bool projectmode = false; dataNode->GetVisibility(projectmode, renderer, "contour.project-onto-plane"); mitk::ContourModel::VertexIterator pointsIt = renderingContour->IteratorBegin(timestep); Point2D pt2d; // projected_p in display coordinates Point2D lastPt2d; int index = 0; mitk::ScalarType maxDiff = 0.25; while (pointsIt != renderingContour->IteratorEnd(timestep)) { lastPt2d = pt2d; point = (*pointsIt)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp, p); - renderer->WorldToDisplay(p, pt2d); + renderer->WorldToView(p, pt2d); ScalarType scalardiff = fabs(renderer->GetCurrentWorldPlaneGeometry()->SignedDistance(p)); // project to plane if (projectmode) { drawit = true; } else if (scalardiff < maxDiff) // point is close enough to be drawn { drawit = true; } else { drawit = false; } // draw line if (drawit) { if (showSegments) { // lastPt2d is not valid in first step if (!(pointsIt == renderingContour->IteratorBegin(timestep))) { - glLineWidth(lineWidth); - glBegin(GL_LINES); - glVertex2f(pt2d[0], pt2d[1]); - glVertex2f(lastPt2d[0], lastPt2d[1]); - glEnd(); - glLineWidth(1); + this->m_Context->GetPen()->SetWidth(lineWidth); + this->m_Context->DrawLine(pt2d[0], pt2d[1], lastPt2d[0], lastPt2d[1]); + this->m_Context->GetPen()->SetWidth(1); } } if (showControlPoints) { // draw ontrol points if ((*pointsIt)->IsControlPoint) { float pointsize = 4; Point2D tmp; Vector2D horz, vert; horz[1] = 0; vert[0] = 0; horz[0] = pointsize; vert[1] = pointsize; - glColor3f(selectedcolor->GetColor().GetRed(), - selectedcolor->GetColor().GetBlue(), - selectedcolor->GetColor().GetGreen()); - glLineWidth(1); + this->m_Context->GetPen()->SetColorF(selectedcolor->GetColor().GetRed(), + selectedcolor->GetColor().GetBlue(), + selectedcolor->GetColor().GetGreen()); + this->m_Context->GetPen()->SetWidth(1); // a rectangle around the point with the selected color - glBegin(GL_LINE_LOOP); + float* rectPts = new float[8]; tmp = pt2d - horz; - glVertex2dv(&tmp[0]); + rectPts[0] = tmp[0]; + rectPts[1] = tmp[1]; tmp = pt2d + vert; - glVertex2dv(&tmp[0]); + rectPts[2] = tmp[0]; + rectPts[3] = tmp[1]; tmp = pt2d + horz; - glVertex2dv(&tmp[0]); + rectPts[4] = tmp[0]; + rectPts[5] = tmp[1]; tmp = pt2d - vert; - glVertex2dv(&tmp[0]); - glEnd(); - glLineWidth(1); + rectPts[6] = tmp[0]; + rectPts[7] = tmp[1]; + this->m_Context->DrawPolygon(rectPts,4); // the actual point in the specified color to see the usual color of the point - glColor3f( + this->m_Context->GetPen()->SetColorF( colorprop->GetColor().GetRed(), colorprop->GetColor().GetGreen(), colorprop->GetColor().GetBlue()); - glPointSize(1); - glBegin(GL_POINTS); - tmp = pt2d; - glVertex2dv(&tmp[0]); - glEnd(); + this->m_Context->DrawPoint(pt2d[0], pt2d[1]); } } if (showPoints) { float pointsize = 3; Point2D tmp; Vector2D horz, vert; horz[1] = 0; vert[0] = 0; horz[0] = pointsize; vert[1] = pointsize; - glColor3f(0.0, 0.0, 0.0); - glLineWidth(1); + this->m_Context->GetPen()->SetColorF(0.0, 0.0, 0.0); + this->m_Context->GetPen()->SetWidth(1); // a rectangle around the point with the selected color - glBegin(GL_LINE_LOOP); + float* rectPts = new float[8]; tmp = pt2d - horz; - glVertex2dv(&tmp[0]); + rectPts[0] = tmp[0]; + rectPts[1] = tmp[1]; tmp = pt2d + vert; - glVertex2dv(&tmp[0]); + rectPts[2] = tmp[0]; + rectPts[3] = tmp[1]; tmp = pt2d + horz; - glVertex2dv(&tmp[0]); + rectPts[4] = tmp[0]; + rectPts[5] = tmp[1]; tmp = pt2d - vert; - glVertex2dv(&tmp[0]); - glEnd(); - glLineWidth(1); + rectPts[6] = tmp[0]; + rectPts[7] = tmp[1]; + this->m_Context->DrawPolygon(rectPts, 4); // the actual point in the specified color to see the usual color of the point - glColor3f(colorprop->GetColor().GetRed(), colorprop->GetColor().GetGreen(), colorprop->GetColor().GetBlue()); - glPointSize(1); - glBegin(GL_POINTS); - tmp = pt2d; - glVertex2dv(&tmp[0]); - glEnd(); + this->m_Context->GetPen()->SetColorF( + colorprop->GetColor().GetRed(), colorprop->GetColor().GetGreen(), colorprop->GetColor().GetBlue()); + this->m_Context->DrawPoint(pt2d[0], pt2d[1]); } if (showPointsNumbers) { std::string l; std::stringstream ss; ss << index; l.append(ss.str()); float rgb[3]; rgb[0] = 0.0; rgb[1] = 0.0; rgb[2] = 0.0; WriteTextWithAnnotation(m_PointNumbersAnnotation, l.c_str(), rgb, pt2d, renderer); } if (showControlPointsNumbers && (*pointsIt)->IsControlPoint) { std::string l; std::stringstream ss; ss << index; l.append(ss.str()); float rgb[3]; rgb[0] = 1.0; rgb[1] = 1.0; rgb[2] = 0.0; WriteTextWithAnnotation(m_ControlPointNumbersAnnotation, l.c_str(), rgb, pt2d, renderer); } index++; } pointsIt++; } // end while iterate over controlpoints // close contour if necessary if (renderingContour->IsClosed(timestep) && drawit && showSegments) { lastPt2d = pt2d; point = renderingContour->GetVertexAt(0, timestep)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp, p); renderer->WorldToDisplay(p, pt2d); - glLineWidth(lineWidth); - glBegin(GL_LINES); - glVertex2f(lastPt2d[0], lastPt2d[1]); - glVertex2f(pt2d[0], pt2d[1]); - glEnd(); - glLineWidth(1); + this->m_Context->GetPen()->SetWidth(lineWidth); + this->m_Context->DrawLine(lastPt2d[0], lastPt2d[1], pt2d[0], pt2d[1]); + this->m_Context->GetPen()->SetWidth(1); } // draw selected vertex if exists if (renderingContour->GetSelectedVertex()) { // transform selected vertex point = renderingContour->GetSelectedVertex()->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp, p); renderer->WorldToDisplay(p, pt2d); ScalarType scalardiff = fabs(renderer->GetCurrentWorldPlaneGeometry()->SignedDistance(p)); //---------------------------------- // draw point if close to plane if (scalardiff < maxDiff) { float pointsize = 5; Point2D tmp; - glColor3f(0.0, 1.0, 0.0); - glLineWidth(1); + + this->m_Context->GetPen()->SetColorF(0.0, 1.0, 0.0); + this->m_Context->GetPen()->SetWidth(1); + // a rectangle around the point with the selected color + float* rectPts = new float[8]; // a diamond around the point - glBegin(GL_LINE_LOOP); // begin from upper left corner and paint clockwise - tmp[0] = pt2d[0] - pointsize; - tmp[1] = pt2d[1] + pointsize; - glVertex2dv(&tmp[0]); - tmp[0] = pt2d[0] + pointsize; - tmp[1] = pt2d[1] + pointsize; - glVertex2dv(&tmp[0]); - tmp[0] = pt2d[0] + pointsize; - tmp[1] = pt2d[1] - pointsize; - glVertex2dv(&tmp[0]); - tmp[0] = pt2d[0] - pointsize; - tmp[1] = pt2d[1] - pointsize; - glVertex2dv(&tmp[0]); - glEnd(); + rectPts[0] = pt2d[0] - pointsize; + rectPts[1] = pt2d[1] + pointsize; + rectPts[2] = pt2d[0] + pointsize; + rectPts[3] = pt2d[1] + pointsize; + rectPts[4] = pt2d[0] + pointsize; + rectPts[5] = pt2d[1] - pointsize; + rectPts[6] = pt2d[0] - pointsize; + rectPts[7] = pt2d[1] - pointsize; + this->m_Context->DrawPolygon(rectPts, 4); } //------------------------------------ } } + this->m_Context->GetDevice()->End(); } void mitk::ContourModelGLMapper2DBase::WriteTextWithAnnotation(TextAnnotationPointerType textAnnotation, const char *text, float rgb[3], Point2D /*pt2d*/, mitk::BaseRenderer * /*renderer*/) { textAnnotation->SetText(text); textAnnotation->SetColor(rgb); textAnnotation->SetOpacity(1); textAnnotation->SetFontSize(16); textAnnotation->SetBoolProperty("drawShadow", false); textAnnotation->SetVisibility(true); } diff --git a/Modules/ContourModel/Rendering/mitkContourModelGLMapper2DBase.h b/Modules/ContourModel/Rendering/mitkContourModelGLMapper2DBase.h index 05688ae45b..221b86075b 100644 --- a/Modules/ContourModel/Rendering/mitkContourModelGLMapper2DBase.h +++ b/Modules/ContourModel/Rendering/mitkContourModelGLMapper2DBase.h @@ -1,64 +1,76 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITK_ContourModelGLMapper2DBase_H_ #define MITK_ContourModelGLMapper2DBase_H_ #include "mitkCommon.h" -#include "mitkGLMapper.h" +#include "mitkMapper.h" #include "mitkTextAnnotation2D.h" #include +#include "vtkNew.h" + +class vtkContext2D; +class vtkPen; namespace mitk { class BaseRenderer; class ContourModel; /** * @brief Base class for OpenGL based 2D mappers. * Provides functionality to draw a contour. * * @ingroup MitkContourModelModule */ - class MITKCONTOURMODEL_EXPORT ContourModelGLMapper2DBase : public GLMapper + class MITKCONTOURMODEL_EXPORT ContourModelGLMapper2DBase : public Mapper { public: - mitkClassMacro(ContourModelGLMapper2DBase, GLMapper); + mitkClassMacro(ContourModelGLMapper2DBase, Mapper); + + void ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor * actor = nullptr) override; protected: typedef TextAnnotation2D::Pointer TextAnnotationPointerType; ContourModelGLMapper2DBase(); virtual ~ContourModelGLMapper2DBase(); void DrawContour(mitk::ContourModel *contour, mitk::BaseRenderer *renderer); void WriteTextWithAnnotation( TextAnnotationPointerType textAnnotation, const char *text, float rgb[3], Point2D pt2d, mitk::BaseRenderer *); virtual void InternalDrawContour(mitk::ContourModel *renderingContour, mitk::BaseRenderer *renderer); + void Initialize(mitk::BaseRenderer *renderer); + TextAnnotationPointerType m_PointNumbersAnnotation; TextAnnotationPointerType m_ControlPointNumbersAnnotation; typedef std::vector RendererListType; RendererListType m_RendererList; + + bool m_Initialized; + + vtkNew m_Context; }; } // namespace mitk #endif diff --git a/Modules/ContourModel/Rendering/mitkContourModelSetGLMapper2D.cpp b/Modules/ContourModel/Rendering/mitkContourModelSetGLMapper2D.cpp index 5abc14afeb..b51290694e 100644 --- a/Modules/ContourModel/Rendering/mitkContourModelSetGLMapper2D.cpp +++ b/Modules/ContourModel/Rendering/mitkContourModelSetGLMapper2D.cpp @@ -1,396 +1,396 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourModelSetGLMapper2D.h" #include "mitkColorProperty.h" #include "mitkContourModelSet.h" #include "mitkPlaneGeometry.h" #include "mitkProperties.h" #include #include "mitkGL.h" mitk::ContourModelSetGLMapper2D::ContourModelSetGLMapper2D() { } mitk::ContourModelSetGLMapper2D::~ContourModelSetGLMapper2D() { } -void mitk::ContourModelSetGLMapper2D::Paint(mitk::BaseRenderer *renderer) +void mitk::ContourModelSetGLMapper2D::MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType /*type*/) { BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer); mitk::DataNode::Pointer dataNode = this->GetDataNode(); bool visible = true; dataNode->GetVisibility(visible, nullptr); if (!visible) return; mitk::ContourModelSet::Pointer input = this->GetInput(); auto centerOfViewPointZ = renderer->GetCurrentWorldPlaneGeometry()->GetCenter()[2]; mitk::ContourModelSet::ContourModelSetIterator it = input->Begin(); mitk::ContourModelSet::ContourModelSetIterator end = input->End(); while (it != end) { //we have the assumption that each contour model vertex has the same z coordinate auto currentZValue = (*it)->GetVertexAt(0)->Coordinates[2]; double acceptedDeviationInMM = 5.0; //only draw contour if it is visible if (currentZValue - acceptedDeviationInMM < centerOfViewPointZ && currentZValue + acceptedDeviationInMM > centerOfViewPointZ){ this->DrawContour(it->GetPointer(), renderer); } ++it; } if (input->GetSize() < 1) return; ls->UpdateGenerateDataTime(); } mitk::ContourModelSet *mitk::ContourModelSetGLMapper2D::GetInput(void) { return const_cast(static_cast(GetDataNode()->GetData())); } void mitk::ContourModelSetGLMapper2D::InternalDrawContour(mitk::ContourModel *renderingContour, mitk::BaseRenderer *renderer) { if (!renderingContour) return; mitk::DataNode::Pointer dataNode = this->GetDataNode(); renderingContour->UpdateOutputInformation(); unsigned int timestep = renderer->GetTimeStep(); if (!renderingContour->IsEmptyTimeStep(timestep)) { // apply color and opacity read from the PropertyList ApplyColorAndOpacityProperties(renderer); mitk::ColorProperty::Pointer colorprop = dynamic_cast(dataNode->GetProperty("contour.color", renderer)); float opacity = 0.5; dataNode->GetFloatProperty("opacity", opacity, renderer); if (colorprop) { // set the color of the contour double red = colorprop->GetColor().GetRed(); double green = colorprop->GetColor().GetGreen(); double blue = colorprop->GetColor().GetBlue(); glColor4f(red, green, blue, opacity); } mitk::ColorProperty::Pointer selectedcolor = dynamic_cast(dataNode->GetProperty("contour.points.color", renderer)); if (!selectedcolor) { selectedcolor = mitk::ColorProperty::New(1.0, 0.0, 0.1); } vtkLinearTransform *transform = dataNode->GetVtkTransform(); // ContourModel::OutputType point; mitk::Point3D point; mitk::Point3D p; float vtkp[3]; float lineWidth = 3.0; bool drawit = false; bool isHovering = false; dataNode->GetBoolProperty("contour.hovering", isHovering); if (isHovering) dataNode->GetFloatProperty("contour.hovering.width", lineWidth); else dataNode->GetFloatProperty("contour.width", lineWidth); bool showSegments = false; dataNode->GetBoolProperty("contour.segments.show", showSegments); bool showControlPoints = false; dataNode->GetBoolProperty("contour.controlpoints.show", showControlPoints); bool showPoints = false; dataNode->GetBoolProperty("contour.points.show", showPoints); bool showPointsNumbers = false; dataNode->GetBoolProperty("contour.points.text", showPointsNumbers); bool showControlPointsNumbers = false; dataNode->GetBoolProperty("contour.controlpoints.text", showControlPointsNumbers); bool projectmode = false; dataNode->GetVisibility(projectmode, renderer, "contour.project-onto-plane"); mitk::ContourModel::VertexIterator pointsIt = renderingContour->IteratorBegin(timestep); Point2D pt2d; // projected_p in display coordinates Point2D lastPt2d; int index = 0; mitk::ScalarType maxDiff = 0.25; while (pointsIt != renderingContour->IteratorEnd(timestep)) { lastPt2d = pt2d; point = (*pointsIt)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp, p); renderer->WorldToDisplay(p, pt2d); ScalarType scalardiff = fabs(renderer->GetCurrentWorldPlaneGeometry()->SignedDistance(p)); // project to plane if (projectmode) { drawit = true; } else if (scalardiff < maxDiff) // point is close enough to be drawn { drawit = true; } else { drawit = false; } // draw line if (drawit) { if (showSegments) { // lastPt2d is not valid in first step if (!(pointsIt == renderingContour->IteratorBegin(timestep))) { glLineWidth(lineWidth); glBegin(GL_LINES); glVertex2f(pt2d[0], pt2d[1]); glVertex2f(lastPt2d[0], lastPt2d[1]); glEnd(); glLineWidth(1); } } if (showControlPoints) { // draw control points if ((*pointsIt)->IsControlPoint) { float pointsize = 4; Point2D tmp; Vector2D horz, vert; horz[1] = 0; vert[0] = 0; horz[0] = pointsize; vert[1] = pointsize; glColor3f(selectedcolor->GetColor().GetRed(), selectedcolor->GetColor().GetBlue(), selectedcolor->GetColor().GetGreen()); glLineWidth(1); // a rectangle around the point with the selected color glBegin(GL_LINE_LOOP); tmp = pt2d - horz; glVertex2dv(&tmp[0]); tmp = pt2d + vert; glVertex2dv(&tmp[0]); tmp = pt2d + horz; glVertex2dv(&tmp[0]); tmp = pt2d - vert; glVertex2dv(&tmp[0]); glEnd(); glLineWidth(1); // the actual point in the specified color to see the usual color of the point glColor3f( colorprop->GetColor().GetRed(), colorprop->GetColor().GetGreen(), colorprop->GetColor().GetBlue()); glPointSize(1); glBegin(GL_POINTS); tmp = pt2d; glVertex2dv(&tmp[0]); glEnd(); } } if (showPoints) { float pointsize = 3; Point2D tmp; Vector2D horz, vert; horz[1] = 0; vert[0] = 0; horz[0] = pointsize; vert[1] = pointsize; glColor3f(0.0, 0.0, 0.0); glLineWidth(1); // a rectangle around the point with the selected color glBegin(GL_LINE_LOOP); tmp = pt2d - horz; glVertex2dv(&tmp[0]); tmp = pt2d + vert; glVertex2dv(&tmp[0]); tmp = pt2d + horz; glVertex2dv(&tmp[0]); tmp = pt2d - vert; glVertex2dv(&tmp[0]); glEnd(); glLineWidth(1); // the actual point in the specified color to see the usual color of the point glColor3f(colorprop->GetColor().GetRed(), colorprop->GetColor().GetGreen(), colorprop->GetColor().GetBlue()); glPointSize(1); glBegin(GL_POINTS); tmp = pt2d; glVertex2dv(&tmp[0]); glEnd(); } if (showPointsNumbers) { std::string l; std::stringstream ss; ss << index; l.append(ss.str()); float rgb[3]; rgb[0] = 0.0; rgb[1] = 0.0; rgb[2] = 0.0; WriteTextWithAnnotation(m_PointNumbersAnnotation, l.c_str(), rgb, pt2d, renderer); } if (showControlPointsNumbers && (*pointsIt)->IsControlPoint) { std::string l; std::stringstream ss; ss << index; l.append(ss.str()); float rgb[3]; rgb[0] = 1.0; rgb[1] = 1.0; rgb[2] = 0.0; WriteTextWithAnnotation(m_ControlPointNumbersAnnotation, l.c_str(), rgb, pt2d, renderer); } index++; } pointsIt++; } // end while iterate over controlpoints // close contour if necessary if (renderingContour->IsClosed(timestep) && drawit && showSegments) { lastPt2d = pt2d; point = renderingContour->GetVertexAt(0, timestep)->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp, p); renderer->WorldToDisplay(p, pt2d); glLineWidth(lineWidth); glBegin(GL_LINES); glVertex2f(lastPt2d[0], lastPt2d[1]); glVertex2f(pt2d[0], pt2d[1]); glEnd(); glLineWidth(1); } // draw selected vertex if exists if (renderingContour->GetSelectedVertex()) { // transform selected vertex point = renderingContour->GetSelectedVertex()->Coordinates; itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp, p); renderer->WorldToDisplay(p, pt2d); ScalarType scalardiff = fabs(renderer->GetCurrentWorldPlaneGeometry()->SignedDistance(p)); //---------------------------------- // draw point if close to plane if (scalardiff < maxDiff) { float pointsize = 5; Point2D tmp; glColor3f(0.0, 1.0, 0.0); glLineWidth(1); // a diamond around the point glBegin(GL_LINE_LOOP); // begin from upper left corner and paint clockwise tmp[0] = pt2d[0] - pointsize; tmp[1] = pt2d[1] + pointsize; glVertex2dv(&tmp[0]); tmp[0] = pt2d[0] + pointsize; tmp[1] = pt2d[1] + pointsize; glVertex2dv(&tmp[0]); tmp[0] = pt2d[0] + pointsize; tmp[1] = pt2d[1] - pointsize; glVertex2dv(&tmp[0]); tmp[0] = pt2d[0] - pointsize; tmp[1] = pt2d[1] - pointsize; glVertex2dv(&tmp[0]); glEnd(); } //------------------------------------ } } } void mitk::ContourModelSetGLMapper2D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { node->AddProperty("contour.color", ColorProperty::New(0.9, 1.0, 0.1), renderer, overwrite); node->AddProperty("contour.points.color", ColorProperty::New(1.0, 0.0, 0.1), renderer, overwrite); node->AddProperty("contour.points.show", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contour.segments.show", mitk::BoolProperty::New(true), renderer, overwrite); node->AddProperty("contour.controlpoints.show", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contour.width", mitk::FloatProperty::New(1.0), renderer, overwrite); node->AddProperty("contour.hovering.width", mitk::FloatProperty::New(3.0), renderer, overwrite); node->AddProperty("contour.hovering", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contour.points.text", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contour.controlpoints.text", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contour.project-onto-plane", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("opacity", mitk::FloatProperty::New(1.0f), renderer, overwrite); Superclass::SetDefaultProperties(node, renderer, overwrite); } diff --git a/Modules/ContourModel/Rendering/mitkContourModelSetGLMapper2D.h b/Modules/ContourModel/Rendering/mitkContourModelSetGLMapper2D.h index 88bc79aa98..8de9f373d0 100644 --- a/Modules/ContourModel/Rendering/mitkContourModelSetGLMapper2D.h +++ b/Modules/ContourModel/Rendering/mitkContourModelSetGLMapper2D.h @@ -1,70 +1,70 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITK_ContourModelSetGLMapper2D_H_ #define MITK_ContourModelSetGLMapper2D_H_ #include "mitkBaseRenderer.h" #include "mitkCommon.h" #include "mitkContourModelGLMapper2DBase.h" #include "mitkContourModelSet.h" #include namespace mitk { class BaseRenderer; class ContourModel; /** * @brief OpenGL-based mapper to display a mitk::ContourModelSet object containing several contours in a 2D render * window * * * @ingroup MitkContourModelModule */ class MITKCONTOURMODEL_EXPORT ContourModelSetGLMapper2D : public ContourModelGLMapper2DBase { public: mitkClassMacro(ContourModelSetGLMapper2D, ContourModelGLMapper2DBase); itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** * reimplemented from Baseclass */ - virtual void Paint(BaseRenderer *renderer) override; + virtual void MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type) override; static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); LocalStorageHandler m_LSH; protected: ContourModelSetGLMapper2D(); virtual ~ContourModelSetGLMapper2D(); void InternalDrawContour(mitk::ContourModel *contour, mitk::BaseRenderer *renderer) override; private: /** * return a reference of the rendered data object */ ContourModelSet *GetInput(void); }; } // namespace mitk #endif diff --git a/Modules/Core/CMakeLists.txt b/Modules/Core/CMakeLists.txt index a20d8efb33..cf7b771577 100644 --- a/Modules/Core/CMakeLists.txt +++ b/Modules/Core/CMakeLists.txt @@ -1,77 +1,77 @@ set(TOOL_CPPS "") # temporary suppress warnings in the following files until image accessors are fully integrated. set_source_files_properties( src/DataManagement/mitkImage.cpp COMPILE_FLAGS -DMITK_NO_DEPRECATED_WARNINGS ) set_source_files_properties( src/Controllers/mitkSliceNavigationController.cpp COMPILE_FLAGS -DMITK_NO_DEPRECATED_WARNINGS ) MITK_CREATE_MODULE( INCLUDE_DIRS PUBLIC ${MITK_BINARY_DIR} PRIVATE src/Algorithms src/Controllers src/DataManagement src/Interactions src/IO src/Rendering ${OPENGL_INCLUDE_DIR} DEPENDS PUBLIC mbilog CppMicroServices PACKAGE_DEPENDS PRIVATE tinyxml OpenGL # Remove public GDCM and ITKIOGDCM+... dependencies after mitkDicomSeriesReader was removed PUBLIC GDCM PUBLIC ITK|ITKTransform+ITKImageGrid+ITKImageFeature+ITKIOImageBase+ITKIOGDCM+ITKIOHDF5+ITKIOLSM+ITKIOMRC+ITKIOBioRad+ITKIOGE+ITKIOStimulate # We privately use/link all ITK modules in order to support all IO, Transform, etc. # factories from ITK which are registered "automatically" via a factory manager. PRIVATE ITK - PUBLIC VTK|vtkFiltersTexture+vtkFiltersParallel+vtkImagingStencil+vtkImagingMath+vtkInteractionStyle+vtkRenderingOpenGL+vtkRenderingVolumeOpenGL+vtkRenderingFreeType+vtkRenderingLabel+vtkInteractionWidgets+vtkIOGeometry+vtkIOXML + PUBLIC VTK|vtkFiltersTexture+vtkFiltersParallel+vtkImagingStencil+vtkImagingMath+vtkInteractionStyle+vtkRenderingOpenGL2+vtkRenderingContextOpenGL2+vtkRenderingVolumeOpenGL2+vtkRenderingFreeType+vtkRenderingLabel+vtkInteractionWidgets+vtkIOGeometry+vtkIOXML PUBLIC Boost SUBPROJECTS MITK-Core # Do not automatically create CppMicroServices initialization code. # Because the VTK 6 "auto-init" functionality injects file-local static # initialization code in every cpp file which includes a VTK header, # static initialization order becomes an issue again. For the Mitk # core library, we need to ensure that the VTK static initialization stuff # happens before the CppMicroServices initialization, since the latter # might already use VTK code which needs to access VTK object factories. # Hence, CppMicroServices initialization code is placed manually within # the mitkCoreActivator.cpp file. NO_INIT ) if(NOT TARGET ${MODULE_TARGET}) message(SEND_ERROR "Core target ${MODULE_TARGET} does not exist") endif() function(_itk_create_factory_register_manager) # In MITK_ITK_Config.cmake, we do *not* include ITK_USE_FILE, which # prevents multiple registrations/unregistrations of ITK IO factories # during library loading/unloading (of MITK libraries). However, we need # "one" place where the IO factories are registered at # least once. This could be the application executable, but every executable would # need to take care of that itself. Instead, we allow the auto registration in the # Mitk Core library. set(NO_DIRECTORY_SCOPED_ITK_COMPILE_DEFINITION 1) find_package(ITK) include(${ITK_USE_FILE}) if(NOT ITK_NO_IO_FACTORY_REGISTER_MANAGER) # We manually add the define which will be of target scope. MITK # patches ITK_USE_FILE to remove the directory scoped compile # definition since it would be propagated to other targets in the # same directory scope but these targets might want to *not* # use the ITK factory manager stuff. target_compile_definitions(${MODULE_TARGET} PRIVATE ITK_IO_FACTORY_REGISTER_MANAGER) endif() endfunction() _itk_create_factory_register_manager() # this is needed for libraries which link to Mitk and need # symbols from explicitly instantiated templates if(MINGW) get_target_property(_mitkCore_MINGW_linkflags ${MODULE_TARGET} LINK_FLAGS) if(NOT _mitkCore_MINGW_linkflags) set(_mitkCore_MINGW_linkflags "") endif(NOT _mitkCore_MINGW_linkflags) set_target_properties(${MODULE_TARGET} PROPERTIES LINK_FLAGS "${_mitkCore_MINGW_linkflags} -Wl,--export-all-symbols") endif(MINGW) if(MSVC_IDE OR MSVC_VERSION OR MINGW) target_link_libraries(${MODULE_TARGET} PRIVATE psapi.lib) endif(MSVC_IDE OR MSVC_VERSION OR MINGW) add_subdirectory(TestingHelper) add_subdirectory(test) diff --git a/Modules/Core/TestingHelper/src/mitkRenderingTestHelper.cpp b/Modules/Core/TestingHelper/src/mitkRenderingTestHelper.cpp index d0a917b508..7aa8f971a1 100644 --- a/Modules/Core/TestingHelper/src/mitkRenderingTestHelper.cpp +++ b/Modules/Core/TestingHelper/src/mitkRenderingTestHelper.cpp @@ -1,308 +1,307 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // VTK #include #include #include #include #include // MITK #include #include #include #include #include // include gl to read out properties #include -#include #include #if defined _MSC_VER #if _MSC_VER >= 1700 #define RESIZE_WORKAROUND #endif #endif #ifdef RESIZE_WORKAROUND #include "vtkWin32OpenGLRenderWindow.h" #endif // VTK Testing to compare the rendered image pixel-wise against a reference screen shot #include "vtkTesting.h" mitk::RenderingTestHelper::RenderingTestHelper(int width, int height, mitk::BaseRenderer::RenderingMode::Type renderingMode) : m_AutomaticallyCloseRenderWindow(true) { this->Initialize(width, height, renderingMode); } mitk::RenderingTestHelper::RenderingTestHelper( int width, int height, int argc, char *argv[], mitk::BaseRenderer::RenderingMode::Type renderingMode) : m_AutomaticallyCloseRenderWindow(true) { this->Initialize(width, height, renderingMode); this->SetInputFileNames(argc, argv); } void mitk::RenderingTestHelper::Initialize(int width, int height, mitk::BaseRenderer::RenderingMode::Type renderingMode) { mitk::UIDGenerator uidGen = mitk::UIDGenerator("UnnamedRenderer_", 8); m_RenderWindow = mitk::RenderWindow::New(nullptr, uidGen.GetUID().c_str(), nullptr, renderingMode); m_DataStorage = mitk::StandaloneDataStorage::New(); m_RenderWindow->GetRenderer()->SetDataStorage(m_DataStorage); this->SetMapperIDToRender2D(); this->GetVtkRenderWindow()->SetSize(width, height); #ifdef RESIZE_WORKAROUND HWND hWnd = static_cast(this->GetVtkRenderWindow())->GetWindowId(); RECT r; r.left = 10; r.top = 10; r.right = r.left + width; r.bottom = r.top + height; LONG style = GetWindowLong(hWnd, GWL_STYLE); AdjustWindowRect(&r, style, FALSE); MITK_INFO << "WANTED:"; MITK_INFO << r.right - r.left; MITK_INFO << r.bottom - r.top; RECT rect; if (GetWindowRect(hWnd, &rect)) { int width = rect.right - rect.left; int height = rect.bottom - rect.top; MITK_INFO << "ACTUAL:"; MITK_INFO << width; MITK_INFO << height; } SetWindowPos(hWnd, HWND_TOP, 0, 0, r.right - r.left, r.bottom - r.top, SWP_NOZORDER); GetWindowRect(hWnd, &rect); int width2 = rect.right - rect.left; int height2 = rect.bottom - rect.top; MITK_INFO << "ACTUAL2:"; MITK_INFO << width2; MITK_INFO << height2; SetWindowPos(hWnd, HWND_TOP, 0, 0, 2 * (r.right - r.left) - width2, 2 * (r.bottom - r.top) - height2, SWP_NOZORDER); #endif m_RenderWindow->GetRenderer()->Resize(width, height); // Prints the glinfo after creation of the vtkrenderwindow, we always want to do this for debugging. this->PrintGLInfo(); } mitk::RenderingTestHelper::~RenderingTestHelper() { } bool mitk::RenderingTestHelper::IsAdvancedOpenGL() { const GLubyte *version = glGetString(GL_VERSION); if (!version) return false; return *version >= '2'; } void mitk::RenderingTestHelper::PrintGLInfo() { GLint maxTextureSize; glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize); ; - MITK_INFO << "OpenGL Render Context Information: \n" - << "- GL_VENDOR: " << glGetString(GL_VENDOR) << "\n" - << "- GL_RENDERER: " << glGetString(GL_RENDERER) << "\n" - << "- GL_VERSION: " << glGetString(GL_VERSION) << "\n" - << "- GL_MAX_TEXTURE_SIZE: " << maxTextureSize << "\n" - << "- GL_EXTENSIONS: " << glGetString(GL_EXTENSIONS); + //MITK_INFO << "OpenGL Render Context Information: \n" + // << "- GL_VENDOR: " << glGetString(GL_VENDOR) << "\n" + // << "- GL_RENDERER: " << glGetString(GL_RENDERER) << "\n" + // << "- GL_VERSION: " << glGetString(GL_VERSION) << "\n" + // << "- GL_MAX_TEXTURE_SIZE: " << maxTextureSize << "\n" + // << "- GL_EXTENSIONS: " << glGetString(GL_EXTENSIONS); } void mitk::RenderingTestHelper::SetMapperID(mitk::BaseRenderer::StandardMapperSlot id) { m_RenderWindow->GetRenderer()->SetMapperID(id); } void mitk::RenderingTestHelper::SetMapperIDToRender3D() { this->SetMapperID(mitk::BaseRenderer::Standard3D); mitk::RenderingManager::GetInstance()->InitializeViews( this->GetDataStorage()->ComputeBoundingGeometry3D(this->GetDataStorage()->GetAll())); } void mitk::RenderingTestHelper::SetMapperIDToRender2D() { this->SetMapperID(mitk::BaseRenderer::Standard2D); } void mitk::RenderingTestHelper::Render() { // if the datastorage is initialized and at least 1 image is loaded render it if (m_DataStorage.IsNotNull() || m_DataStorage->GetAll()->Size() >= 1) { // Prepare the VTK camera before rendering. m_RenderWindow->GetRenderer()->PrepareRender(); this->GetVtkRenderWindow()->Render(); this->GetVtkRenderWindow()->WaitForCompletion(); if (m_AutomaticallyCloseRenderWindow == false) { // Use interaction to stop the test this->GetVtkRenderWindow()->GetInteractor()->Start(); } } else { MITK_ERROR << "No images loaded in data storage!"; } } mitk::DataStorage::Pointer mitk::RenderingTestHelper::GetDataStorage() { return m_DataStorage; } void mitk::RenderingTestHelper::SetInputFileNames(int argc, char *argv[]) { // i is set 1, because 0 is the testname as string // parse parameters for (int i = 1; i < argc; ++i) { // add everything to a list but -T and -V std::string tmp = argv[i]; if ((tmp.compare("-T")) && (tmp.compare("-V"))) { this->AddToStorage(tmp); } else { break; } } } void mitk::RenderingTestHelper::SetViewDirection(mitk::SliceNavigationController::ViewDirection viewDirection) { mitk::BaseRenderer::GetInstance(m_RenderWindow->GetVtkRenderWindow()) ->GetSliceNavigationController() ->SetDefaultViewDirection(viewDirection); mitk::RenderingManager::GetInstance()->InitializeViews( m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll())); } void mitk::RenderingTestHelper::ReorientSlices(mitk::Point3D origin, mitk::Vector3D rotation) { mitk::SliceNavigationController::Pointer sliceNavigationController = mitk::BaseRenderer::GetInstance(m_RenderWindow->GetVtkRenderWindow())->GetSliceNavigationController(); sliceNavigationController->ReorientSlices(origin, rotation); } vtkRenderer *mitk::RenderingTestHelper::GetVtkRenderer() { return m_RenderWindow->GetRenderer()->GetVtkRenderer(); } void mitk::RenderingTestHelper::SetImageProperty(const char *propertyKey, mitk::BaseProperty *property) { this->m_DataStorage->GetNode(mitk::NodePredicateDataType::New("Image"))->SetProperty(propertyKey, property); } vtkRenderWindow *mitk::RenderingTestHelper::GetVtkRenderWindow() { return m_RenderWindow->GetVtkRenderWindow(); } bool mitk::RenderingTestHelper::CompareRenderWindowAgainstReference(int argc, char *argv[], double threshold) { this->Render(); // retVal meanings: (see VTK/Rendering/vtkTesting.h) // 0 = test failed // 1 = test passed // 2 = test not run // 3 = something with vtkInteraction if (vtkTesting::Test(argc, argv, this->GetVtkRenderWindow(), threshold) == 1) return true; else return false; } // method to save a screenshot of the renderwindow (e.g. create a reference screenshot) void mitk::RenderingTestHelper::SaveAsPNG(std::string fileName) { vtkSmartPointer renderer = this->GetVtkRenderer(); bool doubleBuffering(renderer->GetRenderWindow()->GetDoubleBuffer()); renderer->GetRenderWindow()->DoubleBufferOff(); vtkSmartPointer magnifier = vtkSmartPointer::New(); magnifier->SetInput(renderer); magnifier->SetMagnification(1); vtkSmartPointer fileWriter = vtkSmartPointer::New(); fileWriter->SetInputConnection(magnifier->GetOutputPort()); fileWriter->SetFileName(fileName.c_str()); fileWriter->Write(); renderer->GetRenderWindow()->SetDoubleBuffer(doubleBuffering); } void mitk::RenderingTestHelper::SetAutomaticallyCloseRenderWindow(bool automaticallyCloseRenderWindow) { m_AutomaticallyCloseRenderWindow = automaticallyCloseRenderWindow; } void mitk::RenderingTestHelper::SaveReferenceScreenShot(std::string fileName) { this->SaveAsPNG(fileName); } void mitk::RenderingTestHelper::AddToStorage(const std::string &filename) { try { mitk::IOUtil::Load(filename, *m_DataStorage.GetPointer()); mitk::RenderingManager::GetInstance()->InitializeViews( m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll())); } catch (itk::ExceptionObject &e) { MITK_ERROR << "Failed loading test data '" << filename << "': " << e.what(); } } void mitk::RenderingTestHelper::AddNodeToStorage(mitk::DataNode::Pointer node) { this->m_DataStorage->Add(node); mitk::RenderingManager::GetInstance()->InitializeViews( m_DataStorage->ComputeBoundingGeometry3D(m_DataStorage->GetAll())); } diff --git a/Modules/Core/files.cmake b/Modules/Core/files.cmake index 402ddc6d26..6ff5c66759 100644 --- a/Modules/Core/files.cmake +++ b/Modules/Core/files.cmake @@ -1,314 +1,312 @@ file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*") set(CPP_FILES mitkCoreActivator.cpp mitkCoreObjectFactoryBase.cpp mitkCoreObjectFactory.cpp mitkCoreServices.cpp mitkException.cpp Algorithms/mitkBaseDataSource.cpp Algorithms/mitkClippedSurfaceBoundsCalculator.cpp Algorithms/mitkCompareImageDataFilter.cpp Algorithms/mitkCompositePixelValueToString.cpp Algorithms/mitkConvert2Dto3DImageFilter.cpp Algorithms/mitkDataNodeSource.cpp Algorithms/mitkExtractSliceFilter.cpp Algorithms/mitkHistogramGenerator.cpp Algorithms/mitkImageChannelSelector.cpp Algorithms/mitkImageSliceSelector.cpp Algorithms/mitkImageSource.cpp Algorithms/mitkImageTimeSelector.cpp Algorithms/mitkImageToImageFilter.cpp Algorithms/mitkImageToSurfaceFilter.cpp Algorithms/mitkMultiComponentImageDataComparisonFilter.cpp Algorithms/mitkPlaneGeometryDataToSurfaceFilter.cpp Algorithms/mitkPointSetSource.cpp Algorithms/mitkPointSetToPointSetFilter.cpp Algorithms/mitkRGBToRGBACastImageFilter.cpp Algorithms/mitkSubImageSelector.cpp Algorithms/mitkSurfaceSource.cpp Algorithms/mitkSurfaceToImageFilter.cpp Algorithms/mitkSurfaceToSurfaceFilter.cpp Algorithms/mitkUIDGenerator.cpp Algorithms/mitkVolumeCalculator.cpp Controllers/mitkBaseController.cpp Controllers/mitkCallbackFromGUIThread.cpp Controllers/mitkCameraController.cpp Controllers/mitkCameraRotationController.cpp Controllers/mitkLimitedLinearUndo.cpp Controllers/mitkOperationEvent.cpp Controllers/mitkPlanePositionManager.cpp Controllers/mitkProgressBar.cpp Controllers/mitkRenderingManager.cpp Controllers/mitkSliceNavigationController.cpp Controllers/mitkSlicesCoordinator.cpp Controllers/mitkStatusBar.cpp Controllers/mitkStepper.cpp Controllers/mitkTestManager.cpp Controllers/mitkUndoController.cpp Controllers/mitkVerboseLimitedLinearUndo.cpp Controllers/mitkVtkLayerController.cpp DataManagement/mitkAnatomicalStructureColorPresets.cpp DataManagement/mitkArbitraryTimeGeometry.cpp DataManagement/mitkAbstractTransformGeometry.cpp DataManagement/mitkAnnotationProperty.cpp DataManagement/mitkApplicationCursor.cpp DataManagement/mitkApplyTransformMatrixOperation.cpp DataManagement/mitkBaseData.cpp DataManagement/mitkBaseGeometry.cpp DataManagement/mitkBaseProperty.cpp DataManagement/mitkChannelDescriptor.cpp DataManagement/mitkClippingProperty.cpp DataManagement/mitkColorProperty.cpp DataManagement/mitkDataNode.cpp DataManagement/mitkDataStorage.cpp DataManagement/mitkEnumerationProperty.cpp DataManagement/mitkFloatPropertyExtension.cpp DataManagement/mitkGeometry3D.cpp DataManagement/mitkGeometryData.cpp DataManagement/mitkGeometryTransformHolder.cpp DataManagement/mitkGroupTagProperty.cpp DataManagement/mitkImageAccessorBase.cpp DataManagement/mitkImageCaster.cpp DataManagement/mitkImageCastPart1.cpp DataManagement/mitkImageCastPart2.cpp DataManagement/mitkImageCastPart3.cpp DataManagement/mitkImageCastPart4.cpp DataManagement/mitkImage.cpp DataManagement/mitkImageDataItem.cpp DataManagement/mitkImageDescriptor.cpp DataManagement/mitkImageReadAccessor.cpp DataManagement/mitkImageStatisticsHolder.cpp DataManagement/mitkImageVtkAccessor.cpp DataManagement/mitkImageVtkReadAccessor.cpp DataManagement/mitkImageVtkWriteAccessor.cpp DataManagement/mitkImageWriteAccessor.cpp DataManagement/mitkIntPropertyExtension.cpp DataManagement/mitkIPersistenceService.cpp DataManagement/mitkIPropertyAliases.cpp DataManagement/mitkIPropertyDescriptions.cpp DataManagement/mitkIPropertyExtensions.cpp DataManagement/mitkIPropertyFilters.cpp DataManagement/mitkIPropertyPersistence.cpp DataManagement/mitkLandmarkProjectorBasedCurvedGeometry.cpp DataManagement/mitkLandmarkProjector.cpp DataManagement/mitkLevelWindow.cpp DataManagement/mitkLevelWindowManager.cpp DataManagement/mitkLevelWindowPreset.cpp DataManagement/mitkLevelWindowProperty.cpp DataManagement/mitkLine.cpp DataManagement/mitkLookupTable.cpp DataManagement/mitkLookupTableProperty.cpp DataManagement/mitkLookupTables.cpp # specializations of GenericLookupTable DataManagement/mitkMaterial.cpp DataManagement/mitkMemoryUtilities.cpp DataManagement/mitkModalityProperty.cpp DataManagement/mitkModifiedLock.cpp DataManagement/mitkNodePredicateAnd.cpp DataManagement/mitkNodePredicateBase.cpp DataManagement/mitkNodePredicateCompositeBase.cpp DataManagement/mitkNodePredicateData.cpp DataManagement/mitkNodePredicateDataType.cpp DataManagement/mitkNodePredicateDimension.cpp DataManagement/mitkNodePredicateFirstLevel.cpp DataManagement/mitkNodePredicateGeometry.cpp DataManagement/mitkNodePredicateNot.cpp DataManagement/mitkNodePredicateOr.cpp DataManagement/mitkNodePredicateProperty.cpp DataManagement/mitkNodePredicateDataProperty.cpp DataManagement/mitkNodePredicateSource.cpp DataManagement/mitkNumericConstants.cpp DataManagement/mitkPlaneGeometry.cpp DataManagement/mitkPlaneGeometryData.cpp DataManagement/mitkPlaneOperation.cpp DataManagement/mitkPlaneOrientationProperty.cpp DataManagement/mitkPointOperation.cpp DataManagement/mitkPointSet.cpp DataManagement/mitkPointSetShapeProperty.cpp DataManagement/mitkProperties.cpp DataManagement/mitkPropertyAliases.cpp DataManagement/mitkPropertyDescriptions.cpp DataManagement/mitkPropertyExtension.cpp DataManagement/mitkPropertyExtensions.cpp DataManagement/mitkPropertyFilter.cpp DataManagement/mitkPropertyFilters.cpp DataManagement/mitkPropertyList.cpp DataManagement/mitkPropertyListReplacedObserver.cpp DataManagement/mitkPropertyNameHelper.cpp DataManagement/mitkPropertyObserver.cpp DataManagement/mitkPropertyPersistence.cpp DataManagement/mitkPropertyPersistenceInfo.cpp DataManagement/mitkProportionalTimeGeometry.cpp DataManagement/mitkRenderingModeProperty.cpp DataManagement/mitkResliceMethodProperty.cpp DataManagement/mitkRestorePlanePositionOperation.cpp DataManagement/mitkRotationOperation.cpp DataManagement/mitkScaleOperation.cpp - DataManagement/mitkShaderProperty.cpp DataManagement/mitkSlicedData.cpp DataManagement/mitkSlicedGeometry3D.cpp DataManagement/mitkSmartPointerProperty.cpp DataManagement/mitkStandaloneDataStorage.cpp DataManagement/mitkStringProperty.cpp DataManagement/mitkSurface.cpp DataManagement/mitkSurfaceOperation.cpp DataManagement/mitkThinPlateSplineCurvedGeometry.cpp DataManagement/mitkTimeGeometry.cpp DataManagement/mitkTransferFunction.cpp DataManagement/mitkTransferFunctionInitializer.cpp DataManagement/mitkTransferFunctionProperty.cpp DataManagement/mitkTemporoSpatialStringProperty.cpp DataManagement/mitkVector.cpp DataManagement/mitkVectorProperty.cpp DataManagement/mitkVtkInterpolationProperty.cpp DataManagement/mitkVtkRepresentationProperty.cpp DataManagement/mitkVtkResliceInterpolationProperty.cpp DataManagement/mitkVtkScalarModeProperty.cpp DataManagement/mitkVtkVolumeRenderingProperty.cpp DataManagement/mitkWeakPointerProperty.cpp Interactions/mitkAction.cpp Interactions/mitkBindDispatcherInteractor.cpp Interactions/mitkCrosshairPositionEvent.cpp Interactions/mitkDataInteractor.cpp Interactions/mitkDispatcher.cpp Interactions/mitkDisplayCoordinateOperation.cpp Interactions/mitkDisplayInteractor.cpp Interactions/mitkEventConfig.cpp Interactions/mitkEventFactory.cpp Interactions/mitkEventRecorder.cpp Interactions/mitkEventStateMachine.cpp Interactions/mitkInteractionEventConst.cpp Interactions/mitkInteractionEvent.cpp Interactions/mitkInteractionEventHandler.cpp Interactions/mitkInteractionEventObserver.cpp Interactions/mitkInteractionKeyEvent.cpp Interactions/mitkInteractionPositionEvent.cpp Interactions/mitkInternalEvent.cpp Interactions/mitkMouseDoubleClickEvent.cpp Interactions/mitkMouseModeSwitcher.cpp Interactions/mitkMouseMoveEvent.cpp Interactions/mitkMousePressEvent.cpp Interactions/mitkMouseReleaseEvent.cpp Interactions/mitkMouseWheelEvent.cpp Interactions/mitkPointSetDataInteractor.cpp Interactions/mitkSinglePointDataInteractor.cpp Interactions/mitkStateMachineAction.cpp Interactions/mitkStateMachineCondition.cpp Interactions/mitkStateMachineContainer.cpp Interactions/mitkStateMachineState.cpp Interactions/mitkStateMachineTransition.cpp Interactions/mitkVtkEventAdapter.cpp Interactions/mitkVtkInteractorStyle.cxx Interactions/mitkXML2EventParser.cpp IO/mitkAbstractFileIO.cpp IO/mitkAbstractFileReader.cpp IO/mitkAbstractFileWriter.cpp IO/mitkCustomMimeType.cpp IO/mitkDicomSeriesReader.cpp IO/mitkDicomSeriesReaderService.cpp IO/mitkDicomSR_GantryTiltInformation.cpp IO/mitkDicomSR_ImageBlockDescriptor.cpp IO/mitkDicomSR_LoadDICOMRGBPixel4D.cpp IO/mitkDicomSR_LoadDICOMRGBPixel.cpp IO/mitkDicomSR_LoadDICOMScalar4D.cpp IO/mitkDicomSR_LoadDICOMScalar.cpp IO/mitkDicomSR_SliceGroupingResult.cpp IO/mitkFileReader.cpp IO/mitkFileReaderRegistry.cpp IO/mitkFileReaderSelector.cpp IO/mitkFileReaderWriterBase.cpp IO/mitkFileWriter.cpp IO/mitkFileWriterRegistry.cpp IO/mitkFileWriterSelector.cpp IO/mitkGeometry3DToXML.cpp IO/mitkIFileIO.cpp IO/mitkIFileReader.cpp IO/mitkIFileWriter.cpp IO/mitkGeometryDataReaderService.cpp IO/mitkGeometryDataWriterService.cpp IO/mitkImageGenerator.cpp IO/mitkImageVtkLegacyIO.cpp IO/mitkImageVtkXmlIO.cpp IO/mitkIMimeTypeProvider.cpp IO/mitkIOConstants.cpp IO/mitkIOMimeTypes.cpp IO/mitkIOUtil.cpp IO/mitkItkImageIO.cpp IO/mitkItkLoggingAdapter.cpp IO/mitkLegacyFileReaderService.cpp IO/mitkLegacyFileWriterService.cpp IO/mitkLocaleSwitch.cpp IO/mitkLog.cpp IO/mitkMimeType.cpp IO/mitkMimeTypeProvider.cpp IO/mitkOperation.cpp IO/mitkPixelType.cpp IO/mitkPointSetReaderService.cpp IO/mitkPointSetWriterService.cpp IO/mitkProportionalTimeGeometryToXML.cpp IO/mitkRawImageFileReader.cpp IO/mitkStandardFileLocations.cpp IO/mitkSurfaceStlIO.cpp IO/mitkSurfaceVtkIO.cpp IO/mitkSurfaceVtkLegacyIO.cpp IO/mitkSurfaceVtkXmlIO.cpp IO/mitkVtkLoggingAdapter.cpp IO/mitkPreferenceListReaderOptionsFunctor.cpp Rendering/mitkAbstractAnnotationRenderer.cpp Rendering/mitkAnnotationUtils.cpp Rendering/mitkBaseRenderer.cpp #Rendering/mitkGLMapper.cpp Moved to deprecated LegacyGL Module Rendering/mitkGradientBackground.cpp Rendering/mitkImageVtkMapper2D.cpp - Rendering/mitkIShaderRepository.cpp Rendering/mitkMapper.cpp Rendering/mitkAnnotation.cpp Rendering/mitkPlaneGeometryDataMapper2D.cpp Rendering/mitkPlaneGeometryDataVtkMapper3D.cpp Rendering/mitkPointSetVtkMapper2D.cpp Rendering/mitkPointSetVtkMapper3D.cpp Rendering/mitkRenderWindowBase.cpp Rendering/mitkRenderWindow.cpp Rendering/mitkRenderWindowFrame.cpp #Rendering/mitkSurfaceGLMapper2D.cpp Moved to deprecated LegacyGL Module Rendering/mitkSurfaceVtkMapper2D.cpp Rendering/mitkSurfaceVtkMapper3D.cpp Rendering/mitkVtkEventProvider.cpp Rendering/mitkVtkMapper.cpp Rendering/mitkVtkPropRenderer.cpp Rendering/mitkVtkWidgetRendering.cpp Rendering/vtkMitkLevelWindowFilter.cpp Rendering/vtkMitkRectangleProp.cpp Rendering/vtkMitkRenderProp.cpp Rendering/vtkMitkThickSlicesFilter.cpp Rendering/vtkNeverTranslucentTexture.cpp ) set(RESOURCE_FILES Interactions/globalConfig.xml Interactions/DisplayInteraction.xml Interactions/DisplayConfig.xml Interactions/DisplayConfigPACS.xml Interactions/DisplayConfigPACSPan.xml Interactions/DisplayConfigPACSScroll.xml Interactions/DisplayConfigPACSZoom.xml Interactions/DisplayConfigPACSLevelWindow.xml Interactions/DisplayConfigMITK.xml Interactions/DisplayConfigMITKNoCrosshair.xml Interactions/DisplayConfigMITKRotation.xml Interactions/DisplayConfigMITKRotationUnCoupled.xml Interactions/DisplayConfigMITKSwivel.xml Interactions/DisplayConfigMITKLimited.xml Interactions/PointSet.xml Interactions/Legacy/StateMachine.xml Interactions/Legacy/DisplayConfigMITKTools.xml Interactions/PointSetConfig.xml mitkLevelWindowPresets.xml mitkAnatomicalStructureColorPresets.xml ) diff --git a/Modules/Core/include/mitkBaseRenderer.h b/Modules/Core/include/mitkBaseRenderer.h index cd126b3c0d..46a372528d 100644 --- a/Modules/Core/include/mitkBaseRenderer.h +++ b/Modules/Core/include/mitkBaseRenderer.h @@ -1,547 +1,558 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 #define BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 #include "mitkCameraRotationController.h" #include "mitkDataStorage.h" #include "mitkPlaneGeometry.h" #include "mitkPlaneGeometryData.h" #include "mitkSliceNavigationController.h" #include "mitkTimeGeometry.h" #include "mitkBindDispatcherInteractor.h" #include "mitkDispatcher.h" #include #include #include #include // DEPRECATED #include namespace mitk { class NavigationController; class SliceNavigationController; class CameraRotationController; class CameraController; class DataStorage; class Mapper; class BaseLocalStorageHandler; class KeyEvent; //##Documentation //## @brief Organizes the rendering process //## //## Organizes the rendering process. A Renderer contains a reference to a //## DataStorage and asks the mappers of the data objects to render //## the data into the renderwindow it is associated to. //## //## \#Render() checks if rendering is currently allowed by calling //## RenderWindow::PrepareRendering(). Initialization of a rendering context //## can also be performed in this method. //## //## The actual rendering code has been moved to \#Repaint() //## Both \#Repaint() and \#Update() are declared protected now. //## //## Note: Separation of the Repaint and Update processes (rendering vs //## creating a vtk prop tree) still needs to be worked on. The whole //## rendering process also should be reworked to use VTK based classes for //## both 2D and 3D rendering. //## @ingroup Renderer class MITKCORE_EXPORT BaseRenderer : public itk::Object { public: /** \brief This rendering mode enumeration is specified at various constructors * of the Renderer and RenderWindow classes, which autoconfigures the * respective VTK objects. This has to be done at construction time because later * configuring turns out to be not working on most platforms. */ struct RenderingMode { enum Type { Standard = 0, // no multi-sampling, no depth-peeling MultiSampling, // multi-sampling (antialiasing), no depth-peeling DepthPeeling // no multi-sampling, depth-peeling is on (order-independant transparency) }; }; typedef std::map BaseRendererMapType; static BaseRendererMapType baseRendererMap; static BaseRenderer *GetInstance(vtkRenderWindow *renWin); static void AddInstance(vtkRenderWindow *renWin, BaseRenderer *baseRenderer); static void RemoveInstance(vtkRenderWindow *renWin); static BaseRenderer *GetByName(const std::string &name); static vtkRenderWindow *GetRenderWindowByName(const std::string &name); #pragma GCC visibility push(default) itkEventMacro(RendererResetEvent, itk::AnyEvent); #pragma GCC visibility pop /** Standard class typedefs. */ mitkClassMacroItkParent(BaseRenderer, itk::Object); BaseRenderer(const char *name = nullptr, vtkRenderWindow *renWin = nullptr, mitk::RenderingManager *rm = nullptr, RenderingMode::Type mode = RenderingMode::Standard); //##Documentation //## @brief MapperSlotId defines which kind of mapper (e.g., 2D or 3D) shoud be used. typedef int MapperSlotId; enum StandardMapperSlot { Standard2D = 1, Standard3D = 2 }; virtual void SetDataStorage(DataStorage *storage); ///< set the datastorage that will be used for rendering //##Documentation //## return the DataStorage that is used for rendering virtual DataStorage::Pointer GetDataStorage() const { return m_DataStorage.GetPointer(); } //##Documentation //## @brief Access the RenderWindow into which this renderer renders. vtkRenderWindow *GetRenderWindow() const { return m_RenderWindow; } vtkRenderer *GetVtkRenderer() const { return m_VtkRenderer; } //##Documentation //## @brief Returns the Dispatcher which handles Events for this BaseRenderer Dispatcher::Pointer GetDispatcher() const; //##Documentation //## @brief Default mapper id to use. static const MapperSlotId defaultMapper; //##Documentation //## @brief Do the rendering and flush the result. virtual void Paint(); //##Documentation //## @brief Initialize the RenderWindow. Should only be called from RenderWindow. virtual void Initialize(); //##Documentation //## @brief Called to inform the renderer that the RenderWindow has been resized. virtual void Resize(int w, int h); //##Documentation //## @brief Initialize the renderer with a RenderWindow (@a renderwindow). virtual void InitRenderer(vtkRenderWindow *renderwindow); //##Documentation //## @brief Set the initial size. Called by RenderWindow after it has become //## visible for the first time. virtual void InitSize(int w, int h); //##Documentation //## @brief Draws a point on the widget. //## Should be used during conferences to show the position of the remote mouse virtual void DrawOverlayMouse(Point2D &p2d); //##Documentation //## @brief Set/Get the WorldGeometry (m_WorldGeometry) for 3D and 2D rendering, that describing the //## (maximal) area to be rendered. //## //## Depending of the type of the passed BaseGeometry more or less information can be extracted: //## \li if it is a PlaneGeometry (which is a sub-class of BaseGeometry), m_CurrentWorldPlaneGeometry is //## also set to point to it. m_WorldTimeGeometry is set to nullptr. //## \li if it is a TimeGeometry, m_WorldTimeGeometry is also set to point to it. //## If m_WorldTimeGeometry contains instances of SlicedGeometry3D, m_CurrentWorldPlaneGeometry is set to //## one of geometries stored in the SlicedGeometry3D according to the value of m_Slice; otherwise //## a PlaneGeometry describing the top of the bounding-box of the BaseGeometry is set as the //## m_CurrentWorldPlaneGeometry. //## \li otherwise a PlaneGeometry describing the top of the bounding-box of the BaseGeometry //## is set as the m_CurrentWorldPlaneGeometry. m_WorldTimeGeometry is set to nullptr. //## @todo add calculation of PlaneGeometry describing the top of the bounding-box of the BaseGeometry //## when the passed BaseGeometry is not sliced. //## \sa m_WorldGeometry //## \sa m_WorldTimeGeometry //## \sa m_CurrentWorldPlaneGeometry virtual void SetWorldGeometry3D(BaseGeometry *geometry); virtual void SetWorldTimeGeometry(mitk::TimeGeometry *geometry); /** * \deprecatedSince{2013_09} Please use TimeGeometry instead of TimeSlicedGeometry. For more information see * http://www.mitk.org/Development/Refactoring%20of%20the%20Geometry%20Classes%20-%20Part%201 */ DEPRECATED(void SetWorldGeometry3D(TimeSlicedGeometry *geometry)); itkGetConstObjectMacro(WorldTimeGeometry, TimeGeometry) itkGetObjectMacro(WorldTimeGeometry, TimeGeometry) //##Documentation //## @brief Get the current 3D-worldgeometry (m_CurrentWorldGeometry) used for 3D-rendering itkGetConstObjectMacro(CurrentWorldGeometry, BaseGeometry) //##Documentation //## @brief Get the current 2D-worldgeometry (m_CurrentWorldPlaneGeometry) used for 2D-rendering itkGetConstObjectMacro(CurrentWorldPlaneGeometry, PlaneGeometry) /** * \deprecatedSince{2014_10} Please use GetCurrentWorldPlaneGeometry */ DEPRECATED(const PlaneGeometry *GetCurrentWorldGeometry2D()) { return GetCurrentWorldPlaneGeometry(); }; //##Documentation //## Calculates the bounds of the DataStorage (if it contains any valid data), //## creates a geometry from these bounds and sets it as world geometry of the renderer. //## //## Call this method to re-initialize the renderer to the current DataStorage //## (e.g. after loading an additional dataset), to ensure that the view is //## aligned correctly. //## \warn This is not implemented yet. virtual bool SetWorldGeometryToDataStorageBounds() { return false; } //##Documentation //## @brief Set/Get m_Slice which defines together with m_TimeStep the 2D geometry //## stored in m_WorldTimeGeometry used as m_CurrentWorldPlaneGeometry //## //## \sa m_Slice virtual void SetSlice(unsigned int slice); itkGetConstMacro(Slice, unsigned int) //##Documentation //## @brief Set/Get m_TimeStep which defines together with m_Slice the 2D geometry //## stored in m_WorldTimeGeometry used as m_CurrentWorldPlaneGeometry //## //## \sa m_TimeStep virtual void SetTimeStep(unsigned int timeStep); itkGetConstMacro(TimeStep, unsigned int) //##Documentation //## @brief Get the time-step of a BaseData object which //## exists at the time of the currently displayed content //## //## Returns -1 or mitk::BaseData::m_TimeSteps if there //## is no data at the current time. //## \sa GetTimeStep, m_TimeStep int GetTimeStep(const BaseData *data) const; //##Documentation //## @brief Get the time in ms of the currently displayed content //## //## \sa GetTimeStep, m_TimeStep ScalarType GetTime() const; //##Documentation //## @brief SetWorldGeometry is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometrySendEvent virtual void SetGeometry(const itk::EventObject &geometrySliceEvent); //##Documentation //## @brief UpdateWorldGeometry is called to re-read the 2D geometry from the //## slice navigation controller virtual void UpdateGeometry(const itk::EventObject &geometrySliceEvent); //##Documentation //## @brief SetSlice is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometrySliceEvent virtual void SetGeometrySlice(const itk::EventObject &geometrySliceEvent); //##Documentation //## @brief SetTimeStep is called according to the geometrySliceEvent, //## which is supposed to be a SliceNavigationController::GeometryTimeEvent virtual void SetGeometryTime(const itk::EventObject &geometryTimeEvent); //##Documentation //## @brief Get a DataNode pointing to a data object containing the current 2D-worldgeometry // m_CurrentWorldPlaneGeometry (for 2D rendering) itkGetObjectMacro(CurrentWorldPlaneGeometryNode, DataNode) /** * \deprecatedSince{2014_10} Please use GetCurrentWorldPlaneGeometryNode */ DEPRECATED(DataNode *GetCurrentWorldGeometry2DNode()) { return GetCurrentWorldPlaneGeometryNode(); }; //##Documentation //## @brief Sets timestamp of CurrentWorldPlaneGeometry and forces so reslicing in that renderwindow void SendUpdateSlice(); //##Documentation //## @brief Get timestamp of last call of SetCurrentWorldPlaneGeometry unsigned long GetCurrentWorldPlaneGeometryUpdateTime() { return m_CurrentWorldPlaneGeometryUpdateTime; } /** * \deprecatedSince{2014_10} Please use GetCurrentWorldPlaneGeometryUpdateTime */ DEPRECATED(unsigned long GetCurrentWorldGeometry2DUpdateTime()) { return GetCurrentWorldPlaneGeometryUpdateTime(); }; //##Documentation //## @brief Get timestamp of last change of current TimeStep unsigned long GetTimeStepUpdateTime() { return m_TimeStepUpdateTime; } //##Documentation //## @brief Perform a picking: find the x,y,z world coordinate of a //## display x,y coordinate. //## @warning Has to be overwritten in subclasses for the 3D-case. //## //## Implemented here only for 2D-rendering virtual void PickWorldPoint(const Point2D &diplayPosition, Point3D &worldPosition) const = 0; /** \brief Determines the object (mitk::DataNode) closest to the current * position by means of picking * * \warning Implementation currently empty for 2D rendering; intended to be * implemented for 3D renderers */ virtual DataNode *PickObject(const Point2D & /*displayPosition*/, Point3D & /*worldPosition*/) const { return nullptr; } //##Documentation //## @brief Get the MapperSlotId to use. itkGetMacro(MapperID, MapperSlotId) itkGetConstMacro(MapperID, MapperSlotId) //##Documentation //## @brief Set the MapperSlotId to use. itkSetMacro(MapperID, MapperSlotId) virtual int *GetSize() const; virtual int *GetViewportSize() const; void SetSliceNavigationController(SliceNavigationController *SlicenavigationController); itkGetObjectMacro(CameraController, CameraController) itkGetObjectMacro(SliceNavigationController, SliceNavigationController) itkGetObjectMacro(CameraRotationController, CameraRotationController) itkGetMacro(EmptyWorldGeometry, bool) //##Documentation //## @brief Tells if the displayed region is shifted and rescaled if the render window is resized. itkGetMacro(KeepDisplayedRegion, bool) //##Documentation //## @brief Tells if the displayed region should be shifted and rescaled if the render window is resized. itkSetMacro(KeepDisplayedRegion, bool) //##Documentation //## @brief get the name of the Renderer //## @note const char *GetName() const { return m_Name.c_str(); } //##Documentation //## @brief get the x_size of the RendererWindow //## @note int GetSizeX() const { return GetSize()[0]; } //##Documentation //## @brief get the y_size of the RendererWindow //## @note int GetSizeY() const { return GetSize()[1]; } const double *GetBounds() const; void RequestUpdate(); void ForceImmediateUpdate(); /** Returns number of mappers which are visible and have level-of-detail * rendering enabled */ unsigned int GetNumberOfVisibleLODEnabledMappers() const; ///** //* \brief Setter for the RenderingManager that handles this instance of BaseRenderer //*/ // void SetRenderingManager( mitk::RenderingManager* ); /** * \brief Getter for the RenderingManager that handles this instance of BaseRenderer */ virtual mitk::RenderingManager *GetRenderingManager() const; //##Documentation //## @brief This method converts a display point to the 3D world index //## using the geometry of the renderWindow. void DisplayToWorld(const Point2D &displayPoint, Point3D &worldIndex) const; //##Documentation //## @brief This method converts a display point to the 2D world index, mapped onto the display plane //## using the geometry of the renderWindow. void DisplayToPlane(const Point2D &displayPoint, Point2D &planePointInMM) const; //##Documentation //## @brief This method converts a 3D world index to the display point //## using the geometry of the renderWindow. void WorldToDisplay(const Point3D &worldIndex, Point2D &displayPoint) const; + //##Documentation + //## @brief This method converts a 3D world index to the point on the viewport + //## using the geometry of the renderWindow. + void WorldToView(const Point3D &worldIndex, Point2D &viewPoint) const; + //##Documentation //## @brief This method converts a 2D plane coordinate to the display point //## using the geometry of the renderWindow. void PlaneToDisplay(const Point2D &planePointInMM, Point2D &displayPoint) const; + //##Documentation + //## @brief This method converts a 2D plane coordinate to the point on the viewport + //## using the geometry of the renderWindow. + void PlaneToView(const Point2D &planePointInMM, Point2D &viewPoint) const; + + double GetScaleFactorMMPerDisplayUnit() const; Point2D GetDisplaySizeInMM() const; Point2D GetViewportSizeInMM() const; Point2D GetOriginInMM() const; itkGetConstMacro(ConstrainZoomingAndPanning, bool) virtual void SetConstrainZoomingAndPanning(bool constrain); /** * \brief Provides (1) world coordinates for a given mouse position and (2) * translates mousePosition to Display coordinates * \deprecated Map2DRendererPositionTo3DWorldPosition is deprecated. Please use DisplayToWorld instead. */ DEPRECATED(virtual Point3D Map2DRendererPositionTo3DWorldPosition(const Point2D &mousePosition) const); protected: virtual ~BaseRenderer(); //##Documentation //## @brief Call update of all mappers. To be implemented in subclasses. virtual void Update() = 0; vtkRenderWindow *m_RenderWindow; vtkRenderer *m_VtkRenderer; //##Documentation //## @brief MapperSlotId to use. Defines which kind of mapper (e.g., 2D or 3D) shoud be used. MapperSlotId m_MapperID; //##Documentation //## @brief The DataStorage that is used for rendering. DataStorage::Pointer m_DataStorage; //##Documentation //## @brief The RenderingManager that manages this instance RenderingManager::Pointer m_RenderingManager; //##Documentation //## @brief Timestamp of last call of Update(). unsigned long m_LastUpdateTime; //##Documentation //## @brief CameraController for 3D rendering //## @note preliminary. itk::SmartPointer m_CameraController; SliceNavigationController::Pointer m_SliceNavigationController; CameraRotationController::Pointer m_CameraRotationController; //##Documentation //## @brief Sets m_CurrentWorldPlaneGeometry virtual void SetCurrentWorldPlaneGeometry(PlaneGeometry *geometry2d); /** * \deprecatedSince{2014_10} Please use SetCurrentWorldPlaneGeometry */ DEPRECATED(void SetCurrentWorldGeometry2D(PlaneGeometry *geometry2d)) { SetCurrentWorldPlaneGeometry(geometry2d); }; //##Documentation //## @brief Sets m_CurrentWorldGeometry virtual void SetCurrentWorldGeometry(BaseGeometry *geometry); private: //##Documentation //## m_WorldTimeGeometry is set by SetWorldGeometry if the passed BaseGeometry is a //## TimeGeometry (or a sub-class of it). If it contains instances of SlicedGeometry3D, //## m_Slice and m_TimeStep (set via SetSlice and SetTimeStep, respectively) define //## which 2D geometry stored in m_WorldTimeGeometry (if available) //## is used as m_CurrentWorldPlaneGeometry. //## \sa m_CurrentWorldPlaneGeometry TimeGeometry::Pointer m_WorldTimeGeometry; //##Documentation //## Pointer to the current 3D-worldgeometry. BaseGeometry::Pointer m_CurrentWorldGeometry; //##Documentation //## Pointer to the current 2D-worldgeometry. The 2D-worldgeometry //## describes the maximal area (2D manifold) to be rendered in case we //## are doing 2D-rendering. //## It is const, since we are not allowed to change it (it may be taken //## directly from the geometry of an image-slice and thus it would be //## very strange when suddenly the image-slice changes its geometry). PlaneGeometry::Pointer m_CurrentWorldPlaneGeometry; //##Documentation //## Defines together with m_Slice which 2D geometry stored in m_WorldTimeGeometry //## is used as m_CurrentWorldPlaneGeometry: m_WorldTimeGeometry->GetPlaneGeometry(m_Slice, m_TimeStep). //## \sa m_WorldTimeGeometry unsigned int m_Slice; //##Documentation //## Defines together with m_TimeStep which 2D geometry stored in m_WorldTimeGeometry //## is used as m_CurrentWorldPlaneGeometry: m_WorldTimeGeometry->GetPlaneGeometry(m_Slice, m_TimeStep). //## \sa m_WorldTimeGeometry unsigned int m_TimeStep; //##Documentation //## @brief timestamp of last call of SetWorldGeometry itk::TimeStamp m_CurrentWorldPlaneGeometryUpdateTime; //##Documentation //## @brief timestamp of last change of the current time step itk::TimeStamp m_TimeStepUpdateTime; //##Documentation //## @brief Helper class which establishes connection between Interactors and Dispatcher via a common DataStorage. BindDispatcherInteractor *m_BindDispatcherInteractor; //##Documentation //## @brief Tells if the displayed region should be shifted or rescaled if the render window is resized. bool m_KeepDisplayedRegion; protected: virtual void PrintSelf(std::ostream &os, itk::Indent indent) const override; //##Documentation //## Data object containing the m_CurrentWorldPlaneGeometry defined above. PlaneGeometryData::Pointer m_CurrentWorldPlaneGeometryData; //##Documentation //## DataNode objects containing the m_CurrentWorldPlaneGeometryData defined above. DataNode::Pointer m_CurrentWorldPlaneGeometryNode; //##Documentation //## @brief test only unsigned long m_CurrentWorldPlaneGeometryTransformTime; std::string m_Name; double m_Bounds[6]; bool m_EmptyWorldGeometry; typedef std::set LODEnabledMappersType; /** Number of mappers which are visible and have level-of-detail * rendering enabled */ unsigned int m_NumberOfVisibleLODEnabledMappers; // Local Storage Handling for mappers protected: std::list m_RegisteredLocalStorageHandlers; bool m_ConstrainZoomingAndPanning; public: void RemoveAllLocalStorages(); void RegisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh); void UnregisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh); }; } // namespace mitk #endif /* BASERENDERER_H_HEADER_INCLUDED_C1CCA0F4 */ diff --git a/Modules/Core/include/mitkCoreServices.h b/Modules/Core/include/mitkCoreServices.h index cc91558851..d47043e871 100644 --- a/Modules/Core/include/mitkCoreServices.h +++ b/Modules/Core/include/mitkCoreServices.h @@ -1,173 +1,166 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKCORESERVICES_H #define MITKCORESERVICES_H #include "MitkCoreExports.h" #include #include #include #include #include #include #include namespace mitk { struct IMimeTypeProvider; - struct IShaderRepository; class IPropertyAliases; class IPropertyDescriptions; class IPropertyExtensions; class IPropertyFilters; class IPropertyPersistence; /** * @brief Access MITK core services. * * This class can be used to conveniently access common * MITK Core service objects. Some getter methods where implementations * exist in the core library are guaranteed to return a non-nullptr service object. * * To ensure that CoreServices::Unget() is called after the caller * has finished using a service object, you should use the CoreServicePointer * helper class which calls Unget() when it goes out of scope: * * \code * CoreServicePointer shaderRepo(CoreServices::GetShaderRepository()); * // Do something with shaderRepo * \endcode * * @see CoreServicePointer */ class MITKCORE_EXPORT CoreServices { public: - /** - * @brief Get an IShaderRepository instance. - * @param context The module context of the module getting the service. - * @return A IShaderRepository instance which can be nullptr. - */ - static IShaderRepository *GetShaderRepository(); /** * @brief Get an IPropertyAliases instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyAliases instance. */ static IPropertyAliases *GetPropertyAliases(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IPropertyDescriptions instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyDescriptions instance. */ static IPropertyDescriptions *GetPropertyDescriptions(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IPropertyExtensions instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyExtensions instance. */ static IPropertyExtensions *GetPropertyExtensions(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IPropertyFilters instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyFilters instance. */ static IPropertyFilters *GetPropertyFilters(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IPropertyPersistence instance. * @param context The module context of the module getting the service. * @return A non-nullptr IPropertyPersistence instance. */ static IPropertyPersistence *GetPropertyPersistence(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Get an IMimeTypeProvider instance. * @param context The module context of the module getting the service. * @return A non-nullptr IMimeTypeProvider instance. */ static IMimeTypeProvider *GetMimeTypeProvider(us::ModuleContext *context = us::GetModuleContext()); /** * @brief Unget a previously acquired service instance. * @param service The service instance to be released. * @return \c true if ungetting the service was successful, \c false otherwise. */ template static bool Unget(S *service, us::ModuleContext *context = us::GetModuleContext()) { return Unget(context, us_service_interface_iid(), service); } private: static bool Unget(us::ModuleContext *context, const std::string &interfaceId, void *service); // purposely not implemented CoreServices(); CoreServices(const CoreServices &); CoreServices &operator=(const CoreServices &); }; /** * @brief A RAII helper class for core service objects. * * This is class is intended for usage in local scopes; it calls * CoreServices::Unget(S*) in its destructor. You should not construct * multiple CoreServicePointer instances using the same service pointer, * unless it is retrieved by a new call to a CoreServices getter method. * * @see CoreServices */ template class MITK_LOCAL CoreServicePointer { public: explicit CoreServicePointer(S *service) : m_service(service) { assert(m_service); } ~CoreServicePointer() { try { CoreServices::Unget(m_service); } catch (const std::exception &e) { MITK_ERROR << e.what(); } catch (...) { MITK_ERROR << "Ungetting core service failed."; } } S *operator->() const { return m_service; } private: // purposely not implemented CoreServicePointer(const CoreServicePointer &); CoreServicePointer &operator=(const CoreServicePointer &); S *const m_service; }; } #endif // MITKCORESERVICES_H diff --git a/Modules/Core/include/mitkIShaderRepository.h b/Modules/Core/include/mitkIShaderRepository.h deleted file mode 100644 index 749e4adb91..0000000000 --- a/Modules/Core/include/mitkIShaderRepository.h +++ /dev/null @@ -1,136 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef MITKISHADERREPOSITORY_H -#define MITKISHADERREPOSITORY_H - -#include - -#include "mitkCommon.h" -#include "mitkServiceInterface.h" - -#include - -class vtkActor; -class vtkShaderProgram2; - -namespace mitk -{ - class DataNode; - class BaseRenderer; - - /** - * \ingroup MicroServices_Interfaces - * \brief Management class for vtkShader XML descriptions. - * - * Loads XML shader files from std::istream objects and adds default properties - * for each shader object (shader uniforms) to the specified mitk::DataNode. - * - * Additionally, it provides a utility function for applying properties for shaders - * in mappers. - */ - struct MITKCORE_EXPORT IShaderRepository - { - struct ShaderPrivate; - - class MITKCORE_EXPORT Shader : public itk::LightObject - { - public: - mitkClassMacroItkParent(Shader, itk::LightObject) itkFactorylessNewMacro(Self) - - ~Shader(); - - int GetId() const; - std::string GetName() const; - std::string GetMaterialXml() const; - - protected: - Shader(); - - void SetId(int id); - void SetName(const std::string &name); - void SetMaterialXml(const std::string &xml); - - private: - // not implemented - Shader(const Shader &); - Shader &operator=(const Shader &); - - ShaderPrivate *d; - }; - - class MITKCORE_EXPORT ShaderProgram : public itk::LightObject - { - public: - virtual void Activate() = 0; - virtual void Deactivate() = 0; - mitkClassMacroItkParent(ShaderProgram, itk::LightObject) - }; - - virtual ~IShaderRepository(); - - virtual std::list GetShaders() const = 0; - - /** - * \brief Return the named shader. - * - * \param name The shader name. - * \return A Shader object. - * - * Names might not be unique. Use the shader id to uniquely identify a shader. - */ - virtual Shader::Pointer GetShader(const std::string &name) const = 0; - - virtual ShaderProgram::Pointer CreateShaderProgram() = 0; - - /** - * \brief Return the shader identified by the given id. - * @param id The shader id. - * @return The shader object or null if the id is unknown. - */ - virtual Shader::Pointer GetShader(int id) const = 0; - - /** \brief Adds all parsed shader uniforms to property list of the given DataNode; - * used by mappers. - */ - virtual void AddDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) const = 0; - - /** \brief Applies shader and shader specific variables of the specified DataNode - * to the VTK object by updating the shader variables of its vtkProperty. - */ - virtual void UpdateShaderProgram(mitk::IShaderRepository::ShaderProgram *shaderProgram, - mitk::DataNode *node, - mitk::BaseRenderer *renderer) const = 0; - - /** \brief Loads a shader from a given file. Make sure that this stream is in the XML shader format. - * - * \return A unique id for the loaded shader which can be used to unload it. - */ - virtual int LoadShader(std::istream &stream, const std::string &name) = 0; - - /** - * \brief Unload a previously loaded shader. - * \param id The unique shader id returned by LoadShader. - * \return \c true if the shader id was found and the shader was successfully unloaded, - * \c false otherwise. - */ - virtual bool UnloadShader(int id) = 0; - }; -} - -MITK_DECLARE_SERVICE_INTERFACE(mitk::IShaderRepository, "org.mitk.services.IShaderRepository/1.0") - -#endif // MITKISHADERREPOSITORY_H diff --git a/Modules/Core/include/mitkMapper.h b/Modules/Core/include/mitkMapper.h index 2d9e8aefe7..e88076edf8 100644 --- a/Modules/Core/include/mitkMapper.h +++ b/Modules/Core/include/mitkMapper.h @@ -1,212 +1,212 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MAPPER_H_HEADER_INCLUDED_C1E6EA08 #define MAPPER_H_HEADER_INCLUDED_C1E6EA08 #include "mitkBaseRenderer.h" #include "mitkCommon.h" #include "mitkLevelWindow.h" #include "mitkLocalStorageHandler.h" #include "mitkVtkPropRenderer.h" #include #include #include // Just included to get VTK version #include class vtkWindow; class vtkProp; namespace mitk { class BaseRenderer; class BaseData; class DataNode; /** \brief Base class of all mappers, Vtk as well as OpenGL mappers * * By the help of mappers, the input data is transformed to tangible primitives, * such as surfaces, points, lines, etc. * This is the base class of all mappers, Vtk as well as OpenGL mappers. * Subclasses of mitk::Mapper control the creation of rendering primitives * that interface to the graphics library (e.g., OpenGL, vtk). * * \todo Should Mapper be a subclass of ImageSource? * \ingroup Mapper */ class MITKCORE_EXPORT Mapper : public itk::Object { public: mitkClassMacroItkParent(Mapper, itk::Object); /** \brief Set the DataNode containing the data to map */ itkSetObjectMacro(DataNode, DataNode); /** \brief Get the DataNode containing the data to map. * Method only returns valid DataNode Pointer if the mapper belongs to a data node. * Otherwise, the returned DataNode Pointer might be invalid. */ virtual DataNode *GetDataNode() const; /**\brief Get the data to map * * Returns the mitk::BaseData object associated with this mapper. * \return the mitk::BaseData associated with this mapper. * \deprecatedSince{2013_03} Use GetDataNode()->GetData() instead to access the data */ DEPRECATED(BaseData *GetData() const); /** \brief Convenience access method for color properties (instances of * ColorProperty) * \return \a true property was found * \deprecatedSince{2013_03} Use GetDataNode()->GetColor(...) instead to get the color */ DEPRECATED(virtual bool GetColor(float rgb[3], BaseRenderer *renderer, const char *name = "color") const); /** \brief Convenience access method for visibility properties (instances * of BoolProperty) * \return \a true property was found * \sa IsVisible * \deprecatedSince{2013_03} Use GetDataNode()->GetVisibility(...) instead to get the visibility */ DEPRECATED(virtual bool GetVisibility(bool &visible, BaseRenderer *renderer, const char *name = "visible") const); /** \brief Convenience access method for opacity properties (instances of * FloatProperty) * \return \a true property was found * \deprecatedSince{2013_03} Use GetDataNode()->GetOpacity(...) instead to get the opacity */ DEPRECATED(virtual bool GetOpacity(float &opacity, BaseRenderer *renderer, const char *name = "opacity") const); /** \brief Convenience access method for color properties (instances of * LevelWindoProperty) * \return \a true property was found * \deprecatedSince{2013_03} Use GetDataNode->GetLevelWindow(...) instead to get the levelwindow */ DEPRECATED(virtual bool GetLevelWindow(LevelWindow &levelWindow, BaseRenderer *renderer, const char *name = "levelwindow") const); /** \brief Convenience access method for visibility properties (instances * of BoolProperty). Return value is the visibility. Default is * visible==true, i.e., true is returned even if the property (\a * propertyKey) is not found. * * Thus, the return value has a different meaning than in the * GetVisibility method! * \sa GetVisibility * \deprecatedSince{2013_03} Use GetDataNode()->GetVisibility(...) instead */ DEPRECATED(virtual bool IsVisible(BaseRenderer *renderer, const char *name = "visible") const); /** \brief Returns whether this is an vtk-based mapper * \deprecatedSince{2013_03} All mappers of superclass VTKMapper are vtk based, use a dynamic_cast instead */ - virtual bool IsVtkBased() const = 0; + virtual bool IsVtkBased() const { return true; } /** \brief Calls the time step of the input data for the specified renderer and checks * whether the time step is valid and calls method GenerateDataForRenderer() */ virtual void Update(BaseRenderer *renderer); /** \brief Responsible for calling the appropriate render functions. * To be implemented in sub-classes. */ virtual void MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type) = 0; /** * \brief Apply specific color and opacity properties read from the PropertyList. * Reimplemented in GLmapper (does not use the actor) and the VtkMapper class. * The function is called by the individual mapper (mostly in the ApplyProperties() or ApplyAllProperties() * method). */ virtual void ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor *actor = nullptr) = 0; /** \brief Set default values of properties used by this mapper * to \a node * * \param node The node for which the properties are set * \param overwrite overwrite existing properties (default: \a false) * \param renderer defines which property list of node is used * (default: \a nullptr, i.e. default property list) */ static void SetDefaultProperties(DataNode *node, BaseRenderer *renderer = nullptr, bool overwrite = false); /** \brief Returns the current time step as calculated from the renderer */ int GetTimestep() const { return m_TimeStep; } /** Returns true if this Mapper currently allows for Level-of-Detail rendering. * This reflects whether this Mapper currently invokes StartEvent, EndEvent, and * ProgressEvent on BaseRenderer. */ virtual bool IsLODEnabled(BaseRenderer * /*renderer*/) const { return false; } protected: /** \brief explicit constructor which disallows implicit conversions */ explicit Mapper(); /** \brief virtual destructor in order to derive from this class */ virtual ~Mapper(); /** \brief Generate the data needed for rendering (independent of a specific renderer) * \deprecatedSince{2013_03} Use GenerateDataForRenderer(BaseRenderer* renderer) instead. */ DEPRECATED(virtual void GenerateData()) {} /** \brief Generate the data needed for rendering into \a renderer */ virtual void GenerateDataForRenderer(BaseRenderer * /* renderer */) {} /** \brief Updates the time step, which is sometimes needed in subclasses */ virtual void CalculateTimeStep(BaseRenderer *renderer); /** \brief Reset the mapper (i.e., make sure that nothing is displayed) if no * valid data is present. In most cases the reimplemented function * disables the according actors (toggling visibility off) * * To be implemented in sub-classes. */ virtual void ResetMapper(BaseRenderer * /*renderer*/) {} mitk::DataNode *m_DataNode; private: /** \brief The current time step of the dataset to be rendered, * for use in subclasses. * The current timestep can be accessed via the GetTimestep() method. */ int m_TimeStep; /** \brief copy constructor */ Mapper(const Mapper &); /** \brief assignment operator */ Mapper &operator=(const Mapper &); public: /** \brief Base class for mapper specific rendering ressources. */ class MITKCORE_EXPORT BaseLocalStorage { public: bool IsGenerateDataRequired(mitk::BaseRenderer *renderer, mitk::Mapper *mapper, mitk::DataNode *dataNode) const; inline void UpdateGenerateDataTime() { m_LastGenerateDataTime.Modified(); } inline itk::TimeStamp &GetLastGenerateDataTime() { return m_LastGenerateDataTime; } protected: /** \brief timestamp of last update of stored data */ itk::TimeStamp m_LastGenerateDataTime; }; }; } // namespace mitk #endif /* MAPPER_H_HEADER_INCLUDED_C1E6EA08 */ diff --git a/Modules/Core/include/mitkPlaneClipping.h b/Modules/Core/include/mitkPlaneClipping.h index 0500a22f35..3f9748922b 100644 --- a/Modules/Core/include/mitkPlaneClipping.h +++ b/Modules/Core/include/mitkPlaneClipping.h @@ -1,154 +1,155 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKPLANECLIPPING_H_HEADER_INCLUDED #define MITKPLANECLIPPING_H_HEADER_INCLUDED #include #include #include +#include #include namespace mitk { namespace PlaneClipping { /** \brief Internal helper method for intersection testing used only in CalculateClippedPlaneBounds() */ static bool LineIntersectZero(vtkPoints *points, int p1, int p2, double *bounds) { double point1[3]; double point2[3]; points->GetPoint(p1, point1); points->GetPoint(p2, point2); if ((point1[2] * point2[2] <= 0.0) && (point1[2] != point2[2])) { double x, y; x = (point1[0] * point2[2] - point1[2] * point2[0]) / (point2[2] - point1[2]); y = (point1[1] * point2[2] - point1[2] * point2[1]) / (point2[2] - point1[2]); if (x < bounds[0]) { bounds[0] = x; } if (x > bounds[1]) { bounds[1] = x; } if (y < bounds[2]) { bounds[2] = y; } if (y > bounds[3]) { bounds[3] = y; } bounds[4] = bounds[5] = 0.0; return true; } return false; } /** \brief Calculate the bounding box of the resliced image. This is necessary for arbitrarily rotated planes in an image volume. A rotated plane (e.g. in swivel mode) will have a new bounding box, which needs to be calculated. */ static bool CalculateClippedPlaneBounds(const BaseGeometry *boundingGeometry, const PlaneGeometry *planeGeometry, double *bounds) { // Clip the plane with the bounding geometry. To do so, the corner points // of the bounding box are transformed by the inverse transformation // matrix, and the transformed bounding box edges derived therefrom are // clipped with the plane z=0. The resulting min/max values are taken as // bounds for the image reslicer. const mitk::BoundingBox *boundingBox = boundingGeometry->GetBoundingBox(); mitk::BoundingBox::PointType bbMin = boundingBox->GetMinimum(); mitk::BoundingBox::PointType bbMax = boundingBox->GetMaximum(); vtkSmartPointer points = vtkSmartPointer::New(); if (boundingGeometry->GetImageGeometry()) { points->InsertPoint(0, bbMin[0] - 0.5, bbMin[1] - 0.5, bbMin[2] - 0.5); points->InsertPoint(1, bbMin[0] - 0.5, bbMin[1] - 0.5, bbMax[2] - 0.5); points->InsertPoint(2, bbMin[0] - 0.5, bbMax[1] - 0.5, bbMax[2] - 0.5); points->InsertPoint(3, bbMin[0] - 0.5, bbMax[1] - 0.5, bbMin[2] - 0.5); points->InsertPoint(4, bbMax[0] - 0.5, bbMin[1] - 0.5, bbMin[2] - 0.5); points->InsertPoint(5, bbMax[0] - 0.5, bbMin[1] - 0.5, bbMax[2] - 0.5); points->InsertPoint(6, bbMax[0] - 0.5, bbMax[1] - 0.5, bbMax[2] - 0.5); points->InsertPoint(7, bbMax[0] - 0.5, bbMax[1] - 0.5, bbMin[2] - 0.5); } else { points->InsertPoint(0, bbMin[0], bbMin[1], bbMin[2]); points->InsertPoint(1, bbMin[0], bbMin[1], bbMax[2]); points->InsertPoint(2, bbMin[0], bbMax[1], bbMax[2]); points->InsertPoint(3, bbMin[0], bbMax[1], bbMin[2]); points->InsertPoint(4, bbMax[0], bbMin[1], bbMin[2]); points->InsertPoint(5, bbMax[0], bbMin[1], bbMax[2]); points->InsertPoint(6, bbMax[0], bbMax[1], bbMax[2]); points->InsertPoint(7, bbMax[0], bbMax[1], bbMin[2]); } vtkSmartPointer newPoints = vtkSmartPointer::New(); vtkSmartPointer transform = vtkSmartPointer::New(); transform->Identity(); transform->Concatenate(planeGeometry->GetVtkTransform()->GetLinearInverse()); transform->Concatenate(boundingGeometry->GetVtkTransform()); transform->TransformPoints(points, newPoints); bounds[0] = bounds[2] = 10000000.0; bounds[1] = bounds[3] = -10000000.0; bounds[4] = bounds[5] = 0.0; LineIntersectZero(newPoints, 0, 1, bounds); LineIntersectZero(newPoints, 1, 2, bounds); LineIntersectZero(newPoints, 2, 3, bounds); LineIntersectZero(newPoints, 3, 0, bounds); LineIntersectZero(newPoints, 0, 4, bounds); LineIntersectZero(newPoints, 1, 5, bounds); LineIntersectZero(newPoints, 2, 6, bounds); LineIntersectZero(newPoints, 3, 7, bounds); LineIntersectZero(newPoints, 4, 5, bounds); LineIntersectZero(newPoints, 5, 6, bounds); LineIntersectZero(newPoints, 6, 7, bounds); LineIntersectZero(newPoints, 7, 4, bounds); if ((bounds[0] > 9999999.0) || (bounds[2] > 9999999.0) || (bounds[1] < -9999999.0) || (bounds[3] < -9999999.0)) { return false; } else { // The resulting bounds must be adjusted by the plane spacing, since we // we have so far dealt with index coordinates const mitk::Vector3D planeSpacing = planeGeometry->GetSpacing(); bounds[0] *= planeSpacing[0]; bounds[1] *= planeSpacing[0]; bounds[2] *= planeSpacing[1]; bounds[3] *= planeSpacing[1]; bounds[4] *= planeSpacing[2]; bounds[5] *= planeSpacing[2]; return true; } } } } #endif diff --git a/Modules/Core/include/mitkShaderProperty.h b/Modules/Core/include/mitkShaderProperty.h deleted file mode 100644 index 0d82ee1d2f..0000000000 --- a/Modules/Core/include/mitkShaderProperty.h +++ /dev/null @@ -1,111 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef __MITKSHADERENUMPROPERTY_H -#define __MITKSHADERENUMPROPERTY_H - -#include "mitkEnumerationProperty.h" - -namespace mitk -{ -#ifdef _MSC_VER -#pragma warning(push) -#pragma warning(disable : 4522) -#endif - - /** - * Encapsulates the shader enumeration - */ - class MITKCORE_EXPORT ShaderProperty : public EnumerationProperty - { - public: - class Element - { - public: - std::string name; - }; - - mitkClassMacro(ShaderProperty, EnumerationProperty); - - itkFactorylessNewMacro(Self) itkCloneMacro(Self) - - mitkNewMacro1Param(ShaderProperty, const IdType &); - - mitkNewMacro1Param(ShaderProperty, const std::string &); - - /** - * Returns the current scalar mode value as defined by VTK constants. - * @returns the current scalar mode as VTK constant. - */ - IdType GetShaderId(); - std::string GetShaderName(); - void SetShader(const IdType &i); - void SetShader(const std::string &i); - - using BaseProperty::operator=; - - protected: - std::list shaderList; - - /** - * Constructor. Sets the representation to a default value of surface(2) - */ - ShaderProperty(); - - ShaderProperty(const ShaderProperty &other); - - /** - * \brief Sets the scalar mode to the given value. If it is not - * valid, the scalar mode is set to default (0). - * @param value the integer representation of the scalar mode - */ - ShaderProperty(const IdType &value); - - /** - * \brief Sets the scalar mode to the given value. If it is not - * valid, the representation is set to default (0). - * @param value the string representation of the scalar mode - */ - ShaderProperty(const std::string &value); - - /** - * this function is overridden as protected, so that the user may not add - * additional invalid scalar mode types. - */ - bool AddEnum(const std::string &name, const IdType &id = 0) override; - - /** - * Adds the enumeration types as defined by vtk to the list of known - * enumeration values. - */ - void AddShaderTypes(); - - private: - // purposely not implemented - ShaderProperty &operator=(const ShaderProperty &); - - virtual itk::LightObject::Pointer InternalClone() const override; - - virtual bool Assign(const BaseProperty &property) override; - }; - -#ifdef _MSC_VER -#pragma warning(pop) -#endif - -} // end of namespace mitk - -#endif //_MITK_VTK_SCALARMODE_PROPERTY__H_ diff --git a/Modules/Core/include/mitkSurfaceVtkMapper3D.h b/Modules/Core/include/mitkSurfaceVtkMapper3D.h index 57f3ca187c..cecdab1456 100644 --- a/Modules/Core/include/mitkSurfaceVtkMapper3D.h +++ b/Modules/Core/include/mitkSurfaceVtkMapper3D.h @@ -1,148 +1,147 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkSurfaceVtkMapper3D_h #define mitkSurfaceVtkMapper3D_h #include "mitkBaseRenderer.h" #include "mitkLocalStorageHandler.h" #include "mitkVtkMapper.h" #include #include #include #include -#include #include #include #include #include namespace mitk { /** * @brief Vtk-based mapper for Surfaces. * * The mapper renders a surface in 3D. The actor is adapted according to the geometry in * the base class in mitk::VtkMapper::UpdateVtkTransform(). * * Properties that can be set for surfaces and influence the surfaceVTKMapper3D are: * * - \b "Backface Culling": True enables backface culling, which means only front-facing polygons will be visualized. False/disabled by default. * - \b "color": (ColorProperty) Diffuse color of the surface object (this property will be read when material.diffuseColor is not defined) * - \b "Opacity": (FloatProperty) Opacity of the surface object * - \b "material.ambientColor": (ColorProperty) Ambient color of the surface object * - \b "material.ambientCoefficient": ( FloatProperty) Ambient coefficient of the surface object * - \b "material.diffuseColor": ( ColorProperty) Diffuse color of the surface object * - \b "material.diffuseCoefficient": (FloatProperty) Diffuse coefficient of the surface object * - \b "material.specularColor": (ColorProperty) Specular Color of the surface object * - \b "material.specularCoefficient": (FloatProperty) Specular coefficient of the surface object * - \b "material.specularPower": (FloatProperty) Specular power of the surface object * - \b "material.interpolation": (VtkInterpolationProperty) Interpolation * - \b "material.representation": (VtkRepresentationProperty*) Representation * - \b "material.wireframeLineWidth": (FloatProperty) Width in pixels of the lines drawn. * - \b "material.pointSize": (FloatProperty) Size in pixels of the points drawn. * - \b "scalar visibility": (BoolProperty) If the scarlars of the surface are visible * - \b "Surface.TransferFunction (TransferFunctionProperty) Set a transferfunction for coloring the surface * - \b "LookupTable (LookupTableProperty) LookupTable * Properties to look for are: * * - \b "scalar visibility": if set to on, scalars assigned to the data are shown * Turn this on if using a lookup table. * - \b "ScalarsRangeMinimum": Optional. Can be used to store the scalar min, e.g. * for the level window settings. * - \b "ScalarsRangeMaximum": Optional. See above. * * There might be still some other, deprecated properties. These will not be documented anymore. * Please check the source if you really need them. * * @ingroup Mapper */ class MITKCORE_EXPORT SurfaceVtkMapper3D : public VtkMapper { public: mitkClassMacro(SurfaceVtkMapper3D, VtkMapper); itkFactorylessNewMacro(Self) itkCloneMacro(Self) itkSetMacro(GenerateNormals, bool); itkGetMacro(GenerateNormals, bool); virtual const mitk::Surface *GetInput(); virtual vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; virtual void ApplyAllProperties(mitk::BaseRenderer *renderer, vtkActor *actor); static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); protected: SurfaceVtkMapper3D(); virtual ~SurfaceVtkMapper3D(); virtual void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; virtual void ResetMapper(mitk::BaseRenderer *renderer) override; /** Checks whether the specified property is a ClippingProperty and if yes, * adds it to m_ClippingPlaneCollection (internal method). */ virtual void CheckForClippingProperty(mitk::BaseRenderer *renderer, mitk::BaseProperty *property); bool m_GenerateNormals; public: class LocalStorage : public mitk::Mapper::BaseLocalStorage { public: vtkSmartPointer m_Actor; - vtkSmartPointer m_VtkPolyDataMapper; + vtkSmartPointer m_VtkPolyDataMapper; vtkSmartPointer m_VtkPolyDataNormals; vtkSmartPointer m_ClippingPlaneCollection; vtkSmartPointer m_DepthSort; itk::TimeStamp m_ShaderTimestampUpdate; LocalStorage() { - m_VtkPolyDataMapper = vtkSmartPointer::New(); + m_VtkPolyDataMapper = vtkSmartPointer::New(); m_VtkPolyDataNormals = vtkSmartPointer::New(); m_Actor = vtkSmartPointer::New(); m_ClippingPlaneCollection = vtkSmartPointer::New(); m_Actor->SetMapper(m_VtkPolyDataMapper); m_DepthSort = vtkSmartPointer::New(); } ~LocalStorage() {} }; mitk::LocalStorageHandler m_LSH; static void ApplyMitkPropertiesToVtkProperty(mitk::DataNode *node, vtkProperty *property, mitk::BaseRenderer *renderer); static void SetDefaultPropertiesForVtkProperty(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite); }; } // namespace mitk #endif /* mitkSurfaceVtkMapper3D_h */ diff --git a/Modules/Core/include/mitkVtkMapper.h b/Modules/Core/include/mitkVtkMapper.h index 15cd86b0d3..0ddd7616f8 100644 --- a/Modules/Core/include/mitkVtkMapper.h +++ b/Modules/Core/include/mitkVtkMapper.h @@ -1,177 +1,170 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // change number #ifndef VTKMAPPER_H_HEADER_INCLUDED_C1C5453B #define VTKMAPPER_H_HEADER_INCLUDED_C1C5453B #include "mitkBaseRenderer.h" #include "mitkDataNode.h" -#include "mitkIShaderRepository.h" #include "mitkLocalStorageHandler.h" #include "mitkMapper.h" #include "mitkVtkPropRenderer.h" #include #include #include #include #include #include #include #include #include #include class vtkProp; class vtkProp3D; class vtkActor; namespace mitk { /** \brief Base class of all Vtk Mappers in order to display primitives * by exploiting Vtk functionality. * * Rendering of opaque, translucent or volumetric geometry and overlays * is done in consecutive render passes. * * \ingroup Mapper */ class MITKCORE_EXPORT VtkMapper : public Mapper { public: mitkClassMacro(VtkMapper, Mapper); virtual vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) = 0; /** \brief Re-issues all drawing commands required to describe * the entire scene each time a new frame is required, * regardless of actual changes. */ static void SetVtkMapperImmediateModeRendering(vtkMapper *mapper); /** * \brief Returns whether this is an vtk-based mapper * \deprecatedSince{2013_03} All mappers of superclass VTKMapper are vtk based, use a dynamic_cast instead */ DEPRECATED(virtual bool IsVtkBased() const override); /** \brief Determines which geometry should be rendered * (opaque, translucent, volumetric, overlay) * and calls the appropriate function. * * Called by mitk::VtkPropRenderer::Render */ void MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type) override; /** \brief Checks visibility and renders the overlay */ virtual void MitkRenderOverlay(BaseRenderer *renderer); /** \brief Checks visibility and renders untransparent geometry */ virtual void MitkRenderOpaqueGeometry(BaseRenderer *renderer); /** \brief Checks visiblity and renders transparent geometry */ virtual void MitkRenderTranslucentGeometry(BaseRenderer *renderer); /** \brief Checks visibility and renders volumes */ virtual void MitkRenderVolumetricGeometry(BaseRenderer *renderer); /** \brief Returns true if this mapper owns the specified vtkProp for * the given BaseRenderer. * * Note: returns false by default; should be implemented for VTK-based * Mapper subclasses. */ virtual bool HasVtkProp(const vtkProp *prop, BaseRenderer *renderer); /** \brief Set the vtkTransform of the m_Prop3D for * the current time step of \a renderer * * Called by mitk::VtkPropRenderer::Update before rendering. This * method will transform all actors (e.g. of an vtkAssembly) according * the geometry. * * \warning This method transforms only props which derive * from vtkProp3D. Make sure to use vtkAssembly, if you have * multiple props. vtkPropAssembly does not work, since it derives * from vtkProp. */ virtual void UpdateVtkTransform(mitk::BaseRenderer *renderer); /** * \brief Apply color and opacity properties read from the PropertyList * \deprecatedSince{2013_03} Use ApplyColorAndOpacityProperties(mitk::BaseRenderer* renderer, vtkActor * actor) * instead */ DEPRECATED(inline virtual void ApplyProperties(vtkActor *actor, mitk::BaseRenderer *renderer)) { ApplyColorAndOpacityProperties(renderer, actor); } /** - * \brief SHADERTODO + * \deprecatedSince{2017_08} */ - void ApplyShaderProperties(mitk::BaseRenderer *renderer); + DEPRECATED(void ApplyShaderProperties(mitk::BaseRenderer *)){} /** * \brief Apply color and opacity properties read from the PropertyList. * Called by mapper subclasses. */ virtual void ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor *actor) override; /** * \brief Release vtk-based graphics resources that are being consumed by this mapper. * * Method called by mitk::VtkPropRenderer. The parameter renderer could be used to * determine which graphic resources to release. The local storage is accessible * by the parameter renderer. Should be overwritten in subclasses. */ virtual void ReleaseGraphicsResources(mitk::BaseRenderer * /*renderer*/) {} class VtkMapperLocalStorage : public mitk::Mapper::BaseLocalStorage { public: - mitk::IShaderRepository::ShaderProgram::Pointer m_ShaderProgram; itk::TimeStamp m_ModifiedTimeStamp; VtkMapperLocalStorage() { - IShaderRepository *shaderRepo = CoreServices::GetShaderRepository(); - if (shaderRepo) - { - m_ShaderProgram = shaderRepo->CreateShaderProgram(); - } } ~VtkMapperLocalStorage() {} }; mitk::LocalStorageHandler m_VtkMapperLSH; protected: /** constructor */ VtkMapper(); /** virtual destructor in order to derive from this class */ virtual ~VtkMapper(); private: /** copy constructor */ VtkMapper(const VtkMapper &); /** assignment operator */ VtkMapper &operator=(const VtkMapper &); }; } // namespace mitk #endif /* VTKMAPPER_H_HEADER_INCLUDED_C1C5453B */ diff --git a/Modules/Core/include/vtkMitkLevelWindowFilter.h b/Modules/Core/include/vtkMitkLevelWindowFilter.h index d78365ad98..b9dffd22d7 100644 --- a/Modules/Core/include/vtkMitkLevelWindowFilter.h +++ b/Modules/Core/include/vtkMitkLevelWindowFilter.h @@ -1,102 +1,102 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __vtkMitkLevelWindowFilter_h #define __vtkMitkLevelWindowFilter_h class vtkScalarsToColors; class vtkPiecewiseFunction; #include #include #include /** Documentation * \brief Applies the grayvalue or color/opacity level window to scalar or RGB(A) images. * * This filter is used to apply the color level window to RGB images (e.g. * diffusion tensor images). Therefore, the RGB channels are converted to * the HSI color space, where the level window can be applied. Afterwards, * the HSI values transformed back to the RGB space. * * The filter is also able to apply an opacity level window to RGBA images. * * \ingroup Renderer */ class MITKCORE_EXPORT vtkMitkLevelWindowFilter : public vtkThreadedImageAlgorithm { public: vtkTypeMacro(vtkMitkLevelWindowFilter, vtkThreadedImageAlgorithm); static vtkMitkLevelWindowFilter *New(); - virtual unsigned long int GetMTime() override; + virtual vtkMTimeType GetMTime() override; /** \brief Get the lookup table for the RGB level window */ vtkScalarsToColors *GetLookupTable(); /** \brief Set the lookup table for the RGB level window */ void SetLookupTable(vtkScalarsToColors *lookupTable); /** \brief Get the piecewise function used to map scalar to alpha component value (only * used when the lookupTable is a vtkColorTransferFunction) */ vtkPiecewiseFunction *GetOpacityPiecewiseFunction() { return m_OpacityFunction; } /** \brief Set the piecewise function used to map scalar to alpha component value (only * used when the lookupTable is a vtkColorTransferFunction) */ void SetOpacityPiecewiseFunction(vtkPiecewiseFunction *opacityFunction); /** \brief Get/Set the lower window opacity for the alpha level window */ void SetMinOpacity(double minOpacity); inline double GetMinOpacity() const; /** \brief Get/Set the upper window opacity for the alpha level window */ void SetMaxOpacity(double maxOpacity); inline double GetMaxOpacity() const; /** \brief Set clipping bounds for the opaque part of the resliced 2d image */ void SetClippingBounds(double *); protected: /** Default constructor. */ vtkMitkLevelWindowFilter(); /** Default deconstructor. */ ~vtkMitkLevelWindowFilter(); /** \brief Method for threaded execution of the filter. * \param *inData: The input. * \param *outData: The output of the filter. * \param extent: Specifies the region of the image to be updated inside this thread. * It is a six-component array of the form (xmin, xmax, ymin, ymax, zmin, zmax). * \param id: The thread id. */ void ThreadedExecute(vtkImageData *inData, vtkImageData *outData, int extent[6], int id) override; // /** Standard VTK filter method to apply the filter. See VTK documentation.*/ int RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) override; // /** Standard VTK filter method to apply the filter. See VTK documentation. Not used at the moment.*/ // void ExecuteInformation(vtkImageData *vtkNotUsed(inData), vtkImageData *vtkNotUsed(outData)); private: /** m_LookupTable contains the lookup table for the RGB level window.*/ vtkScalarsToColors *m_LookupTable; /** The transfer function to map the scalar to alpha (4th component of the RGBA output value) */ vtkPiecewiseFunction *m_OpacityFunction; /** m_MinOpacity contains the lower bound for the alpha level window.*/ double m_MinOpacity; /** m_MaxOpacity contains the upper bound for the alpha level window.*/ double m_MaxOpacity; double m_ClippingBounds[4]; }; #endif diff --git a/Modules/Core/include/vtkNeverTranslucentTexture.h b/Modules/Core/include/vtkNeverTranslucentTexture.h index fcfc29addf..5a62b4aa58 100644 --- a/Modules/Core/include/vtkNeverTranslucentTexture.h +++ b/Modules/Core/include/vtkNeverTranslucentTexture.h @@ -1,102 +1,102 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkNeverTranslucentTexture_h #define mitkNeverTranslucentTexture_h #include #include #include /** \brief VTK Fix to speed up our image rendering. The way we render images while changing the contrast via level/window extremely slows down rendering. The cause of this slowdown is that VTK asks a texture (via a call to IsTranslucent) if it is translucent. When the texture refers to a lookup table this question is answered in a most expensive way: pushing every pixel through the lookup table to see whether it would render translucent. We can speed this up extremely by always answering NO. 2D Image rendering in the context of MITK is still correct. This class is injected into the VTK system by registering it with vtkObjectFactory as a replacement for vtkTexture. We chose vtkOpenGLTexture as super class, because it seems that the other texture super class is deprecated: http://www.cmake.org/Wiki/VTK:How_I_mangled_Mesa \sa ImageVtkMapper2D */ /* NOT exported, this is a 2D image mapper helper */ class MITKCORE_EXPORT vtkNeverTranslucentTexture : public vtkOpenGLTexture { public: static vtkNeverTranslucentTexture *New(); - vtkTypeMacro(vtkNeverTranslucentTexture, vtkTexture); + vtkTypeMacro(vtkNeverTranslucentTexture, vtkOpenGLTexture); void PrintSelf(ostream &os, vtkIndent indent) override; /** \brief The FIX (see class description). VTK Description: Is this Texture Translucent? Returns false (0) if the texture is either fully opaque or has only fully transparent pixels and fully opaque pixels and the Interpolate flag is turn off. */ virtual int IsTranslucent() override; protected: vtkNeverTranslucentTexture(); private: vtkNeverTranslucentTexture(const vtkNeverTranslucentTexture &); // Not implemented. void operator=(const vtkNeverTranslucentTexture &); // Not implemented. }; /** \brief Factory for vtkNeverTranslucentTexture (see this class!). Registered in CoreActivator to replace all instances of vtkTexture with vtkNeverTranslucentTexture. Required to make rendering of images during level/window operations acceptably fast. */ class vtkNeverTranslucentTextureFactory : public vtkObjectFactory { public: vtkNeverTranslucentTextureFactory(); static vtkNeverTranslucentTextureFactory *New(); virtual const char *GetVTKSourceVersion() override; const char *GetDescription() override; protected: vtkNeverTranslucentTextureFactory(const vtkNeverTranslucentTextureFactory &); void operator=(const vtkNeverTranslucentTextureFactory &); }; #endif diff --git a/Modules/Core/src/DataManagement/mitkShaderProperty.cpp b/Modules/Core/src/DataManagement/mitkShaderProperty.cpp deleted file mode 100644 index ac7782cc43..0000000000 --- a/Modules/Core/src/DataManagement/mitkShaderProperty.cpp +++ /dev/null @@ -1,118 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkShaderProperty.h" -#include - -#include "mitkCoreServices.h" -#include "mitkIShaderRepository.h" - -#include -#include - -mitk::ShaderProperty::ShaderProperty() -{ - AddShaderTypes(); - SetShader((IdType)0); -} - -mitk::ShaderProperty::ShaderProperty(const ShaderProperty &other) - : mitk::EnumerationProperty(other), shaderList(other.shaderList) -{ -} - -mitk::ShaderProperty::ShaderProperty(const IdType &value) -{ - AddShaderTypes(); - SetShader(value); -} - -mitk::ShaderProperty::ShaderProperty(const std::string &value) -{ - AddShaderTypes(); - SetShader(value); -} - -void mitk::ShaderProperty::SetShader(const IdType &value) -{ - if (IsValidEnumerationValue(value)) - SetValue(value); - else - SetValue((IdType)0); -} - -void mitk::ShaderProperty::SetShader(const std::string &value) -{ - if (IsValidEnumerationValue(value)) - SetValue(value); - else - SetValue((IdType)0); -} - -mitk::EnumerationProperty::IdType mitk::ShaderProperty::GetShaderId() -{ - return GetValueAsId(); -} - -std::string mitk::ShaderProperty::GetShaderName() -{ - return GetValueAsString(); -} - -void mitk::ShaderProperty::AddShaderTypes() -{ - AddEnum("fixed"); - - IShaderRepository *shaderRepo = CoreServices::GetShaderRepository(); - if (shaderRepo == nullptr) - return; - - std::list l = shaderRepo->GetShaders(); - std::list::const_iterator i = l.begin(); - - while (i != l.end()) - { - AddEnum((*i)->GetName()); - ++i; - } -} - -bool mitk::ShaderProperty::AddEnum(const std::string &name, const IdType & /*id*/) -{ - Element e; - - e.name = name; - - bool success = Superclass::AddEnum(e.name, (IdType)shaderList.size()); - - shaderList.push_back(e); - - return success; -} - -bool mitk::ShaderProperty::Assign(const BaseProperty &property) -{ - Superclass::Assign(property); - this->shaderList = static_cast(property).shaderList; - return true; -} - -itk::LightObject::Pointer mitk::ShaderProperty::InternalClone() const -{ - itk::LightObject::Pointer result(new Self(*this)); - result->UnRegister(); - return result; -} diff --git a/Modules/Core/src/Rendering/mitkBaseRenderer.cpp b/Modules/Core/src/Rendering/mitkBaseRenderer.cpp index 047df06e48..cde6d18e19 100644 --- a/Modules/Core/src/Rendering/mitkBaseRenderer.cpp +++ b/Modules/Core/src/Rendering/mitkBaseRenderer.cpp @@ -1,758 +1,787 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkBaseRenderer.h" #include "mitkMapper.h" #include "mitkResliceMethodProperty.h" // Geometries #include "mitkPlaneGeometry.h" #include "mitkSlicedGeometry3D.h" // Controllers #include "mitkCameraController.h" #include "mitkCameraRotationController.h" #include "mitkSliceNavigationController.h" #include "mitkVtkLayerController.h" #include "mitkInteractionConst.h" #include "mitkProperties.h" #include "mitkWeakPointerProperty.h" // VTK #include #include #include #include #include #include #include mitk::BaseRenderer::BaseRendererMapType mitk::BaseRenderer::baseRendererMap; mitk::BaseRenderer *mitk::BaseRenderer::GetInstance(vtkRenderWindow *renWin) { for (BaseRendererMapType::iterator mapit = baseRendererMap.begin(); mapit != baseRendererMap.end(); ++mapit) { if ((*mapit).first == renWin) return (*mapit).second; } return nullptr; } void mitk::BaseRenderer::AddInstance(vtkRenderWindow *renWin, BaseRenderer *baseRenderer) { if (renWin == nullptr || baseRenderer == nullptr) return; // ensure that no BaseRenderer is managed twice mitk::BaseRenderer::RemoveInstance(renWin); baseRendererMap.insert(BaseRendererMapType::value_type(renWin, baseRenderer)); } void mitk::BaseRenderer::RemoveInstance(vtkRenderWindow *renWin) { BaseRendererMapType::iterator mapit = baseRendererMap.find(renWin); if (mapit != baseRendererMap.end()) baseRendererMap.erase(mapit); } mitk::BaseRenderer *mitk::BaseRenderer::GetByName(const std::string &name) { for (BaseRendererMapType::iterator mapit = baseRendererMap.begin(); mapit != baseRendererMap.end(); ++mapit) { if ((*mapit).second->m_Name == name) return (*mapit).second; } return nullptr; } vtkRenderWindow *mitk::BaseRenderer::GetRenderWindowByName(const std::string &name) { for (BaseRendererMapType::iterator mapit = baseRendererMap.begin(); mapit != baseRendererMap.end(); ++mapit) { if ((*mapit).second->m_Name == name) return (*mapit).first; } return nullptr; } mitk::BaseRenderer::BaseRenderer(const char *name, vtkRenderWindow *renWin, mitk::RenderingManager *rm, RenderingMode::Type renderingMode) : m_RenderWindow(nullptr), m_VtkRenderer(nullptr), m_MapperID(defaultMapper), m_DataStorage(nullptr), m_RenderingManager(rm), m_LastUpdateTime(0), m_CameraController(nullptr), m_SliceNavigationController(nullptr), m_CameraRotationController(nullptr), m_WorldTimeGeometry(nullptr), m_CurrentWorldGeometry(nullptr), m_CurrentWorldPlaneGeometry(nullptr), m_Slice(0), m_TimeStep(), m_CurrentWorldPlaneGeometryUpdateTime(), m_TimeStepUpdateTime(), m_KeepDisplayedRegion(true), m_CurrentWorldPlaneGeometryData(nullptr), m_CurrentWorldPlaneGeometryNode(nullptr), m_CurrentWorldPlaneGeometryTransformTime(0), m_Name(name), m_EmptyWorldGeometry(true), m_NumberOfVisibleLODEnabledMappers(0) { m_Bounds[0] = 0; m_Bounds[1] = 0; m_Bounds[2] = 0; m_Bounds[3] = 0; m_Bounds[4] = 0; m_Bounds[5] = 0; if (name != nullptr) { m_Name = name; } else { m_Name = "unnamed renderer"; itkWarningMacro(<< "Created unnamed renderer. Bad for serialization. Please choose a name."); } if (renWin != nullptr) { m_RenderWindow = renWin; m_RenderWindow->Register(nullptr); } else { itkWarningMacro(<< "Created mitkBaseRenderer without vtkRenderWindow present."); } // instances.insert( this ); // adding this BaseRenderer to the List of all BaseRenderer m_BindDispatcherInteractor = new mitk::BindDispatcherInteractor(GetName()); WeakPointerProperty::Pointer rendererProp = WeakPointerProperty::New((itk::Object *)this); m_CurrentWorldPlaneGeometry = mitk::PlaneGeometry::New(); m_CurrentWorldPlaneGeometryData = mitk::PlaneGeometryData::New(); m_CurrentWorldPlaneGeometryData->SetPlaneGeometry(m_CurrentWorldPlaneGeometry); m_CurrentWorldPlaneGeometryNode = mitk::DataNode::New(); m_CurrentWorldPlaneGeometryNode->SetData(m_CurrentWorldPlaneGeometryData); m_CurrentWorldPlaneGeometryNode->GetPropertyList()->SetProperty("renderer", rendererProp); m_CurrentWorldPlaneGeometryNode->GetPropertyList()->SetProperty("layer", IntProperty::New(1000)); m_CurrentWorldPlaneGeometryNode->SetProperty("reslice.thickslices", mitk::ResliceMethodProperty::New()); m_CurrentWorldPlaneGeometryNode->SetProperty("reslice.thickslices.num", mitk::IntProperty::New(1)); m_CurrentWorldPlaneGeometryTransformTime = m_CurrentWorldPlaneGeometryNode->GetVtkTransform()->GetMTime(); mitk::SliceNavigationController::Pointer sliceNavigationController = mitk::SliceNavigationController::New(); sliceNavigationController->SetRenderer(this); sliceNavigationController->ConnectGeometrySliceEvent(this); sliceNavigationController->ConnectGeometryUpdateEvent(this); sliceNavigationController->ConnectGeometryTimeEvent(this, false); m_SliceNavigationController = sliceNavigationController; m_CameraRotationController = mitk::CameraRotationController::New(); m_CameraRotationController->SetRenderWindow(m_RenderWindow); m_CameraRotationController->AcquireCamera(); m_CameraController = mitk::CameraController::New(); m_CameraController->SetRenderer(this); m_VtkRenderer = vtkRenderer::New(); if (renderingMode == RenderingMode::DepthPeeling) { m_VtkRenderer->SetUseDepthPeeling(1); m_VtkRenderer->SetMaximumNumberOfPeels(8); m_VtkRenderer->SetOcclusionRatio(0.0); } if (mitk::VtkLayerController::GetInstance(m_RenderWindow) == nullptr) { mitk::VtkLayerController::AddInstance(m_RenderWindow, m_VtkRenderer); } mitk::VtkLayerController::GetInstance(m_RenderWindow)->InsertSceneRenderer(m_VtkRenderer); } mitk::BaseRenderer::~BaseRenderer() { if (m_VtkRenderer != nullptr) { m_VtkRenderer->Delete(); m_VtkRenderer = nullptr; } if (m_CameraController.IsNotNull()) m_CameraController->SetRenderer(nullptr); mitk::VtkLayerController::RemoveInstance(m_RenderWindow); RemoveAllLocalStorages(); m_DataStorage = nullptr; if (m_BindDispatcherInteractor != nullptr) { delete m_BindDispatcherInteractor; } if (m_RenderWindow != nullptr) { m_RenderWindow->Delete(); m_RenderWindow = nullptr; } } void mitk::BaseRenderer::RemoveAllLocalStorages() { this->InvokeEvent(mitk::BaseRenderer::RendererResetEvent()); std::list::iterator it; for (it = m_RegisteredLocalStorageHandlers.begin(); it != m_RegisteredLocalStorageHandlers.end(); ++it) (*it)->ClearLocalStorage(this, false); m_RegisteredLocalStorageHandlers.clear(); } void mitk::BaseRenderer::RegisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh) { m_RegisteredLocalStorageHandlers.push_back(lsh); } mitk::Dispatcher::Pointer mitk::BaseRenderer::GetDispatcher() const { return m_BindDispatcherInteractor->GetDispatcher(); } void mitk::BaseRenderer::UnregisterLocalStorageHandler(mitk::BaseLocalStorageHandler *lsh) { m_RegisteredLocalStorageHandlers.remove(lsh); } void mitk::BaseRenderer::SetDataStorage(DataStorage *storage) { if (storage != m_DataStorage && storage != nullptr) { m_DataStorage = storage; m_BindDispatcherInteractor->SetDataStorage(m_DataStorage); this->Modified(); } } const mitk::BaseRenderer::MapperSlotId mitk::BaseRenderer::defaultMapper = 1; void mitk::BaseRenderer::Paint() { } void mitk::BaseRenderer::Initialize() { } void mitk::BaseRenderer::Resize(int w, int h) { this->m_RenderWindow->SetSize(w, h); } void mitk::BaseRenderer::InitRenderer(vtkRenderWindow *renderwindow) { if (m_RenderWindow != renderwindow) { if (m_RenderWindow != nullptr) { m_RenderWindow->Delete(); } m_RenderWindow = renderwindow; if (m_RenderWindow != nullptr) { m_RenderWindow->Register(nullptr); } } RemoveAllLocalStorages(); if (m_CameraController.IsNotNull()) { m_CameraController->SetRenderer(this); } } void mitk::BaseRenderer::InitSize(int w, int h) { this->m_RenderWindow->SetSize(w, h); } void mitk::BaseRenderer::SetSlice(unsigned int slice) { if (m_Slice != slice) { m_Slice = slice; if (m_WorldTimeGeometry.IsNotNull()) { // get world geometry which may be rotated, for the current time step SlicedGeometry3D *slicedWorldGeometry = dynamic_cast(m_WorldTimeGeometry->GetGeometryForTimeStep(m_TimeStep).GetPointer()); if (slicedWorldGeometry != nullptr) { // if slice position is part of the world geometry... if (m_Slice >= slicedWorldGeometry->GetSlices()) // set the current worldplanegeomety as the selected 2D slice of the world geometry m_Slice = slicedWorldGeometry->GetSlices() - 1; SetCurrentWorldPlaneGeometry(slicedWorldGeometry->GetPlaneGeometry(m_Slice)); SetCurrentWorldGeometry(slicedWorldGeometry); } } else Modified(); } } void mitk::BaseRenderer::SetTimeStep(unsigned int timeStep) { if (m_TimeStep != timeStep) { m_TimeStep = timeStep; m_TimeStepUpdateTime.Modified(); if (m_WorldTimeGeometry.IsNotNull()) { if (m_TimeStep >= m_WorldTimeGeometry->CountTimeSteps()) m_TimeStep = m_WorldTimeGeometry->CountTimeSteps() - 1; SlicedGeometry3D *slicedWorldGeometry = dynamic_cast(m_WorldTimeGeometry->GetGeometryForTimeStep(m_TimeStep).GetPointer()); if (slicedWorldGeometry != nullptr) { SetCurrentWorldPlaneGeometry(slicedWorldGeometry->GetPlaneGeometry(m_Slice)); SetCurrentWorldGeometry(slicedWorldGeometry); } } else Modified(); } } int mitk::BaseRenderer::GetTimeStep(const mitk::BaseData *data) const { if ((data == nullptr) || (data->IsInitialized() == false)) { return -1; } return data->GetTimeGeometry()->TimePointToTimeStep(GetTime()); } mitk::ScalarType mitk::BaseRenderer::GetTime() const { if (m_WorldTimeGeometry.IsNull()) { return 0; } else { ScalarType timeInMS = m_WorldTimeGeometry->TimeStepToTimePoint(GetTimeStep()); if (timeInMS == itk::NumericTraits::NonpositiveMin()) return 0; else return timeInMS; } } void mitk::BaseRenderer::SetWorldTimeGeometry(mitk::TimeGeometry *geometry) { assert(geometry != nullptr); itkDebugMacro("setting WorldTimeGeometry to " << geometry); if (m_WorldTimeGeometry != geometry) { if (geometry->GetBoundingBoxInWorld()->GetDiagonalLength2() == 0) return; m_WorldTimeGeometry = geometry; itkDebugMacro("setting WorldTimeGeometry to " << m_WorldTimeGeometry); if (m_TimeStep >= m_WorldTimeGeometry->CountTimeSteps()) m_TimeStep = m_WorldTimeGeometry->CountTimeSteps() - 1; BaseGeometry *geometry3d; geometry3d = m_WorldTimeGeometry->GetGeometryForTimeStep(m_TimeStep); SetWorldGeometry3D(geometry3d); } } void mitk::BaseRenderer::SetWorldGeometry3D(mitk::BaseGeometry *geometry) { itkDebugMacro("setting WorldGeometry3D to " << geometry); if (geometry->GetBoundingBox()->GetDiagonalLength2() == 0) return; SlicedGeometry3D *slicedWorldGeometry; slicedWorldGeometry = dynamic_cast(geometry); PlaneGeometry::Pointer geometry2d; if (slicedWorldGeometry != nullptr) { if (m_Slice >= slicedWorldGeometry->GetSlices() && (m_Slice != 0)) m_Slice = slicedWorldGeometry->GetSlices() - 1; geometry2d = slicedWorldGeometry->GetPlaneGeometry(m_Slice); if (geometry2d.IsNull()) { PlaneGeometry::Pointer plane = mitk::PlaneGeometry::New(); plane->InitializeStandardPlane(slicedWorldGeometry); geometry2d = plane; } SetCurrentWorldGeometry(slicedWorldGeometry); } else { geometry2d = dynamic_cast(geometry); if (geometry2d.IsNull()) { PlaneGeometry::Pointer plane = PlaneGeometry::New(); plane->InitializeStandardPlane(geometry); geometry2d = plane; } SetCurrentWorldGeometry(geometry); } SetCurrentWorldPlaneGeometry(geometry2d); // calls Modified() if (m_CurrentWorldPlaneGeometry.IsNull()) itkWarningMacro("m_CurrentWorldPlaneGeometry is nullptr"); } void mitk::BaseRenderer::SetCurrentWorldPlaneGeometry(mitk::PlaneGeometry *geometry2d) { if (m_CurrentWorldPlaneGeometry != geometry2d) { m_CurrentWorldPlaneGeometry = geometry2d; m_CurrentWorldPlaneGeometryData->SetPlaneGeometry(m_CurrentWorldPlaneGeometry); m_CurrentWorldPlaneGeometryUpdateTime.Modified(); Modified(); } } void mitk::BaseRenderer::SendUpdateSlice() { m_CurrentWorldPlaneGeometryUpdateTime.Modified(); } int *mitk::BaseRenderer::GetSize() const { return this->m_RenderWindow->GetSize(); } int *mitk::BaseRenderer::GetViewportSize() const { return this->m_VtkRenderer->GetSize(); } void mitk::BaseRenderer::SetCurrentWorldGeometry(mitk::BaseGeometry *geometry) { m_CurrentWorldGeometry = geometry; if (geometry == nullptr) { m_Bounds[0] = 0; m_Bounds[1] = 0; m_Bounds[2] = 0; m_Bounds[3] = 0; m_Bounds[4] = 0; m_Bounds[5] = 0; m_EmptyWorldGeometry = true; return; } BoundingBox::Pointer boundingBox = m_CurrentWorldGeometry->CalculateBoundingBoxRelativeToTransform(nullptr); const BoundingBox::BoundsArrayType &worldBounds = boundingBox->GetBounds(); m_Bounds[0] = worldBounds[0]; m_Bounds[1] = worldBounds[1]; m_Bounds[2] = worldBounds[2]; m_Bounds[3] = worldBounds[3]; m_Bounds[4] = worldBounds[4]; m_Bounds[5] = worldBounds[5]; if (boundingBox->GetDiagonalLength2() <= mitk::eps) m_EmptyWorldGeometry = true; else m_EmptyWorldGeometry = false; } void mitk::BaseRenderer::SetGeometry(const itk::EventObject &geometrySendEvent) { const SliceNavigationController::GeometrySendEvent *sendEvent = dynamic_cast(&geometrySendEvent); assert(sendEvent != nullptr); SetWorldTimeGeometry(sendEvent->GetTimeGeometry()); } void mitk::BaseRenderer::UpdateGeometry(const itk::EventObject &geometryUpdateEvent) { const SliceNavigationController::GeometryUpdateEvent *updateEvent = dynamic_cast(&geometryUpdateEvent); if (updateEvent == nullptr) return; if (m_CurrentWorldGeometry.IsNotNull()) { SlicedGeometry3D *slicedWorldGeometry = dynamic_cast(m_CurrentWorldGeometry.GetPointer()); if (slicedWorldGeometry) { PlaneGeometry *geometry2D = slicedWorldGeometry->GetPlaneGeometry(m_Slice); SetCurrentWorldPlaneGeometry(geometry2D); // calls Modified() } } } void mitk::BaseRenderer::SetGeometrySlice(const itk::EventObject &geometrySliceEvent) { const SliceNavigationController::GeometrySliceEvent *sliceEvent = dynamic_cast(&geometrySliceEvent); assert(sliceEvent != nullptr); SetSlice(sliceEvent->GetPos()); } void mitk::BaseRenderer::SetGeometryTime(const itk::EventObject &geometryTimeEvent) { const SliceNavigationController::GeometryTimeEvent *timeEvent = dynamic_cast(&geometryTimeEvent); assert(timeEvent != nullptr); SetTimeStep(timeEvent->GetPos()); } const double *mitk::BaseRenderer::GetBounds() const { return m_Bounds; } void mitk::BaseRenderer::DrawOverlayMouse(mitk::Point2D &itkNotUsed(p2d)) { MITK_INFO << "BaseRenderer::DrawOverlayMouse()- should be inconcret implementation OpenGLRenderer." << std::endl; } void mitk::BaseRenderer::RequestUpdate() { SetConstrainZoomingAndPanning(true); m_RenderingManager->RequestUpdate(this->m_RenderWindow); } void mitk::BaseRenderer::ForceImmediateUpdate() { m_RenderingManager->ForceImmediateUpdate(this->m_RenderWindow); } unsigned int mitk::BaseRenderer::GetNumberOfVisibleLODEnabledMappers() const { return m_NumberOfVisibleLODEnabledMappers; } mitk::RenderingManager *mitk::BaseRenderer::GetRenderingManager() const { return m_RenderingManager.GetPointer(); } /*! Sets the new Navigation controller */ void mitk::BaseRenderer::SetSliceNavigationController(mitk::SliceNavigationController *SlicenavigationController) { if (SlicenavigationController == nullptr) return; // copy worldgeometry SlicenavigationController->SetInputWorldTimeGeometry(SlicenavigationController->GetCreatedWorldGeometry()); SlicenavigationController->Update(); // set new m_SliceNavigationController = SlicenavigationController; m_SliceNavigationController->SetRenderer(this); if (m_SliceNavigationController.IsNotNull()) { m_SliceNavigationController->ConnectGeometrySliceEvent(this); m_SliceNavigationController->ConnectGeometryUpdateEvent(this); m_SliceNavigationController->ConnectGeometryTimeEvent(this, false); } } void mitk::BaseRenderer::DisplayToWorld(const Point2D &displayPoint, Point3D &worldIndex) const { if (m_MapperID == BaseRenderer::Standard2D) { double display[3], *world; // For the rigth z-position in display coordinates, take the focal point, convert it to display and use it for // correct depth. double *displayCoord; double cameraFP[4]; // Get camera focal point and position. Convert to display (screen) // coordinates. We need a depth value for z-buffer. this->GetVtkRenderer()->GetActiveCamera()->GetFocalPoint(cameraFP); cameraFP[3] = 0.0; this->GetVtkRenderer()->SetWorldPoint(cameraFP[0], cameraFP[1], cameraFP[2], cameraFP[3]); this->GetVtkRenderer()->WorldToDisplay(); displayCoord = this->GetVtkRenderer()->GetDisplayPoint(); // now convert the display point to world coordinates display[0] = displayPoint[0]; display[1] = displayPoint[1]; display[2] = displayCoord[2]; this->GetVtkRenderer()->SetDisplayPoint(display); this->GetVtkRenderer()->DisplayToWorld(); world = this->GetVtkRenderer()->GetWorldPoint(); for (int i = 0; i < 3; i++) { worldIndex[i] = world[i] / world[3]; } } else if (m_MapperID == BaseRenderer::Standard3D) { PickWorldPoint( displayPoint, worldIndex); // Seems to be the same code as above, but subclasses may contain different implementations. } return; } void mitk::BaseRenderer::DisplayToPlane(const Point2D &displayPoint, Point2D &planePointInMM) const { if (m_MapperID == BaseRenderer::Standard2D) { Point3D worldPoint; this->DisplayToWorld(displayPoint, worldPoint); this->m_CurrentWorldPlaneGeometry->Map(worldPoint, planePointInMM); } else if (m_MapperID == BaseRenderer::Standard3D) { MITK_WARN << "No conversion possible with 3D mapper."; return; } return; } void mitk::BaseRenderer::WorldToDisplay(const Point3D &worldIndex, Point2D &displayPoint) const { double world[4], *display; world[0] = worldIndex[0]; world[1] = worldIndex[1]; world[2] = worldIndex[2]; world[3] = 1.0; this->GetVtkRenderer()->SetWorldPoint(world); this->GetVtkRenderer()->WorldToDisplay(); display = this->GetVtkRenderer()->GetDisplayPoint(); displayPoint[0] = display[0]; displayPoint[1] = display[1]; return; } +void mitk::BaseRenderer::WorldToView(const mitk::Point3D &worldIndex, mitk::Point2D &viewPoint) const +{ + double world[4], *view; + + world[0] = worldIndex[0]; + world[1] = worldIndex[1]; + world[2] = worldIndex[2]; + world[3] = 1.0; + + this->GetVtkRenderer()->SetWorldPoint(world); + this->GetVtkRenderer()->WorldToView(); + view = this->GetVtkRenderer()->GetViewPoint(); + this->GetVtkRenderer()->ViewToNormalizedViewport(view[0], view[1], view[2]); + + viewPoint[0] = view[0] * this->GetViewportSize()[0]; + viewPoint[1] = view[1] * this->GetViewportSize()[1]; + + return; +} + void mitk::BaseRenderer::PlaneToDisplay(const Point2D &planePointInMM, Point2D &displayPoint) const { Point3D worldPoint; this->m_CurrentWorldPlaneGeometry->Map(planePointInMM, worldPoint); this->WorldToDisplay(worldPoint, displayPoint); return; } +void mitk::BaseRenderer::PlaneToView(const Point2D &planePointInMM, Point2D &viewPoint) const +{ + Point3D worldPoint; + this->m_CurrentWorldPlaneGeometry->Map(planePointInMM, worldPoint); + this->WorldToView(worldPoint,viewPoint); + + return; +} + double mitk::BaseRenderer::GetScaleFactorMMPerDisplayUnit() const { if (this->GetMapperID() == BaseRenderer::Standard2D) { // GetParallelScale returns half of the height of the render window in mm. // Divided by the half size of the Display size in pixel givest the mm per pixel. return this->GetVtkRenderer()->GetActiveCamera()->GetParallelScale() * 2.0 / GetViewportSize()[1]; } else return 1.0; } mitk::Point2D mitk::BaseRenderer::GetDisplaySizeInMM() const { Point2D dispSizeInMM; dispSizeInMM[0] = GetSizeX() * GetScaleFactorMMPerDisplayUnit(); dispSizeInMM[1] = GetSizeY() * GetScaleFactorMMPerDisplayUnit(); return dispSizeInMM; } mitk::Point2D mitk::BaseRenderer::GetViewportSizeInMM() const { Point2D dispSizeInMM; dispSizeInMM[0] = GetViewportSize()[0] * GetScaleFactorMMPerDisplayUnit(); dispSizeInMM[1] = GetViewportSize()[1] * GetScaleFactorMMPerDisplayUnit(); return dispSizeInMM; } mitk::Point2D mitk::BaseRenderer::GetOriginInMM() const { Point2D originPx; originPx[0] = m_VtkRenderer->GetOrigin()[0]; originPx[1] = m_VtkRenderer->GetOrigin()[1]; Point2D displayGeometryOriginInMM; DisplayToPlane(originPx, displayGeometryOriginInMM); // top left of the render window (Origin) return displayGeometryOriginInMM; } void mitk::BaseRenderer::SetConstrainZoomingAndPanning(bool constrain) { m_ConstrainZoomingAndPanning = constrain; if (m_ConstrainZoomingAndPanning) { this->GetCameraController()->AdjustCameraToPlane(); } } mitk::Point3D mitk::BaseRenderer::Map2DRendererPositionTo3DWorldPosition(const Point2D &mousePosition) const { // DEPRECATED: Map2DRendererPositionTo3DWorldPosition is deprecated. use DisplayToWorldInstead Point3D position; DisplayToWorld(mousePosition, position); return position; } void mitk::BaseRenderer::PrintSelf(std::ostream &os, itk::Indent indent) const { os << indent << " MapperID: " << m_MapperID << std::endl; os << indent << " Slice: " << m_Slice << std::endl; os << indent << " TimeStep: " << m_TimeStep << std::endl; os << indent << " CurrentWorldPlaneGeometry: "; if (m_CurrentWorldPlaneGeometry.IsNull()) os << "nullptr" << std::endl; else m_CurrentWorldPlaneGeometry->Print(os, indent); os << indent << " CurrentWorldPlaneGeometryUpdateTime: " << m_CurrentWorldPlaneGeometryUpdateTime << std::endl; os << indent << " CurrentWorldPlaneGeometryTransformTime: " << m_CurrentWorldPlaneGeometryTransformTime << std::endl; Superclass::PrintSelf(os, indent); } diff --git a/Modules/Core/src/Rendering/mitkIShaderRepository.cpp b/Modules/Core/src/Rendering/mitkIShaderRepository.cpp deleted file mode 100644 index 7e9e8b92ff..0000000000 --- a/Modules/Core/src/Rendering/mitkIShaderRepository.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkIShaderRepository.h" - -namespace mitk -{ - IShaderRepository::~IShaderRepository() {} - struct IShaderRepository::ShaderPrivate - { - ShaderPrivate() : id(-1) {} - int id; - std::string name; - std::string materialXml; - }; - - IShaderRepository::Shader::Shader() : d(new ShaderPrivate) {} - void IShaderRepository::Shader::SetId(int id) { d->id = id; } - IShaderRepository::Shader::~Shader() { delete d; } - int IShaderRepository::Shader::GetId() const { return d->id; } - std::string IShaderRepository::Shader::GetName() const { return d->name; } - std::string IShaderRepository::Shader::GetMaterialXml() const { return d->materialXml; } - void IShaderRepository::Shader::SetName(const std::string &name) { d->name = name; } - void IShaderRepository::Shader::SetMaterialXml(const std::string &xml) { d->materialXml = xml; } -} diff --git a/Modules/Core/src/Rendering/mitkPlaneGeometryDataVtkMapper3D.cpp b/Modules/Core/src/Rendering/mitkPlaneGeometryDataVtkMapper3D.cpp index 0e5a82b349..ac25920ae4 100644 --- a/Modules/Core/src/Rendering/mitkPlaneGeometryDataVtkMapper3D.cpp +++ b/Modules/Core/src/Rendering/mitkPlaneGeometryDataVtkMapper3D.cpp @@ -1,589 +1,589 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPlaneGeometryDataVtkMapper3D.h" #include "mitkImageVtkMapper2D.h" #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateOr.h" #include "mitkSmartPointerProperty.h" #include "mitkSurface.h" #include "mitkVtkRepresentationProperty.h" #include "mitkWeakPointerProperty.h" #include "vtkMitkLevelWindowFilter.h" #include "vtkNeverTranslucentTexture.h" #include #include #include #include #include #include #include #include #include #include #include #include namespace mitk { PlaneGeometryDataVtkMapper3D::PlaneGeometryDataVtkMapper3D() : m_NormalsActorAdded(false), m_DataStorage(nullptr) { m_EdgeTuber = vtkTubeFilter::New(); m_EdgeMapper = vtkPolyDataMapper::New(); m_SurfaceCreator = PlaneGeometryDataToSurfaceFilter::New(); m_SurfaceCreatorBoundingBox = BoundingBox::New(); m_SurfaceCreatorPointsContainer = BoundingBox::PointsContainer::New(); m_Edges = vtkFeatureEdges::New(); m_Edges->BoundaryEdgesOn(); m_Edges->FeatureEdgesOff(); m_Edges->NonManifoldEdgesOff(); m_Edges->ManifoldEdgesOff(); m_EdgeTransformer = vtkTransformPolyDataFilter::New(); m_NormalsTransformer = vtkTransformPolyDataFilter::New(); m_EdgeActor = vtkActor::New(); m_BackgroundMapper = vtkPolyDataMapper::New(); m_BackgroundActor = vtkActor::New(); m_Prop3DAssembly = vtkAssembly::New(); m_ImageAssembly = vtkAssembly::New(); m_SurfaceCreatorBoundingBox->SetPoints(m_SurfaceCreatorPointsContainer); m_Cleaner = vtkCleanPolyData::New(); m_Cleaner->PieceInvariantOn(); m_Cleaner->ConvertLinesToPointsOn(); m_Cleaner->ConvertPolysToLinesOn(); m_Cleaner->ConvertStripsToPolysOn(); m_Cleaner->PointMergingOn(); // Make sure that the FeatureEdge algorithm is initialized with a "valid" // (though empty) input vtkPolyData *emptyPolyData = vtkPolyData::New(); m_Cleaner->SetInputData(emptyPolyData); emptyPolyData->Delete(); m_Edges->SetInputConnection(m_Cleaner->GetOutputPort()); m_EdgeTransformer->SetInputConnection(m_Edges->GetOutputPort()); m_EdgeTuber->SetInputConnection(m_EdgeTransformer->GetOutputPort()); m_EdgeTuber->SetVaryRadiusToVaryRadiusOff(); m_EdgeTuber->SetNumberOfSides(12); m_EdgeTuber->CappingOn(); m_EdgeMapper->SetInputConnection(m_EdgeTuber->GetOutputPort()); m_EdgeMapper->ScalarVisibilityOff(); m_BackgroundMapper->SetInputData(emptyPolyData); m_BackgroundMapper->Update(); m_EdgeActor->SetMapper(m_EdgeMapper); m_BackgroundActor->GetProperty()->SetAmbient(0.5); m_BackgroundActor->GetProperty()->SetColor(0.0, 0.0, 0.0); m_BackgroundActor->GetProperty()->SetOpacity(0.0); m_BackgroundActor->SetMapper(m_BackgroundMapper); vtkProperty *backfaceProperty = m_BackgroundActor->MakeProperty(); backfaceProperty->SetColor(0.0, 0.0, 0.0); m_BackgroundActor->SetBackfaceProperty(backfaceProperty); backfaceProperty->Delete(); m_FrontHedgeHog = vtkHedgeHog::New(); m_BackHedgeHog = vtkHedgeHog::New(); m_FrontNormalsMapper = vtkPolyDataMapper::New(); m_FrontNormalsMapper->SetInputConnection(m_FrontHedgeHog->GetOutputPort()); m_BackNormalsMapper = vtkPolyDataMapper::New(); m_Prop3DAssembly->AddPart(m_EdgeActor); m_Prop3DAssembly->AddPart(m_ImageAssembly); m_FrontNormalsActor = vtkActor::New(); m_FrontNormalsActor->SetMapper(m_FrontNormalsMapper); m_BackNormalsActor = vtkActor::New(); m_BackNormalsActor->SetMapper(m_BackNormalsMapper); m_ImageMapperDeletedCommand = MemberCommandType::New(); m_ImageMapperDeletedCommand->SetCallbackFunction(this, &PlaneGeometryDataVtkMapper3D::ImageMapperDeletedCallback); } PlaneGeometryDataVtkMapper3D::~PlaneGeometryDataVtkMapper3D() { m_ImageAssembly->Delete(); m_Prop3DAssembly->Delete(); m_EdgeTuber->Delete(); m_EdgeMapper->Delete(); m_EdgeTransformer->Delete(); m_Cleaner->Delete(); m_Edges->Delete(); m_NormalsTransformer->Delete(); m_EdgeActor->Delete(); m_BackgroundMapper->Delete(); m_BackgroundActor->Delete(); m_FrontNormalsMapper->Delete(); m_FrontNormalsActor->Delete(); m_FrontHedgeHog->Delete(); m_BackNormalsMapper->Delete(); m_BackNormalsActor->Delete(); m_BackHedgeHog->Delete(); for (ActorList::iterator it = m_ImageActors.begin(); it != m_ImageActors.end(); ++it) it->second.m_Actor->ReleaseGraphicsResources(0); // Delete entries in m_ImageActors list one by one m_ImageActors.clear(); m_DataStorage = nullptr; } vtkProp *PlaneGeometryDataVtkMapper3D::GetVtkProp(mitk::BaseRenderer * /*renderer*/) { if ((this->GetDataNode() != nullptr) && (m_ImageAssembly != nullptr)) { // Do not transform the entire Prop3D assembly, but only the image part // here. The colored frame is transformed elsewhere (via m_EdgeTransformer), // since only vertices should be transformed there, not the poly data // itself, to avoid distortion for anisotropic datasets. m_ImageAssembly->SetUserTransform(this->GetDataNode()->GetVtkTransform()); } return m_Prop3DAssembly; } void PlaneGeometryDataVtkMapper3D::UpdateVtkTransform(mitk::BaseRenderer * /*renderer*/) { m_ImageAssembly->SetUserTransform(this->GetDataNode()->GetVtkTransform(this->GetTimestep())); } const PlaneGeometryData *PlaneGeometryDataVtkMapper3D::GetInput() { return static_cast(GetDataNode()->GetData()); } void PlaneGeometryDataVtkMapper3D::SetDataStorageForTexture(mitk::DataStorage *storage) { if (storage != nullptr && m_DataStorage != storage) { m_DataStorage = storage; this->Modified(); } } void PlaneGeometryDataVtkMapper3D::ImageMapperDeletedCallback(itk::Object *caller, const itk::EventObject & /*event*/) { ImageVtkMapper2D *imageMapper = dynamic_cast(caller); if ((imageMapper != nullptr)) { if (m_ImageActors.count(imageMapper) > 0) { m_ImageActors[imageMapper].m_Sender = nullptr; // sender is already destroying itself m_ImageActors.erase(imageMapper); } } } void PlaneGeometryDataVtkMapper3D::GenerateDataForRenderer(BaseRenderer *renderer) { SetVtkMapperImmediateModeRendering(m_EdgeMapper); SetVtkMapperImmediateModeRendering(m_BackgroundMapper); // Remove all actors from the assembly, and re-initialize it with the // edge actor m_ImageAssembly->GetParts()->RemoveAllItems(); bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) { // visibility has explicitly to be set in the single actors // due to problems when using cell picking: // even if the assembly is invisible, the renderer contains // references to the assemblies parts. During picking the // visibility of each part is checked, and not only for the // whole assembly. m_ImageAssembly->VisibilityOff(); m_EdgeActor->VisibilityOff(); return; } // visibility has explicitly to be set in the single actors // due to problems when using cell picking: // even if the assembly is invisible, the renderer contains // references to the assemblies parts. During picking the // visibility of each part is checked, and not only for the // whole assembly. m_ImageAssembly->VisibilityOn(); bool drawEdges = true; this->GetDataNode()->GetBoolProperty("draw edges", drawEdges, renderer); m_EdgeActor->SetVisibility(drawEdges); PlaneGeometryData::Pointer input = const_cast(this->GetInput()); if (input.IsNotNull() && (input->GetPlaneGeometry() != nullptr)) { SmartPointerProperty::Pointer surfacecreatorprop; surfacecreatorprop = dynamic_cast(GetDataNode()->GetProperty("surfacegeometry", renderer)); if ((surfacecreatorprop.IsNull()) || (surfacecreatorprop->GetSmartPointer().IsNull()) || ((m_SurfaceCreator = dynamic_cast(surfacecreatorprop->GetSmartPointer().GetPointer())) .IsNull())) { m_SurfaceCreator->PlaceByGeometryOn(); surfacecreatorprop = SmartPointerProperty::New(m_SurfaceCreator); GetDataNode()->SetProperty("surfacegeometry", surfacecreatorprop); } m_SurfaceCreator->SetInput(input); int res; if (GetDataNode()->GetIntProperty("xresolution", res, renderer)) { m_SurfaceCreator->SetXResolution(res); } if (GetDataNode()->GetIntProperty("yresolution", res, renderer)) { m_SurfaceCreator->SetYResolution(res); } double tubeRadius = 1.0; // Radius of tubular edge surrounding plane // Clip the PlaneGeometry with the reference geometry bounds (if available) if (input->GetPlaneGeometry()->HasReferenceGeometry()) { const BaseGeometry *referenceGeometry = input->GetPlaneGeometry()->GetReferenceGeometry(); BoundingBox::PointType boundingBoxMin, boundingBoxMax; boundingBoxMin = referenceGeometry->GetBoundingBox()->GetMinimum(); boundingBoxMax = referenceGeometry->GetBoundingBox()->GetMaximum(); if (referenceGeometry->GetImageGeometry()) { for (unsigned int i = 0; i < 3; ++i) { boundingBoxMin[i] -= 0.5; boundingBoxMax[i] -= 0.5; } } m_SurfaceCreatorPointsContainer->CreateElementAt(0) = boundingBoxMin; m_SurfaceCreatorPointsContainer->CreateElementAt(1) = boundingBoxMax; m_SurfaceCreatorBoundingBox->ComputeBoundingBox(); m_SurfaceCreator->SetBoundingBox(m_SurfaceCreatorBoundingBox); tubeRadius = referenceGeometry->GetDiagonalLength() / 450.0; } // If no reference geometry is available, clip with the current global // bounds else if (m_DataStorage.IsNotNull()) { m_SurfaceCreator->SetBoundingBox(m_DataStorage->ComputeVisibleBoundingBox(nullptr, "includeInBoundingBox")); tubeRadius = sqrt(m_SurfaceCreator->GetBoundingBox()->GetDiagonalLength2()) / 450.0; } // Calculate the surface of the PlaneGeometry m_SurfaceCreator->Update(); Surface *surface = m_SurfaceCreator->GetOutput(); // Check if there's something to display, otherwise return if ((surface->GetVtkPolyData() == 0) || (surface->GetVtkPolyData()->GetNumberOfCells() == 0)) { m_ImageAssembly->VisibilityOff(); return; } // add a graphical representation of the surface normals if requested DataNode *node = this->GetDataNode(); bool displayNormals = false; bool colorTwoSides = false; bool invertNormals = false; node->GetBoolProperty("draw normals 3D", displayNormals, renderer); node->GetBoolProperty("color two sides", colorTwoSides, renderer); node->GetBoolProperty("invert normals", invertNormals, renderer); // if we want to draw the display normals or render two sides we have to get the colors if (displayNormals || colorTwoSides) { // get colors float frontColor[3] = {0.0, 0.0, 1.0}; node->GetColor(frontColor, renderer, "front color"); float backColor[3] = {1.0, 0.0, 0.0}; node->GetColor(backColor, renderer, "back color"); if (displayNormals) { m_NormalsTransformer->SetInputData(surface->GetVtkPolyData()); m_NormalsTransformer->SetTransform(node->GetVtkTransform(this->GetTimestep())); m_FrontHedgeHog->SetInputConnection(m_NormalsTransformer->GetOutputPort()); m_FrontHedgeHog->SetVectorModeToUseNormal(); m_FrontHedgeHog->SetScaleFactor(invertNormals ? 1.0 : -1.0); m_FrontHedgeHog->Update(); m_FrontNormalsActor->GetProperty()->SetColor(frontColor[0], frontColor[1], frontColor[2]); m_BackHedgeHog->SetInputConnection(m_NormalsTransformer->GetOutputPort()); m_BackHedgeHog->SetVectorModeToUseNormal(); m_BackHedgeHog->SetScaleFactor(invertNormals ? -1.0 : 1.0); m_BackHedgeHog->Update(); m_BackNormalsActor->GetProperty()->SetColor(backColor[0], backColor[1], backColor[2]); // if there is no actor added yet, add one if (!m_NormalsActorAdded) { m_Prop3DAssembly->AddPart(m_FrontNormalsActor); m_Prop3DAssembly->AddPart(m_BackNormalsActor); m_NormalsActorAdded = true; } } // if we don't want to display normals AND there is an actor added remove the actor else if (m_NormalsActorAdded) { m_Prop3DAssembly->RemovePart(m_FrontNormalsActor); m_Prop3DAssembly->RemovePart(m_BackNormalsActor); m_NormalsActorAdded = false; } if (colorTwoSides) { if (!invertNormals) { m_BackgroundActor->GetProperty()->SetColor(backColor[0], backColor[1], backColor[2]); m_BackgroundActor->GetBackfaceProperty()->SetColor(frontColor[0], frontColor[1], frontColor[2]); } else { m_BackgroundActor->GetProperty()->SetColor(frontColor[0], frontColor[1], frontColor[2]); m_BackgroundActor->GetBackfaceProperty()->SetColor(backColor[0], backColor[1], backColor[2]); } } } // Add black background for all images (which may be transparent) m_BackgroundMapper->SetInputData(surface->GetVtkPolyData()); - m_ImageAssembly->AddPart(m_BackgroundActor); + // m_ImageAssembly->AddPart(m_BackgroundActor); LayerSortedActorList layerSortedActors; // Traverse the data tree to find nodes resliced by ImageMapperGL2D // use a predicate to get all data nodes which are "images" or inherit from mitk::Image mitk::TNodePredicateDataType::Pointer predicateAllImages = mitk::TNodePredicateDataType::New(); mitk::DataStorage::SetOfObjects::ConstPointer all = m_DataStorage->GetSubset(predicateAllImages); // process all found images for (mitk::DataStorage::SetOfObjects::ConstIterator it = all->Begin(); it != all->End(); ++it) { DataNode *node = it->Value(); if (node != nullptr) this->ProcessNode(node, renderer, surface, layerSortedActors); } // Add all image actors to the assembly, sorted according to // layer property LayerSortedActorList::iterator actorIt; for (actorIt = layerSortedActors.begin(); actorIt != layerSortedActors.end(); ++actorIt) { m_ImageAssembly->AddPart(actorIt->second); } // Configurate the tube-shaped frame: size according to the surface // bounds, color as specified in the plane's properties vtkPolyData *surfacePolyData = surface->GetVtkPolyData(); m_Cleaner->SetInputData(surfacePolyData); m_EdgeTransformer->SetTransform(this->GetDataNode()->GetVtkTransform(this->GetTimestep())); // Adjust the radius according to extent m_EdgeTuber->SetRadius(tubeRadius); // Get the plane's color and set the tube properties accordingly ColorProperty::Pointer colorProperty; colorProperty = dynamic_cast(this->GetDataNode()->GetProperty("color")); if (colorProperty.IsNotNull()) { const Color &color = colorProperty->GetColor(); m_EdgeActor->GetProperty()->SetColor(color.GetRed(), color.GetGreen(), color.GetBlue()); } else { m_EdgeActor->GetProperty()->SetColor(1.0, 1.0, 1.0); } m_ImageAssembly->SetUserTransform(this->GetDataNode()->GetVtkTransform(this->GetTimestep())); } VtkRepresentationProperty *representationProperty; this->GetDataNode()->GetProperty(representationProperty, "material.representation", renderer); if (representationProperty != nullptr) m_BackgroundActor->GetProperty()->SetRepresentation(representationProperty->GetVtkRepresentation()); } void PlaneGeometryDataVtkMapper3D::ProcessNode(DataNode *node, BaseRenderer *renderer, Surface *surface, LayerSortedActorList &layerSortedActors) { if (node != nullptr) { // we need to get the information from the 2D mapper to render the texture on the 3D plane ImageVtkMapper2D *imageMapper = dynamic_cast(node->GetMapper(1)); // GetMapper(1) provides the 2D mapper for the data node // if there is a 2D mapper, which is not the standard image mapper... if (!imageMapper && node->GetMapper(1)) { //... check if it is the composite mapper std::string cname(node->GetMapper(1)->GetNameOfClass()); if (!cname.compare("CompositeMapper")) // string.compare returns 0 if the two strings are equal. { // get the standard image mapper. // This is a special case in MITK and does only work for the CompositeMapper. imageMapper = dynamic_cast(node->GetMapper(3)); } } if ((node->IsVisible(renderer)) && imageMapper) { WeakPointerProperty::Pointer rendererProp = dynamic_cast(GetDataNode()->GetPropertyList()->GetProperty("renderer")); if (rendererProp.IsNotNull()) { BaseRenderer::Pointer planeRenderer = dynamic_cast(rendererProp->GetWeakPointer().GetPointer()); // Retrieve and update image to be mapped const ImageVtkMapper2D::LocalStorage *localStorage = imageMapper->GetLocalStorage(planeRenderer); if (planeRenderer.IsNotNull()) { // perform update of imagemapper if needed (maybe the respective 2D renderwindow is not rendered/update // before) imageMapper->Update(planeRenderer); // If it has not been initialized already in a previous pass, // generate an actor and a texture object to // render the image associated with the ImageVtkMapper2D. vtkActor *imageActor; vtkDataSetMapper *dataSetMapper = nullptr; vtkTexture *texture; if (m_ImageActors.count(imageMapper) == 0) { dataSetMapper = vtkDataSetMapper::New(); // Enable rendering without copying the image. dataSetMapper->ImmediateModeRenderingOn(); texture = vtkNeverTranslucentTexture::New(); texture->RepeatOff(); imageActor = vtkActor::New(); imageActor->SetMapper(dataSetMapper); imageActor->SetTexture(texture); imageActor->GetProperty()->SetOpacity( 0.999); // HACK! otherwise VTK wouldn't recognize this as translucent // surface (if LUT values map to alpha < 255 // improvement: apply "opacity" property onle HERE and also in 2D image mapper. DO NOT change LUT to // achieve // translucent images (see method ChangeOpacity in image mapper 2D) // Make imageActor the sole owner of the mapper and texture // objects dataSetMapper->UnRegister(nullptr); texture->UnRegister(nullptr); // Store the actor so that it may be accessed in following // passes. m_ImageActors[imageMapper].Initialize(imageActor, imageMapper, m_ImageMapperDeletedCommand); } else { // Else, retrieve the actor and associated objects from the // previous pass. imageActor = m_ImageActors[imageMapper].m_Actor; dataSetMapper = (vtkDataSetMapper *)imageActor->GetMapper(); texture = imageActor->GetTexture(); } // Set poly data new each time its object changes (e.g. when // switching between planar and curved geometries) if ((dataSetMapper != nullptr) && (dataSetMapper->GetInput() != surface->GetVtkPolyData())) { dataSetMapper->SetInputData(surface->GetVtkPolyData()); } dataSetMapper->Update(); // Check if the m_ReslicedImage is nullptr. // This is the case when no image geometry is met by // the reslicer. In that case, the texture has to be // empty (black) and we don't have to do anything. // See fixed bug #13275 if (localStorage->m_ReslicedImage != nullptr) { texture->SetInputConnection(localStorage->m_LevelWindowFilter->GetOutputPort()); // do not use a VTK lookup table (we do that ourselves in m_LevelWindowFilter) texture->MapColorScalarsThroughLookupTableOff(); // re-use properties from the 2D image mapper imageActor->SetProperty(localStorage->m_Actor->GetProperty()); imageActor->GetProperty()->SetAmbient(0.5); // Set texture interpolation on/off bool textureInterpolation = node->IsOn("texture interpolation", renderer); texture->SetInterpolate(textureInterpolation); // Store this actor to be added to the actor assembly, sort // by layer int layer = 1; node->GetIntProperty("layer", layer); layerSortedActors.insert(std::pair(layer, imageActor)); } } } } } } void PlaneGeometryDataVtkMapper3D::ActorInfo::Initialize(vtkActor *actor, itk::Object *sender, itk::Command *command) { m_Actor = actor; m_Sender = sender; // Get informed when ImageMapper object is deleted, so that // the data structures built here can be deleted as well m_ObserverID = sender->AddObserver(itk::DeleteEvent(), command); } PlaneGeometryDataVtkMapper3D::ActorInfo::ActorInfo() : m_Actor(nullptr), m_Sender(nullptr), m_ObserverID(0) {} PlaneGeometryDataVtkMapper3D::ActorInfo::~ActorInfo() { if (m_Sender != nullptr) { m_Sender->RemoveObserver(m_ObserverID); } if (m_Actor != nullptr) { m_Actor->ReleaseGraphicsResources(0); m_Actor->Delete(); } } } // namespace mitk diff --git a/Modules/Core/src/Rendering/mitkPointSetVtkMapper3D.cpp b/Modules/Core/src/Rendering/mitkPointSetVtkMapper3D.cpp index a4988d204d..9259fd473c 100644 --- a/Modules/Core/src/Rendering/mitkPointSetVtkMapper3D.cpp +++ b/Modules/Core/src/Rendering/mitkPointSetVtkMapper3D.cpp @@ -1,706 +1,705 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPointSetVtkMapper3D.h" #include "mitkColorProperty.h" #include "mitkDataNode.h" #include "mitkPointSet.h" #include "mitkProperties.h" #include "mitkVtkPropRenderer.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include - #include +#include const mitk::PointSet *mitk::PointSetVtkMapper3D::GetInput() { return static_cast(GetDataNode()->GetData()); } mitk::PointSetVtkMapper3D::PointSetVtkMapper3D() : m_vtkSelectedPointList(nullptr), m_vtkUnselectedPointList(nullptr), m_VtkSelectedPolyDataMapper(nullptr), m_VtkUnselectedPolyDataMapper(nullptr), m_vtkTextList(nullptr), m_NumberOfSelectedAdded(0), m_NumberOfUnselectedAdded(0), m_PointSize(1.0), m_ContourRadius(0.5), m_VertexRendering(false) { // propassembly m_PointsAssembly = vtkSmartPointer::New(); // creating actors to be able to set transform m_SelectedActor = vtkSmartPointer::New(); m_UnselectedActor = vtkSmartPointer::New(); m_ContourActor = vtkSmartPointer::New(); } mitk::PointSetVtkMapper3D::~PointSetVtkMapper3D() { } void mitk::PointSetVtkMapper3D::ReleaseGraphicsResources(vtkWindow *renWin) { m_PointsAssembly->ReleaseGraphicsResources(renWin); m_SelectedActor->ReleaseGraphicsResources(renWin); m_UnselectedActor->ReleaseGraphicsResources(renWin); m_ContourActor->ReleaseGraphicsResources(renWin); } void mitk::PointSetVtkMapper3D::ReleaseGraphicsResources(mitk::BaseRenderer *renderer) { m_PointsAssembly->ReleaseGraphicsResources(renderer->GetRenderWindow()); m_SelectedActor->ReleaseGraphicsResources(renderer->GetRenderWindow()); m_UnselectedActor->ReleaseGraphicsResources(renderer->GetRenderWindow()); m_ContourActor->ReleaseGraphicsResources(renderer->GetRenderWindow()); } void mitk::PointSetVtkMapper3D::CreateVTKRenderObjects() { m_vtkSelectedPointList = vtkSmartPointer::New(); m_vtkUnselectedPointList = vtkSmartPointer::New(); m_PointsAssembly->VisibilityOn(); if (m_PointsAssembly->GetParts()->IsItemPresent(m_SelectedActor)) m_PointsAssembly->RemovePart(m_SelectedActor); if (m_PointsAssembly->GetParts()->IsItemPresent(m_UnselectedActor)) m_PointsAssembly->RemovePart(m_UnselectedActor); if (m_PointsAssembly->GetParts()->IsItemPresent(m_ContourActor)) m_PointsAssembly->RemovePart(m_ContourActor); // exceptional displaying for PositionTracker -> MouseOrientationTool int mapperID; bool isInputDevice = false; if (this->GetDataNode()->GetBoolProperty("inputdevice", isInputDevice) && isInputDevice) { if (this->GetDataNode()->GetIntProperty("BaseRendererMapperID", mapperID) && mapperID == BaseRenderer::Standard3D) return; // The event for the PositionTracker came from the 3d widget and not needs to be displayed } // get and update the PointSet mitk::PointSet::Pointer input = const_cast(this->GetInput()); /* only update the input data, if the property tells us to */ bool update = true; this->GetDataNode()->GetBoolProperty("updateDataOnRender", update); if (update == true) input->Update(); int timestep = this->GetTimestep(); mitk::PointSet::DataType::Pointer itkPointSet = input->GetPointSet(timestep); if (itkPointSet.GetPointer() == nullptr) { m_PointsAssembly->VisibilityOff(); return; } // now fill selected and unselected pointList // get size of Points in Property m_PointSize = 2; mitk::FloatProperty::Pointer pointSizeProp = dynamic_cast(this->GetDataNode()->GetProperty("pointsize")); if (pointSizeProp.IsNotNull()) m_PointSize = pointSizeProp->GetValue(); // get the property for creating a label onto every point only once bool showLabel = true; this->GetDataNode()->GetBoolProperty("show label", showLabel); const char *pointLabel = nullptr; if (showLabel) { if (dynamic_cast(this->GetDataNode()->GetPropertyList()->GetProperty("label")) != nullptr) pointLabel = dynamic_cast(this->GetDataNode()->GetPropertyList()->GetProperty("label"))->GetValue(); else showLabel = false; } // whether or not to creat a "contour" - connecting lines between all the points int nbPoints = itkPointSet->GetPointData()->Size(); bool makeContour = false; this->GetDataNode()->GetBoolProperty("show contour", makeContour); bool closeContour = false; this->GetDataNode()->GetBoolProperty("close contour", closeContour); int contourPointLimit = 0; // NO contour if (makeContour) { if (closeContour) contourPointLimit = nbPoints; else contourPointLimit = nbPoints - 1; } // build list of all positions for later transform in one go mitk::PointSet::PointsContainer::Iterator pointsIter; int ptIdx; m_NumberOfSelectedAdded = 0; m_NumberOfUnselectedAdded = 0; vtkSmartPointer localPoints = vtkSmartPointer::New(); m_WorldPositions = vtkSmartPointer::New(); m_PointConnections = vtkSmartPointer::New(); // m_PointConnections between points for (ptIdx = 0, pointsIter = itkPointSet->GetPoints()->Begin(); pointsIter != itkPointSet->GetPoints()->End(); pointsIter++, ptIdx++) { itk::Point currentPoint = pointsIter->Value(); localPoints->InsertPoint(ptIdx, currentPoint[0], currentPoint[1], currentPoint[2]); if (makeContour && ptIdx < contourPointLimit) { vtkIdType cell[2] = {(ptIdx + 1) % nbPoints, ptIdx}; m_PointConnections->InsertNextCell(2, cell); } } vtkSmartPointer vtktransform = this->GetDataNode()->GetVtkTransform(this->GetTimestep()); vtktransform->TransformPoints(localPoints, m_WorldPositions); // create contour if (makeContour) { this->CreateContour(m_WorldPositions, m_PointConnections); } // check if the list for the PointDataContainer is the same size as the PointsContainer. Is not, then the points were // inserted manually and can not be visualized according to the PointData (selected/unselected) bool pointDataBroken = (itkPointSet->GetPointData()->Size() != itkPointSet->GetPoints()->Size()); // now add an object for each point in data mitk::PointSet::PointDataContainer::Iterator pointDataIter = itkPointSet->GetPointData()->Begin(); for (ptIdx = 0; ptIdx < nbPoints; ++ptIdx) // pointDataIter moved at end of loop { double currentPoint[3]; m_WorldPositions->GetPoint(ptIdx, currentPoint); vtkSmartPointer source; // check for the pointtype in data and decide which geom-object to take and then add to the selected or unselected // list int pointType; if (itkPointSet->GetPointData()->size() == 0 || pointDataBroken) pointType = mitk::PTUNDEFINED; else pointType = pointDataIter.Value().pointSpec; switch (pointType) { case mitk::PTUNDEFINED: { vtkSmartPointer sphere = vtkSmartPointer::New(); sphere->SetRadius(m_PointSize / 2.0f); sphere->SetCenter(currentPoint); // sphere->SetCenter(pointsIter.Value()[0],pointsIter.Value()[1],pointsIter.Value()[2]); // MouseOrientation Tool (PositionTracker) if (isInputDevice) { sphere->SetThetaResolution(10); sphere->SetPhiResolution(10); } else { sphere->SetThetaResolution(20); sphere->SetPhiResolution(20); } source = sphere; } break; case mitk::PTSTART: { vtkSmartPointer cube = vtkSmartPointer::New(); cube->SetXLength(m_PointSize / 2); cube->SetYLength(m_PointSize / 2); cube->SetZLength(m_PointSize / 2); cube->SetCenter(currentPoint); source = cube; } break; case mitk::PTCORNER: { vtkSmartPointer cone = vtkSmartPointer::New(); cone->SetRadius(m_PointSize / 2.0f); cone->SetCenter(currentPoint); cone->SetResolution(20); source = cone; } break; case mitk::PTEDGE: { vtkSmartPointer cylinder = vtkSmartPointer::New(); cylinder->SetRadius(m_PointSize / 2.0f); cylinder->SetCenter(currentPoint); cylinder->SetResolution(20); source = cylinder; } break; case mitk::PTEND: { vtkSmartPointer sphere = vtkSmartPointer::New(); sphere->SetRadius(m_PointSize / 2.0f); // no SetCenter?? this functionality should be explained! // otherwise: join with default block! sphere->SetThetaResolution(20); sphere->SetPhiResolution(20); source = sphere; } break; default: { vtkSmartPointer sphere = vtkSmartPointer::New(); sphere->SetRadius(m_PointSize / 2.0f); sphere->SetCenter(currentPoint); sphere->SetThetaResolution(20); sphere->SetPhiResolution(20); source = sphere; } break; } if (pointDataIter.Value().selected && !pointDataBroken) { m_vtkSelectedPointList->AddInputConnection(source->GetOutputPort()); ++m_NumberOfSelectedAdded; } else { m_vtkUnselectedPointList->AddInputConnection(source->GetOutputPort()); ++m_NumberOfUnselectedAdded; } if (showLabel) { char buffer[20]; std::string l = pointLabel; if (input->GetSize() > 1) { sprintf(buffer, "%d", ptIdx + 1); l.append(buffer); } // Define the text for the label vtkSmartPointer label = vtkSmartPointer::New(); label->SetText(l.c_str()); //# Set up a transform to move the label to a new position. vtkSmartPointer aLabelTransform = vtkSmartPointer::New(); aLabelTransform->Identity(); aLabelTransform->Translate(currentPoint[0] + 2, currentPoint[1] + 2, currentPoint[2]); aLabelTransform->Scale(5.7, 5.7, 5.7); //# Move the label to a new position. vtkSmartPointer labelTransform = vtkSmartPointer::New(); labelTransform->SetTransform(aLabelTransform); labelTransform->SetInputConnection(label->GetOutputPort()); // add it to the wright PointList if (pointType) { m_vtkSelectedPointList->AddInputConnection(labelTransform->GetOutputPort()); ++m_NumberOfSelectedAdded; } else { m_vtkUnselectedPointList->AddInputConnection(labelTransform->GetOutputPort()); ++m_NumberOfUnselectedAdded; } } if (pointDataIter != itkPointSet->GetPointData()->End()) pointDataIter++; } // end FOR // now according to number of elements added to selected or unselected, build up the rendering pipeline if (m_NumberOfSelectedAdded > 0) { m_VtkSelectedPolyDataMapper = vtkSmartPointer::New(); m_VtkSelectedPolyDataMapper->SetInputConnection(m_vtkSelectedPointList->GetOutputPort()); // create a new instance of the actor m_SelectedActor = vtkSmartPointer::New(); m_SelectedActor->SetMapper(m_VtkSelectedPolyDataMapper); m_PointsAssembly->AddPart(m_SelectedActor); } if (m_NumberOfUnselectedAdded > 0) { m_VtkUnselectedPolyDataMapper = vtkSmartPointer::New(); m_VtkUnselectedPolyDataMapper->SetInputConnection(m_vtkUnselectedPointList->GetOutputPort()); // create a new instance of the actor m_UnselectedActor = vtkSmartPointer::New(); m_UnselectedActor->SetMapper(m_VtkUnselectedPolyDataMapper); m_PointsAssembly->AddPart(m_UnselectedActor); } } void mitk::PointSetVtkMapper3D::VertexRendering() { // get and update the PointSet mitk::PointSet::Pointer input = const_cast(this->GetInput()); /* only update the input data, if the property tells us to */ bool update = true; this->GetDataNode()->GetBoolProperty("updateDataOnRender", update); if (update == true) input->Update(); int timestep = this->GetTimestep(); mitk::PointSet::DataType::Pointer itkPointSet = input->GetPointSet(timestep); // turn off standard actors m_UnselectedActor->VisibilityOff(); m_SelectedActor->VisibilityOff(); // point size m_PointSize = 2.0; mitk::FloatProperty::Pointer pointSizeProp = dynamic_cast(this->GetDataNode()->GetProperty("pointsize")); if (pointSizeProp.IsNotNull()) m_PointSize = pointSizeProp->GetValue(); double *color = m_UnselectedActor->GetProperty()->GetColor(); double opacity = m_UnselectedActor->GetProperty()->GetOpacity(); glClearColor(0.0, 0.0, 0.0, 0.0); glDisable(GL_COLOR_MATERIAL); glDisable(GL_LIGHTING); glEnable(GL_POINT_SMOOTH); glPointSize(m_PointSize); glBegin(GL_POINTS); glColor4d(color[0], color[1], color[2], opacity); for (auto pointsIter = itkPointSet->GetPoints()->Begin(); pointsIter != itkPointSet->GetPoints()->End(); pointsIter++) { const itk::Point &point = pointsIter->Value(); glVertex3d(point[0], point[1], point[2]); } glEnd(); // reset context glPointSize(1.0); glDisable(GL_POINT_SMOOTH); glEnable(GL_COLOR_MATERIAL); glEnable(GL_LIGHTING); } void mitk::PointSetVtkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) { m_UnselectedActor->VisibilityOff(); m_SelectedActor->VisibilityOff(); m_ContourActor->VisibilityOff(); return; } // create new vtk render objects (e.g. sphere for a point) SetVtkMapperImmediateModeRendering(m_VtkSelectedPolyDataMapper); SetVtkMapperImmediateModeRendering(m_VtkUnselectedPolyDataMapper); BaseLocalStorage *ls = m_LSH.GetLocalStorage(renderer); bool needGenerateData = ls->IsGenerateDataRequired(renderer, this, GetDataNode()); if (!needGenerateData) { mitk::FloatProperty *pointSizeProp = dynamic_cast(this->GetDataNode()->GetProperty("pointsize")); mitk::FloatProperty *contourSizeProp = dynamic_cast(this->GetDataNode()->GetProperty("contoursize")); bool useVertexRendering = false; this->GetDataNode()->GetBoolProperty("Vertex Rendering", useVertexRendering); // only create new vtk render objects if property values were changed if (pointSizeProp && m_PointSize != pointSizeProp->GetValue()) needGenerateData = true; if (contourSizeProp && m_ContourRadius != contourSizeProp->GetValue()) needGenerateData = true; // when vertex rendering is enabled the pointset is always // drawn with opengl, thus we leave needGenerateData always false if (useVertexRendering && m_VertexRendering != useVertexRendering) { needGenerateData = false; m_VertexRendering = true; } else if (!useVertexRendering && m_VertexRendering) { m_VertexRendering = false; needGenerateData = true; } } if (needGenerateData) { this->CreateVTKRenderObjects(); ls->UpdateGenerateDataTime(); } this->ApplyAllProperties(renderer, m_ContourActor); bool showPoints = true; this->GetDataNode()->GetBoolProperty("show points", showPoints); m_UnselectedActor->SetVisibility(showPoints && !m_VertexRendering); m_SelectedActor->SetVisibility(showPoints && !m_VertexRendering); if (false && dynamic_cast(this->GetDataNode()->GetProperty("opacity")) != nullptr) { mitk::FloatProperty::Pointer pointOpacity = dynamic_cast(this->GetDataNode()->GetProperty("opacity")); float opacity = pointOpacity->GetValue(); m_ContourActor->GetProperty()->SetOpacity(opacity); m_UnselectedActor->GetProperty()->SetOpacity(opacity); m_SelectedActor->GetProperty()->SetOpacity(opacity); } bool showContour = false; this->GetDataNode()->GetBoolProperty("show contour", showContour); m_ContourActor->SetVisibility(showContour); // use vertex rendering if (m_VertexRendering) { VertexRendering(); ls->UpdateGenerateDataTime(); } } void mitk::PointSetVtkMapper3D::ResetMapper(BaseRenderer * /*renderer*/) { m_PointsAssembly->VisibilityOff(); } vtkProp *mitk::PointSetVtkMapper3D::GetVtkProp(mitk::BaseRenderer * /*renderer*/) { return m_PointsAssembly; } void mitk::PointSetVtkMapper3D::UpdateVtkTransform(mitk::BaseRenderer * /*renderer*/) { } void mitk::PointSetVtkMapper3D::ApplyAllProperties(mitk::BaseRenderer *renderer, vtkActor *actor) { Superclass::ApplyColorAndOpacityProperties(renderer, actor); // check for color props and use it for rendering of selected/unselected points and contour // due to different params in VTK (double/float) we have to convert! // vars to convert to double unselectedColor[4] = {1.0f, 1.0f, 0.0f, 1.0f}; // yellow double selectedColor[4] = {1.0f, 0.0f, 0.0f, 1.0f}; // red double contourColor[4] = {1.0f, 0.0f, 0.0f, 1.0f}; // red // different types for color!!! mitk::Color tmpColor; double opacity = 1.0; // check if there is an unselected property if (dynamic_cast( this->GetDataNode()->GetPropertyList(renderer)->GetProperty("unselectedcolor")) != nullptr) { tmpColor = dynamic_cast( this->GetDataNode()->GetPropertyList(renderer)->GetProperty("unselectedcolor")) ->GetValue(); unselectedColor[0] = tmpColor[0]; unselectedColor[1] = tmpColor[1]; unselectedColor[2] = tmpColor[2]; unselectedColor[3] = 1.0f; //!!define a new ColorProp to be able to pass alpha value } else if (dynamic_cast( this->GetDataNode()->GetPropertyList(nullptr)->GetProperty("unselectedcolor")) != nullptr) { tmpColor = dynamic_cast(this->GetDataNode()->GetPropertyList(nullptr)->GetProperty("unselectedcolor")) ->GetValue(); unselectedColor[0] = tmpColor[0]; unselectedColor[1] = tmpColor[1]; unselectedColor[2] = tmpColor[2]; unselectedColor[3] = 1.0f; //!!define a new ColorProp to be able to pass alpha value } else { // check if the node has a color float unselectedColorTMP[4] = {1.0f, 1.0f, 0.0f, 1.0f}; // yellow m_DataNode->GetColor(unselectedColorTMP, nullptr); unselectedColor[0] = unselectedColorTMP[0]; unselectedColor[1] = unselectedColorTMP[1]; unselectedColor[2] = unselectedColorTMP[2]; // unselectedColor[3] stays 1.0f } // get selected property if (dynamic_cast( this->GetDataNode()->GetPropertyList(renderer)->GetProperty("selectedcolor")) != nullptr) { tmpColor = dynamic_cast(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("selectedcolor")) ->GetValue(); selectedColor[0] = tmpColor[0]; selectedColor[1] = tmpColor[1]; selectedColor[2] = tmpColor[2]; selectedColor[3] = 1.0f; } else if (dynamic_cast( this->GetDataNode()->GetPropertyList(nullptr)->GetProperty("selectedcolor")) != nullptr) { tmpColor = dynamic_cast(this->GetDataNode()->GetPropertyList(nullptr)->GetProperty("selectedcolor")) ->GetValue(); selectedColor[0] = tmpColor[0]; selectedColor[1] = tmpColor[1]; selectedColor[2] = tmpColor[2]; selectedColor[3] = 1.0f; } // get contour property if (dynamic_cast( this->GetDataNode()->GetPropertyList(renderer)->GetProperty("contourcolor")) != nullptr) { tmpColor = dynamic_cast(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("contourcolor")) ->GetValue(); contourColor[0] = tmpColor[0]; contourColor[1] = tmpColor[1]; contourColor[2] = tmpColor[2]; contourColor[3] = 1.0f; } else if (dynamic_cast( this->GetDataNode()->GetPropertyList(nullptr)->GetProperty("contourcolor")) != nullptr) { tmpColor = dynamic_cast(this->GetDataNode()->GetPropertyList(nullptr)->GetProperty("contourcolor")) ->GetValue(); contourColor[0] = tmpColor[0]; contourColor[1] = tmpColor[1]; contourColor[2] = tmpColor[2]; contourColor[3] = 1.0f; } if (dynamic_cast(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("opacity")) != nullptr) { mitk::FloatProperty::Pointer pointOpacity = dynamic_cast(this->GetDataNode()->GetPropertyList(renderer)->GetProperty("opacity")); opacity = pointOpacity->GetValue(); } else if (dynamic_cast(this->GetDataNode()->GetPropertyList(nullptr)->GetProperty("opacity")) != nullptr) { mitk::FloatProperty::Pointer pointOpacity = dynamic_cast(this->GetDataNode()->GetPropertyList(nullptr)->GetProperty("opacity")); opacity = pointOpacity->GetValue(); } // finished color / opacity fishing! // check if a contour shall be drawn bool showContour = false; this->GetDataNode()->GetBoolProperty("show contour", showContour, renderer); if (showContour && (m_ContourActor != nullptr)) { this->CreateContour(m_WorldPositions, m_PointConnections); m_ContourActor->GetProperty()->SetColor(contourColor); m_ContourActor->GetProperty()->SetOpacity(opacity); } m_SelectedActor->GetProperty()->SetColor(selectedColor); m_SelectedActor->GetProperty()->SetOpacity(opacity); m_UnselectedActor->GetProperty()->SetColor(unselectedColor); m_UnselectedActor->GetProperty()->SetOpacity(opacity); } void mitk::PointSetVtkMapper3D::CreateContour(vtkPoints *points, vtkCellArray *m_PointConnections) { vtkSmartPointer vtkContourPolyData = vtkSmartPointer::New(); vtkSmartPointer vtkContourPolyDataMapper = vtkSmartPointer::New(); vtkSmartPointer contour = vtkSmartPointer::New(); contour->SetPoints(points); contour->SetLines(m_PointConnections); vtkSmartPointer tubeFilter = vtkSmartPointer::New(); tubeFilter->SetNumberOfSides(12); tubeFilter->SetInputData(contour); // check for property contoursize. m_ContourRadius = 0.5; mitk::FloatProperty::Pointer contourSizeProp = dynamic_cast(this->GetDataNode()->GetProperty("contoursize")); if (contourSizeProp.IsNotNull()) m_ContourRadius = contourSizeProp->GetValue(); tubeFilter->SetRadius(m_ContourRadius); tubeFilter->Update(); // add to pipeline vtkContourPolyData->AddInputConnection(tubeFilter->GetOutputPort()); vtkContourPolyDataMapper->SetInputConnection(vtkContourPolyData->GetOutputPort()); m_ContourActor->SetMapper(vtkContourPolyDataMapper); m_PointsAssembly->AddPart(m_ContourActor); } void mitk::PointSetVtkMapper3D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { node->AddProperty("line width", mitk::IntProperty::New(2), renderer, overwrite); node->AddProperty("pointsize", mitk::FloatProperty::New(1.0), renderer, overwrite); node->AddProperty("selectedcolor", mitk::ColorProperty::New(1.0f, 0.0f, 0.0f), renderer, overwrite); // red node->AddProperty("color", mitk::ColorProperty::New(1.0f, 1.0f, 0.0f), renderer, overwrite); // yellow node->AddProperty("opacity", mitk::FloatProperty::New(1.0f), renderer, overwrite); node->AddProperty("show contour", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("close contour", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("contourcolor", mitk::ColorProperty::New(1.0f, 0.0f, 0.0f), renderer, overwrite); node->AddProperty("contoursize", mitk::FloatProperty::New(0.5), renderer, overwrite); node->AddProperty("show points", mitk::BoolProperty::New(true), renderer, overwrite); node->AddProperty("updateDataOnRender", mitk::BoolProperty::New(true), renderer, overwrite); node->AddProperty("Vertex Rendering", mitk::BoolProperty::New(false), renderer, overwrite); Superclass::SetDefaultProperties(node, renderer, overwrite); } diff --git a/Modules/Core/src/Rendering/mitkSurfaceVtkMapper3D.cpp b/Modules/Core/src/Rendering/mitkSurfaceVtkMapper3D.cpp index cc114feac0..bc15a7a8ed 100644 --- a/Modules/Core/src/Rendering/mitkSurfaceVtkMapper3D.cpp +++ b/Modules/Core/src/Rendering/mitkSurfaceVtkMapper3D.cpp @@ -1,532 +1,522 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSurfaceVtkMapper3D.h" #include #include #include #include #include #include #include -#include #include #include #include #include #include #include #include #include // VTK #include #include #include #include #include #include #include #include const mitk::Surface *mitk::SurfaceVtkMapper3D::GetInput() { return static_cast(GetDataNode()->GetData()); } mitk::SurfaceVtkMapper3D::SurfaceVtkMapper3D() { m_GenerateNormals = false; } mitk::SurfaceVtkMapper3D::~SurfaceVtkMapper3D() { } void mitk::SurfaceVtkMapper3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) { ls->m_Actor->VisibilityOff(); return; } // // set the input-object at time t for the mapper // mitk::Surface::Pointer input = const_cast(this->GetInput()); vtkSmartPointer polydata = input->GetVtkPolyData(this->GetTimestep()); if (polydata == nullptr) { ls->m_Actor->VisibilityOff(); return; } if (m_GenerateNormals) { ls->m_VtkPolyDataNormals->SetInputData(polydata); ls->m_VtkPolyDataMapper->SetInputConnection(ls->m_VtkPolyDataNormals->GetOutputPort()); } else { bool depthsorting = false; GetDataNode()->GetBoolProperty("Depth Sorting", depthsorting); if (depthsorting) { ls->m_DepthSort->SetInputData(polydata); ls->m_DepthSort->SetCamera(renderer->GetVtkRenderer()->GetActiveCamera()); ls->m_DepthSort->SetDirectionToBackToFront(); ls->m_DepthSort->Update(); ls->m_VtkPolyDataMapper->SetInputConnection(ls->m_DepthSort->GetOutputPort()); } else { ls->m_VtkPolyDataMapper->SetInputData(polydata); } } // // apply properties read from the PropertyList // ApplyAllProperties(renderer, ls->m_Actor); if (visible) ls->m_Actor->VisibilityOn(); } void mitk::SurfaceVtkMapper3D::ResetMapper(BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); ls->m_Actor->VisibilityOff(); } void mitk::SurfaceVtkMapper3D::ApplyMitkPropertiesToVtkProperty(mitk::DataNode *node, vtkProperty *property, mitk::BaseRenderer *renderer) { // Backface culling { mitk::BoolProperty::Pointer p; node->GetProperty(p, "Backface Culling", renderer); bool useCulling = false; if (p.IsNotNull()) useCulling = p->GetValue(); property->SetBackfaceCulling(useCulling); } // Colors { double ambient[3] = {0.5, 0.5, 0.0}; double diffuse[3] = {0.5, 0.5, 0.0}; double specular[3] = {1.0, 1.0, 1.0}; float coeff_ambient = 0.5f; float coeff_diffuse = 0.5f; float coeff_specular = 0.5f; float power_specular = 10.0f; // Color { mitk::ColorProperty::Pointer p; node->GetProperty(p, "color", renderer); if (p.IsNotNull()) { mitk::Color c = p->GetColor(); ambient[0] = c.GetRed(); ambient[1] = c.GetGreen(); ambient[2] = c.GetBlue(); diffuse[0] = c.GetRed(); diffuse[1] = c.GetGreen(); diffuse[2] = c.GetBlue(); // Setting specular color to the same, make physically no real sense, however vtk rendering slows down, if these // colors are different. specular[0] = c.GetRed(); specular[1] = c.GetGreen(); specular[2] = c.GetBlue(); } } // Ambient { mitk::ColorProperty::Pointer p; node->GetProperty(p, "material.ambientColor", renderer); if (p.IsNotNull()) { mitk::Color c = p->GetColor(); ambient[0] = c.GetRed(); ambient[1] = c.GetGreen(); ambient[2] = c.GetBlue(); } } // Diffuse { mitk::ColorProperty::Pointer p; node->GetProperty(p, "material.diffuseColor", renderer); if (p.IsNotNull()) { mitk::Color c = p->GetColor(); diffuse[0] = c.GetRed(); diffuse[1] = c.GetGreen(); diffuse[2] = c.GetBlue(); } } // Specular { mitk::ColorProperty::Pointer p; node->GetProperty(p, "material.specularColor", renderer); if (p.IsNotNull()) { mitk::Color c = p->GetColor(); specular[0] = c.GetRed(); specular[1] = c.GetGreen(); specular[2] = c.GetBlue(); } } // Ambient coeff { node->GetFloatProperty("material.ambientCoefficient", coeff_ambient, renderer); } // Diffuse coeff { node->GetFloatProperty("material.diffuseCoefficient", coeff_diffuse, renderer); } // Specular coeff { node->GetFloatProperty("material.specularCoefficient", coeff_specular, renderer); } // Specular power { node->GetFloatProperty("material.specularPower", power_specular, renderer); } property->SetAmbient(coeff_ambient); property->SetDiffuse(coeff_diffuse); property->SetSpecular(coeff_specular); property->SetSpecularPower(power_specular); property->SetAmbientColor(ambient); property->SetDiffuseColor(diffuse); property->SetSpecularColor(specular); } // Render mode { // Opacity { float opacity = 1.0f; if (node->GetOpacity(opacity, renderer)) property->SetOpacity(opacity); } // Wireframe line width { float lineWidth = 1; node->GetFloatProperty("material.wireframeLineWidth", lineWidth, renderer); property->SetLineWidth(lineWidth); } // Point size { float pointSize = 1.0f; node->GetFloatProperty("material.pointSize", pointSize, renderer); property->SetPointSize(pointSize); } // Representation { mitk::VtkRepresentationProperty::Pointer p; node->GetProperty(p, "material.representation", renderer); if (p.IsNotNull()) property->SetRepresentation(p->GetVtkRepresentation()); } // Interpolation { mitk::VtkInterpolationProperty::Pointer p; node->GetProperty(p, "material.interpolation", renderer); if (p.IsNotNull()) property->SetInterpolation(p->GetVtkInterpolation()); } } } void mitk::SurfaceVtkMapper3D::ApplyAllProperties(mitk::BaseRenderer *renderer, vtkActor * /*actor*/) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); - // Applying shading properties Superclass::ApplyColorAndOpacityProperties(renderer, ls->m_Actor); - this->ApplyShaderProperties(renderer); // VTK Properties ApplyMitkPropertiesToVtkProperty(this->GetDataNode(), ls->m_Actor->GetProperty(), renderer); mitk::TransferFunctionProperty::Pointer transferFuncProp; this->GetDataNode()->GetProperty(transferFuncProp, "Surface.TransferFunction", renderer); if (transferFuncProp.IsNotNull()) { ls->m_VtkPolyDataMapper->SetLookupTable(transferFuncProp->GetValue()->GetColorTransferFunction()); } mitk::LookupTableProperty::Pointer lookupTableProp; this->GetDataNode()->GetProperty(lookupTableProp, "LookupTable", renderer); if (lookupTableProp.IsNotNull()) { ls->m_VtkPolyDataMapper->SetLookupTable(lookupTableProp->GetLookupTable()->GetVtkLookupTable()); } mitk::LevelWindow levelWindow; if (this->GetDataNode()->GetLevelWindow(levelWindow, renderer, "levelWindow")) { ls->m_VtkPolyDataMapper->SetScalarRange(levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound()); } else if (this->GetDataNode()->GetLevelWindow(levelWindow, renderer)) { ls->m_VtkPolyDataMapper->SetScalarRange(levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound()); } bool scalarVisibility = false; this->GetDataNode()->GetBoolProperty("scalar visibility", scalarVisibility); ls->m_VtkPolyDataMapper->SetScalarVisibility((scalarVisibility ? 1 : 0)); if (scalarVisibility) { mitk::VtkScalarModeProperty *scalarMode; if (this->GetDataNode()->GetProperty(scalarMode, "scalar mode", renderer)) ls->m_VtkPolyDataMapper->SetScalarMode(scalarMode->GetVtkScalarMode()); else ls->m_VtkPolyDataMapper->SetScalarModeToDefault(); bool colorMode = false; this->GetDataNode()->GetBoolProperty("color mode", colorMode); ls->m_VtkPolyDataMapper->SetColorMode((colorMode ? 1 : 0)); double scalarsMin = 0; this->GetDataNode()->GetDoubleProperty("ScalarsRangeMinimum", scalarsMin, renderer); double scalarsMax = 1.0; this->GetDataNode()->GetDoubleProperty("ScalarsRangeMaximum", scalarsMax, renderer); ls->m_VtkPolyDataMapper->SetScalarRange(scalarsMin, scalarsMax); } mitk::SmartPointerProperty::Pointer imagetextureProp = dynamic_cast(GetDataNode()->GetProperty("Surface.Texture", renderer)); if (imagetextureProp.IsNotNull()) { mitk::Image *miktTexture = dynamic_cast(imagetextureProp->GetSmartPointer().GetPointer()); vtkSmartPointer vtkTxture = vtkSmartPointer::New(); // Either select the first slice of a volume if (miktTexture->GetDimension(2) > 1) { MITK_WARN << "3D Textures are not supported by VTK and MITK. The first slice of the volume will be used instead!"; mitk::ImageSliceSelector::Pointer sliceselector = mitk::ImageSliceSelector::New(); sliceselector->SetSliceNr(0); sliceselector->SetChannelNr(0); sliceselector->SetTimeNr(0); sliceselector->SetInput(miktTexture); sliceselector->Update(); vtkTxture->SetInputData(sliceselector->GetOutput()->GetVtkImageData()); } else // or just use the 2D image { vtkTxture->SetInputData(miktTexture->GetVtkImageData()); } // pass the texture to the actor ls->m_Actor->SetTexture(vtkTxture); if (ls->m_VtkPolyDataMapper->GetInput()->GetPointData()->GetTCoords() == nullptr) { MITK_ERROR << "Surface.Texture property was set, but there are no texture coordinates. Please provide texture " "coordinates for the vtkPolyData via vtkPolyData->GetPointData()->SetTCoords()."; } // if no texture is set, this will also remove a previously used texture // and reset the actor to it's default behaviour } else { ls->m_Actor->SetTexture(0); } // deprecated settings bool deprecatedUseCellData = false; this->GetDataNode()->GetBoolProperty("deprecated useCellDataForColouring", deprecatedUseCellData); bool deprecatedUsePointData = false; this->GetDataNode()->GetBoolProperty("deprecated usePointDataForColouring", deprecatedUsePointData); if (deprecatedUseCellData) { ls->m_VtkPolyDataMapper->SetColorModeToDefault(); ls->m_VtkPolyDataMapper->SetScalarRange(0, 255); ls->m_VtkPolyDataMapper->ScalarVisibilityOn(); ls->m_VtkPolyDataMapper->SetScalarModeToUseCellData(); ls->m_Actor->GetProperty()->SetSpecular(1); ls->m_Actor->GetProperty()->SetSpecularPower(50); ls->m_Actor->GetProperty()->SetInterpolationToPhong(); } else if (deprecatedUsePointData) { float scalarsMin = 0; if (dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMinimum")) != nullptr) scalarsMin = dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMinimum"))->GetValue(); float scalarsMax = 0.1; if (dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMaximum")) != nullptr) scalarsMax = dynamic_cast(this->GetDataNode()->GetProperty("ScalarsRangeMaximum"))->GetValue(); ls->m_VtkPolyDataMapper->SetScalarRange(scalarsMin, scalarsMax); ls->m_VtkPolyDataMapper->SetColorModeToMapScalars(); ls->m_VtkPolyDataMapper->ScalarVisibilityOn(); ls->m_Actor->GetProperty()->SetSpecular(1); ls->m_Actor->GetProperty()->SetSpecularPower(50); ls->m_Actor->GetProperty()->SetInterpolationToPhong(); } int deprecatedScalarMode = VTK_COLOR_MODE_DEFAULT; if (this->GetDataNode()->GetIntProperty("deprecated scalar mode", deprecatedScalarMode, renderer)) { ls->m_VtkPolyDataMapper->SetScalarMode(deprecatedScalarMode); ls->m_VtkPolyDataMapper->ScalarVisibilityOn(); ls->m_Actor->GetProperty()->SetSpecular(1); ls->m_Actor->GetProperty()->SetSpecularPower(50); } // Check whether one or more ClippingProperty objects have been defined for // this node. Check both renderer specific and global property lists, since // properties in both should be considered. const PropertyList::PropertyMap *rendererProperties = this->GetDataNode()->GetPropertyList(renderer)->GetMap(); const PropertyList::PropertyMap *globalProperties = this->GetDataNode()->GetPropertyList(nullptr)->GetMap(); // Add clipping planes (if any) ls->m_ClippingPlaneCollection->RemoveAllItems(); PropertyList::PropertyMap::const_iterator it; for (it = rendererProperties->begin(); it != rendererProperties->end(); ++it) { this->CheckForClippingProperty(renderer, (*it).second.GetPointer()); } for (it = globalProperties->begin(); it != globalProperties->end(); ++it) { this->CheckForClippingProperty(renderer, (*it).second.GetPointer()); } if (ls->m_ClippingPlaneCollection->GetNumberOfItems() > 0) { ls->m_VtkPolyDataMapper->SetClippingPlanes(ls->m_ClippingPlaneCollection); } else { ls->m_VtkPolyDataMapper->RemoveAllClippingPlanes(); } } vtkProp *mitk::SurfaceVtkMapper3D::GetVtkProp(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); return ls->m_Actor; } void mitk::SurfaceVtkMapper3D::CheckForClippingProperty(mitk::BaseRenderer *renderer, mitk::BaseProperty *property) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); ClippingProperty *clippingProperty = dynamic_cast(property); if ((clippingProperty != nullptr) && (clippingProperty->GetClippingEnabled())) { const Point3D &origin = clippingProperty->GetOrigin(); const Vector3D &normal = clippingProperty->GetNormal(); vtkSmartPointer clippingPlane = vtkSmartPointer::New(); clippingPlane->SetOrigin(origin[0], origin[1], origin[2]); clippingPlane->SetNormal(normal[0], normal[1], normal[2]); ls->m_ClippingPlaneCollection->AddItem(clippingPlane); } } void mitk::SurfaceVtkMapper3D::SetDefaultPropertiesForVtkProperty(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { // Shading { node->AddProperty("material.wireframeLineWidth", mitk::FloatProperty::New(1.0f), renderer, overwrite); node->AddProperty("material.pointSize", mitk::FloatProperty::New(1.0f), renderer, overwrite); node->AddProperty("material.ambientCoefficient", mitk::FloatProperty::New(0.05f), renderer, overwrite); node->AddProperty("material.diffuseCoefficient", mitk::FloatProperty::New(0.9f), renderer, overwrite); node->AddProperty("material.specularCoefficient", mitk::FloatProperty::New(1.0f), renderer, overwrite); node->AddProperty("material.specularPower", mitk::FloatProperty::New(16.0f), renderer, overwrite); node->AddProperty("material.representation", mitk::VtkRepresentationProperty::New(), renderer, overwrite); node->AddProperty("material.interpolation", mitk::VtkInterpolationProperty::New(), renderer, overwrite); } - - // Shaders - IShaderRepository *shaderRepo = CoreServices::GetShaderRepository(); - if (shaderRepo) - { - shaderRepo->AddDefaultProperties(node, renderer, overwrite); - } } void mitk::SurfaceVtkMapper3D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { node->AddProperty("color", mitk::ColorProperty::New(1.0f, 1.0f, 1.0f), renderer, overwrite); node->AddProperty("opacity", mitk::FloatProperty::New(1.0), renderer, overwrite); mitk::SurfaceVtkMapper3D::SetDefaultPropertiesForVtkProperty(node, renderer, overwrite); // Shading node->AddProperty("scalar visibility", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("color mode", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("scalar mode", mitk::VtkScalarModeProperty::New(), renderer, overwrite); mitk::Surface::Pointer surface = dynamic_cast(node->GetData()); if (surface.IsNotNull()) { if ((surface->GetVtkPolyData() != 0) && (surface->GetVtkPolyData()->GetPointData() != nullptr) && (surface->GetVtkPolyData()->GetPointData()->GetScalars() != 0)) { node->AddProperty("scalar visibility", mitk::BoolProperty::New(true), renderer, overwrite); node->AddProperty("color mode", mitk::BoolProperty::New(true), renderer, overwrite); } } // Backface culling node->AddProperty("Backface Culling", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("Depth Sorting", mitk::BoolProperty::New(false), renderer, overwrite); mitk::CoreServices::GetPropertyDescriptions()->AddDescription( "Depth Sorting", "Enables correct rendering for transparent objects by ordering polygons according to the distance " "to the camera. It is not recommended to enable this property for large surfaces (rendering might " "be slow)."); Superclass::SetDefaultProperties(node, renderer, overwrite); } diff --git a/Modules/Core/src/Rendering/mitkVtkMapper.cpp b/Modules/Core/src/Rendering/mitkVtkMapper.cpp index 5003e99123..6dd8eb2cba 100644 --- a/Modules/Core/src/Rendering/mitkVtkMapper.cpp +++ b/Modules/Core/src/Rendering/mitkVtkMapper.cpp @@ -1,161 +1,140 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkVtkMapper.h" mitk::VtkMapper::VtkMapper() { } mitk::VtkMapper::~VtkMapper() { } void mitk::VtkMapper::MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type) { - VtkMapperLocalStorage *ls = m_VtkMapperLSH.GetLocalStorage(renderer); - if (ls->m_ShaderProgram) - { - ls->m_ShaderProgram->Activate(); - } - switch (type) { case mitk::VtkPropRenderer::Opaque: this->MitkRenderOpaqueGeometry(renderer); break; case mitk::VtkPropRenderer::Translucent: this->MitkRenderTranslucentGeometry(renderer); break; case mitk::VtkPropRenderer::Overlay: this->MitkRenderOverlay(renderer); break; case mitk::VtkPropRenderer::Volumetric: this->MitkRenderVolumetricGeometry(renderer); break; } - - if (ls->m_ShaderProgram) - { - ls->m_ShaderProgram->Deactivate(); - } } bool mitk::VtkMapper::IsVtkBased() const { return true; } void mitk::VtkMapper::MitkRenderOverlay(BaseRenderer *renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) return; if (this->GetVtkProp(renderer)->GetVisibility()) { GetVtkProp(renderer)->RenderOverlay(renderer->GetVtkRenderer()); } } void mitk::VtkMapper::MitkRenderOpaqueGeometry(BaseRenderer *renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) return; if (this->GetVtkProp(renderer)->GetVisibility()) { GetVtkProp(renderer)->RenderOpaqueGeometry(renderer->GetVtkRenderer()); } } void mitk::VtkMapper::MitkRenderTranslucentGeometry(BaseRenderer *renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) return; if (this->GetVtkProp(renderer)->GetVisibility()) { GetVtkProp(renderer)->RenderTranslucentPolygonalGeometry(renderer->GetVtkRenderer()); } } -void mitk::VtkMapper::ApplyShaderProperties(mitk::BaseRenderer *renderer) -{ - IShaderRepository *shaderRepo = CoreServices::GetShaderRepository(); - if (shaderRepo) - { - VtkMapperLocalStorage *ls = m_VtkMapperLSH.GetLocalStorage(renderer); - shaderRepo->UpdateShaderProgram(ls->m_ShaderProgram, this->GetDataNode(), renderer); - } -} - void mitk::VtkMapper::MitkRenderVolumetricGeometry(BaseRenderer *renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) return; if (GetVtkProp(renderer)->GetVisibility()) { GetVtkProp(renderer)->RenderVolumetricGeometry(renderer->GetVtkRenderer()); } } bool mitk::VtkMapper::HasVtkProp(const vtkProp *prop, BaseRenderer *renderer) { vtkProp *myProp = this->GetVtkProp(renderer); // TODO: check if myProp is a vtkAssembly and if so, check if prop is contained in its leafs return (prop == myProp); } void mitk::VtkMapper::SetVtkMapperImmediateModeRendering(vtkMapper *mapper) { if (mapper) mapper->SetImmediateModeRendering(mitk::VtkPropRenderer::useImmediateModeRendering()); } void mitk::VtkMapper::UpdateVtkTransform(mitk::BaseRenderer *renderer) { vtkLinearTransform *vtktransform = GetDataNode()->GetVtkTransform(this->GetTimestep()); vtkProp3D *prop = dynamic_cast(GetVtkProp(renderer)); if (prop) prop->SetUserTransform(vtktransform); } void mitk::VtkMapper::ApplyColorAndOpacityProperties(BaseRenderer *renderer, vtkActor *actor) { float rgba[4] = {1.0f, 1.0f, 1.0f, 1.0f}; DataNode *node = GetDataNode(); // check for color prop and use it for rendering if it exists node->GetColor(rgba, renderer, "color"); // check for opacity prop and use it for rendering if it exists node->GetOpacity(rgba[3], renderer, "opacity"); double drgba[4] = {rgba[0], rgba[1], rgba[2], rgba[3]}; actor->GetProperty()->SetColor(drgba); actor->GetProperty()->SetOpacity(drgba[3]); } diff --git a/Modules/Core/src/Rendering/vtkMitkLevelWindowFilter.cpp b/Modules/Core/src/Rendering/vtkMitkLevelWindowFilter.cpp index e95629279c..1fca3768d1 100644 --- a/Modules/Core/src/Rendering/vtkMitkLevelWindowFilter.cpp +++ b/Modules/Core/src/Rendering/vtkMitkLevelWindowFilter.cpp @@ -1,589 +1,589 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "vtkMitkLevelWindowFilter.h" #include "vtkObjectFactory.h" #include #include #include #include #include #include #include #include // used for acos etc. #include // used for PI #include #include static const double PI = itk::Math::pi; vtkStandardNewMacro(vtkMitkLevelWindowFilter); vtkMitkLevelWindowFilter::vtkMitkLevelWindowFilter() : m_LookupTable(nullptr), m_OpacityFunction(nullptr), m_MinOpacity(0.0), m_MaxOpacity(255.0) { // MITK_INFO << "mitk level/window filter uses " << GetNumberOfThreads() << " thread(s)"; } vtkMitkLevelWindowFilter::~vtkMitkLevelWindowFilter() { } -unsigned long int vtkMitkLevelWindowFilter::GetMTime() +vtkMTimeType vtkMitkLevelWindowFilter::GetMTime() { - unsigned long mTime = this->vtkObject::GetMTime(); - unsigned long time; + vtkMTimeType mTime = this->vtkObject::GetMTime(); + vtkMTimeType time; if (this->m_LookupTable != nullptr) { time = this->m_LookupTable->GetMTime(); mTime = (time > mTime ? time : mTime); } return mTime; } void vtkMitkLevelWindowFilter::SetLookupTable(vtkScalarsToColors *lookupTable) { if (m_LookupTable != lookupTable) { m_LookupTable = lookupTable; this->Modified(); } } vtkScalarsToColors *vtkMitkLevelWindowFilter::GetLookupTable() { return m_LookupTable; } void vtkMitkLevelWindowFilter::SetOpacityPiecewiseFunction(vtkPiecewiseFunction *opacityFunction) { if (m_OpacityFunction != opacityFunction) { m_OpacityFunction = opacityFunction; this->Modified(); } } // This code was copied from the iil. The template works only for float and double. // Internal method which should never be used anywhere else and should not be in th header. // Convert color pixels from (R,G,B) to (H,S,I). // Reference: "Digital Image Processing, 2nd. edition", R. Gonzalez and R. Woods. Prentice Hall, 2002. template void RGBtoHSI(T *RGB, T *HSI) { T R = RGB[0], G = RGB[1], B = RGB[2], nR = (R < 0 ? 0 : (R > 255 ? 255 : R)) / 255, nG = (G < 0 ? 0 : (G > 255 ? 255 : G)) / 255, nB = (B < 0 ? 0 : (B > 255 ? 255 : B)) / 255, m = nR < nG ? (nR < nB ? nR : nB) : (nG < nB ? nG : nB), theta = (T)(std::acos(0.5f * ((nR - nG) + (nR - nB)) / std::sqrt(std::pow(nR - nG, 2) + (nR - nB) * (nG - nB))) * 180 / PI), sum = nR + nG + nB; T H = 0, S = 0, I = 0; if (theta > 0) H = (nB <= nG) ? theta : 360 - theta; if (sum > 0) S = 1 - 3 / sum * m; I = sum / 3; HSI[0] = (T)H; HSI[1] = (T)S; HSI[2] = (T)I; } // This code was copied from the iil. The template works only for float and double. // Internal method which should never be used anywhere else and should not be in th header. // Convert color pixels from (H,S,I) to (R,G,B). template void HSItoRGB(T *HSI, T *RGB) { T H = (T)HSI[0], S = (T)HSI[1], I = (T)HSI[2], a = I * (1 - S), R = 0, G = 0, B = 0; if (H < 120) { B = a; R = (T)(I * (1 + S * std::cos(H * PI / 180) / std::cos((60 - H) * PI / 180))); G = 3 * I - (R + B); } else if (H < 240) { H -= 120; R = a; G = (T)(I * (1 + S * std::cos(H * PI / 180) / std::cos((60 - H) * PI / 180))); B = 3 * I - (R + G); } else { H -= 240; G = a; B = (T)(I * (1 + S * std::cos(H * PI / 180) / std::cos((60 - H) * PI / 180))); R = 3 * I - (G + B); } R *= 255; G *= 255; B *= 255; RGB[0] = (T)(R < 0 ? 0 : (R > 255 ? 255 : R)); RGB[1] = (T)(G < 0 ? 0 : (G > 255 ? 255 : G)); RGB[2] = (T)(B < 0 ? 0 : (B > 255 ? 255 : B)); } // Internal method which should never be used anywhere else and should not be in th header. //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. template void vtkApplyLookupTableOnRGBA(vtkMitkLevelWindowFilter *self, vtkImageData *inData, vtkImageData *outData, int outExt[6], double *clippingBounds, T *) { vtkImageIterator inputIt(inData, outExt); vtkImageIterator outputIt(outData, outExt); vtkLookupTable *lookupTable; const int maxC = inData->GetNumberOfScalarComponents(); double tableRange[2]; lookupTable = dynamic_cast(self->GetLookupTable()); lookupTable->GetTableRange(tableRange); // parameters for RGB level window const double scale = (tableRange[1] - tableRange[0] > 0 ? 255.0 / (tableRange[1] - tableRange[0]) : 0.0); const double bias = tableRange[0] * scale; // parameters for opaque level window const double scaleOpac = (self->GetMaxOpacity() - self->GetMinOpacity() > 0 ? 255.0 / (self->GetMaxOpacity() - self->GetMinOpacity()) : 0.0); const double biasOpac = self->GetMinOpacity() * scaleOpac; int y = outExt[2]; // Loop through ouput pixels while (!outputIt.IsAtEnd()) { T *inputSI = inputIt.BeginSpan(); T *outputSI = outputIt.BeginSpan(); T *outputSIEnd = outputIt.EndSpan(); if (y >= clippingBounds[2] && y < clippingBounds[3]) { int x = outExt[0]; while (outputSI != outputSIEnd) { if (x >= clippingBounds[0] && x < clippingBounds[1]) { double rgb[3], alpha, hsi[3]; // level/window mechanism for intensity in HSI space rgb[0] = static_cast(*inputSI); inputSI++; rgb[1] = static_cast(*inputSI); inputSI++; rgb[2] = static_cast(*inputSI); inputSI++; RGBtoHSI(rgb, hsi); hsi[2] = hsi[2] * 255.0 * scale - bias; hsi[2] = (hsi[2] > 255.0 ? 255 : (hsi[2] < 0.0 ? 0 : hsi[2])); hsi[2] /= 255.0; HSItoRGB(hsi, rgb); *outputSI = static_cast(rgb[0]); outputSI++; *outputSI = static_cast(rgb[1]); outputSI++; *outputSI = static_cast(rgb[2]); outputSI++; unsigned char finalAlpha = 255; // RGBA case if (maxC >= 4) { // level/window mechanism for opacity alpha = static_cast(*inputSI); inputSI++; alpha = alpha * scaleOpac - biasOpac; if (alpha > 255.0) { alpha = 255.0; } else if (alpha < 0.0) { alpha = 0.0; } finalAlpha = static_cast(alpha); for (int c = 4; c < maxC; c++) inputSI++; } *outputSI = static_cast(finalAlpha); outputSI++; } else { inputSI += maxC; *outputSI = 0; outputSI++; *outputSI = 0; outputSI++; *outputSI = 0; outputSI++; *outputSI = 0; outputSI++; } x++; } } else { while (outputSI != outputSIEnd) { *outputSI = 0; outputSI++; *outputSI = 0; outputSI++; *outputSI = 0; outputSI++; *outputSI = 0; outputSI++; } } inputIt.NextSpan(); outputIt.NextSpan(); y++; } } // Internal method which should never be used anywhere else and should not be in th header. //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. template void vtkApplyLookupTableOnScalarsFast( vtkMitkLevelWindowFilter *self, vtkImageData *inData, vtkImageData *outData, int outExt[6], T *) { vtkImageIterator inputIt(inData, outExt); vtkImageIterator outputIt(outData, outExt); double tableRange[2]; // access vtkLookupTable vtkLookupTable *lookupTable = dynamic_cast(self->GetLookupTable()); lookupTable->GetTableRange(tableRange); // access elements of the vtkLookupTable const int *realLookupTable = reinterpret_cast(lookupTable->GetTable()->GetPointer(0)); int maxIndex = lookupTable->GetNumberOfColors() - 1; const float scale = (tableRange[1] - tableRange[0] > 0 ? (maxIndex + 1) / (tableRange[1] - tableRange[0]) : 0.0); // ensuring that starting point is zero float bias = -tableRange[0] * scale; // due to later conversion to int for rounding bias += 0.5f; // Loop through ouput pixels while (!outputIt.IsAtEnd()) { unsigned char *outputSI = outputIt.BeginSpan(); unsigned char *outputSIEnd = outputIt.EndSpan(); T *inputSI = inputIt.BeginSpan(); while (outputSI != outputSIEnd) { // map to an index int idx = static_cast(*inputSI * scale + bias); if (idx < 0) idx = 0; else if (idx > maxIndex) idx = maxIndex; *reinterpret_cast(outputSI) = realLookupTable[idx]; inputSI++; outputSI += 4; } inputIt.NextSpan(); outputIt.NextSpan(); } } // Internal method which should never be used anywhere else and should not be in th header. //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. template void vtkApplyLookupTableOnScalars(vtkMitkLevelWindowFilter *self, vtkImageData *inData, vtkImageData *outData, int outExt[6], double *clippingBounds, T *) { vtkImageIterator inputIt(inData, outExt); vtkImageIterator outputIt(outData, outExt); vtkScalarsToColors *lookupTable = self->GetLookupTable(); int y = outExt[2]; // Loop through ouput pixels while (!outputIt.IsAtEnd()) { unsigned char *outputSI = outputIt.BeginSpan(); unsigned char *outputSIEnd = outputIt.EndSpan(); // do we iterate over the inner vertical clipping bounds if (y >= clippingBounds[2] && y < clippingBounds[3]) { T *inputSI = inputIt.BeginSpan(); int x = outExt[0]; while (outputSI != outputSIEnd) { // is this pixel within horizontal clipping bounds if (x >= clippingBounds[0] && x < clippingBounds[1]) { // fetching original value double grayValue = static_cast(*inputSI); // applying lookuptable - copy the 4 (RGBA) chars as a single int *reinterpret_cast(outputSI) = *reinterpret_cast(lookupTable->MapValue(grayValue)); } else { // outer horizontal clipping bounds - write a transparent RGBA pixel as a single int *reinterpret_cast(outputSI) = 0; } inputSI++; outputSI += 4; x++; } } else { // outer vertical clipping bounds - write a transparent RGBA line as ints while (outputSI != outputSIEnd) { *reinterpret_cast(outputSI) = 0; outputSI += 4; } } inputIt.NextSpan(); outputIt.NextSpan(); y++; } } // Internal method which should never be used anywhere else and should not be in th header. //---------------------------------------------------------------------------- // This templated function executes the filter for any type of data. template void vtkApplyLookupTableOnScalarsCTF(vtkMitkLevelWindowFilter *self, vtkImageData *inData, vtkImageData *outData, int outExt[6], double *clippingBounds, T *) { vtkImageIterator inputIt(inData, outExt); vtkImageIterator outputIt(outData, outExt); vtkColorTransferFunction *lookupTable = dynamic_cast(self->GetLookupTable()); vtkPiecewiseFunction *opacityFunction = self->GetOpacityPiecewiseFunction(); int y = outExt[2]; // Loop through ouput pixels while (!outputIt.IsAtEnd()) { unsigned char *outputSI = outputIt.BeginSpan(); unsigned char *outputSIEnd = outputIt.EndSpan(); // do we iterate over the inner vertical clipping bounds if (y >= clippingBounds[2] && y < clippingBounds[3]) { T *inputSI = inputIt.BeginSpan(); int x = outExt[0]; while (outputSI != outputSIEnd) { // is this pixel within horizontal clipping bounds if (x >= clippingBounds[0] && x < clippingBounds[1]) { // fetching original value double grayValue = static_cast(*inputSI); // applying directly colortransferfunction // because vtkColorTransferFunction::MapValue is not threadsafe double rgba[4]; lookupTable->GetColor(grayValue, rgba); // RGB mapping rgba[3] = 1.0; if (opacityFunction) rgba[3] = opacityFunction->GetValue(grayValue); // Alpha mapping for (int i = 0; i < 4; ++i) { outputSI[i] = static_cast(255.0 * rgba[i] + 0.5); } } else { // outer horizontal clipping bounds - write a transparent RGBA pixel as a single int *reinterpret_cast(outputSI) = 0; } inputSI++; outputSI += 4; x++; } } else { // outer vertical clipping bounds - write a transparent RGBA line as ints while (outputSI != outputSIEnd) { *reinterpret_cast(outputSI) = 0; outputSI += 4; } } inputIt.NextSpan(); outputIt.NextSpan(); y++; } } int vtkMitkLevelWindowFilter::RequestInformation(vtkInformation *request, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { vtkInformation *outInfo = outputVector->GetInformationObject(0); // do nothing except copy scalar type info this->CopyInputArrayAttributesToOutput(request, inputVector, outputVector); vtkDataObject::SetPointDataActiveScalarInfo(outInfo, VTK_UNSIGNED_CHAR, 4); return 1; } // Method to run the filter in different threads. void vtkMitkLevelWindowFilter::ThreadedExecute(vtkImageData *inData, vtkImageData *outData, int extent[6], int /*id*/) { if (inData->GetNumberOfScalarComponents() > 2) { switch (inData->GetScalarType()) { vtkTemplateMacro( vtkApplyLookupTableOnRGBA(this, inData, outData, extent, m_ClippingBounds, static_cast(nullptr))); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } else { bool dontClip = extent[2] >= m_ClippingBounds[2] && extent[3] <= m_ClippingBounds[3] && extent[0] >= m_ClippingBounds[0] && extent[1] <= m_ClippingBounds[1]; if (this->GetLookupTable()) this->GetLookupTable()->Build(); vtkLookupTable *vlt = dynamic_cast(this->GetLookupTable()); vtkColorTransferFunction *ctf = dynamic_cast(this->GetLookupTable()); bool linearLookupTable = vlt && vlt->GetScale() == VTK_SCALE_LINEAR; bool useFast = dontClip && linearLookupTable; if (ctf) { switch (inData->GetScalarType()) { vtkTemplateMacro(vtkApplyLookupTableOnScalarsCTF( this, inData, outData, extent, m_ClippingBounds, static_cast(nullptr))); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } else if (useFast) { switch (inData->GetScalarType()) { vtkTemplateMacro( vtkApplyLookupTableOnScalarsFast(this, inData, outData, extent, static_cast(nullptr))); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } else { switch (inData->GetScalarType()) { vtkTemplateMacro(vtkApplyLookupTableOnScalars( this, inData, outData, extent, m_ClippingBounds, static_cast(nullptr))); default: vtkErrorMacro(<< "Execute: Unknown ScalarType"); return; } } } } // void vtkMitkLevelWindowFilter::ExecuteInformation( // vtkImageData *vtkNotUsed(inData), vtkImageData *vtkNotUsed(outData)) //{ //} void vtkMitkLevelWindowFilter::SetMinOpacity(double minOpacity) { m_MinOpacity = minOpacity; } inline double vtkMitkLevelWindowFilter::GetMinOpacity() const { return m_MinOpacity; } void vtkMitkLevelWindowFilter::SetMaxOpacity(double maxOpacity) { m_MaxOpacity = maxOpacity; } inline double vtkMitkLevelWindowFilter::GetMaxOpacity() const { return m_MaxOpacity; } void vtkMitkLevelWindowFilter::SetClippingBounds(double *bounds) // TODO does double[4] work?? { for (unsigned int i = 0; i < 4; ++i) m_ClippingBounds[i] = bounds[i]; } diff --git a/Modules/Core/src/mitkCoreActivator.cpp b/Modules/Core/src/mitkCoreActivator.cpp index ac2a072d41..785e45b8e9 100644 --- a/Modules/Core/src/mitkCoreActivator.cpp +++ b/Modules/Core/src/mitkCoreActivator.cpp @@ -1,457 +1,324 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCoreActivator.h" // File IO #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mitkDicomSeriesReaderService.h" #include "mitkLegacyFileWriterService.h" #include #include #include // Micro Services #include #include #include #include #include #include #include #include #include #include // ITK "injects" static initialization code for IO factories // via the itkImageIOFactoryRegisterManager.h header (which // is generated in the application library build directory). // To ensure that the code is called *before* the CppMicroServices // static initialization code (which triggers the Activator::Start // method), we include the ITK header here. #include void HandleMicroServicesMessages(us::MsgType type, const char *msg) { switch (type) { case us::DebugMsg: MITK_DEBUG << msg; break; case us::InfoMsg: MITK_INFO << msg; break; case us::WarningMsg: MITK_WARN << msg; break; case us::ErrorMsg: MITK_ERROR << msg; break; } } void AddMitkAutoLoadPaths(const std::string &programPath) { us::ModuleSettings::AddAutoLoadPath(programPath); #ifdef __APPLE__ // Walk up three directories since that is where the .dylib files are located // for build trees. std::string additionalPath = programPath; bool addPath = true; for (int i = 0; i < 3; ++i) { std::size_t index = additionalPath.find_last_of('/'); if (index != std::string::npos) { additionalPath = additionalPath.substr(0, index); } else { addPath = false; break; } } if (addPath) { us::ModuleSettings::AddAutoLoadPath(additionalPath); } #endif } -class ShaderRepositoryTracker : public us::ServiceTracker -{ -public: - ShaderRepositoryTracker() : Superclass(us::GetModuleContext()) {} - virtual void Close() override - { - us::GetModuleContext()->RemoveModuleListener(this, &ShaderRepositoryTracker::HandleModuleEvent); - Superclass::Close(); - } - - virtual void Open() override - { - us::GetModuleContext()->AddModuleListener(this, &ShaderRepositoryTracker::HandleModuleEvent); - Superclass::Open(); - } - -private: - typedef us::ServiceTracker Superclass; - - TrackedType AddingService(const ServiceReferenceType &reference) override - { - mitk::IShaderRepository *shaderRepo = Superclass::AddingService(reference); - if (shaderRepo) - { - // Add all existing shaders from modules to the new shader repository. - // If the shader repository is registered in a modules activator, the - // GetLoadedModules() function call below will also return the module - // which is currently registering the repository. The HandleModuleEvent - // method contains code to avoid double registrations due to a fired - // ModuleEvent::LOADED event after the activators Load() method finished. - std::vector modules = us::ModuleRegistry::GetLoadedModules(); - for (std::vector::const_iterator iter = modules.begin(), endIter = modules.end(); iter != endIter; - ++iter) - { - this->AddModuleShaderToRepository(*iter, shaderRepo); - } - - m_ShaderRepositories.push_back(shaderRepo); - } - return shaderRepo; - } - - void RemovedService(const ServiceReferenceType & /*reference*/, TrackedType tracked) override - { - m_ShaderRepositories.erase(std::remove(m_ShaderRepositories.begin(), m_ShaderRepositories.end(), tracked), - m_ShaderRepositories.end()); - } - - void HandleModuleEvent(const us::ModuleEvent moduleEvent) - { - if (moduleEvent.GetType() == us::ModuleEvent::LOADED) - { - std::vector shaderRepos; - for (std::map>>::const_iterator - shaderMapIter = m_ModuleIdToShaderIds.begin(), - shaderMapEndIter = m_ModuleIdToShaderIds.end(); - shaderMapIter != shaderMapEndIter; - ++shaderMapIter) - { - if (shaderMapIter->second.find(moduleEvent.GetModule()->GetModuleId()) == shaderMapIter->second.end()) - { - shaderRepos.push_back(shaderMapIter->first); - } - } - AddModuleShadersToRepositories(moduleEvent.GetModule(), shaderRepos); - } - else if (moduleEvent.GetType() == us::ModuleEvent::UNLOADED) - { - RemoveModuleShadersFromRepositories(moduleEvent.GetModule(), m_ShaderRepositories); - } - } - - void AddModuleShadersToRepositories(us::Module *module, const std::vector &shaderRepos) - { - // search and load shader files - std::vector shaderResources = module->FindResources("Shaders", "*.xml", true); - for (std::vector::iterator i = shaderResources.begin(); i != shaderResources.end(); ++i) - { - if (*i) - { - us::ModuleResourceStream rs(*i); - for (const auto &shaderRepo : shaderRepos) - { - int id = (shaderRepo)->LoadShader(rs, i->GetBaseName()); - if (id >= 0) - { - m_ModuleIdToShaderIds[shaderRepo][module->GetModuleId()].push_back(id); - } - } - rs.seekg(0, std::ios_base::beg); - } - } - } - - void AddModuleShaderToRepository(us::Module *module, mitk::IShaderRepository *shaderRepo) - { - std::vector shaderRepos; - shaderRepos.push_back(shaderRepo); - this->AddModuleShadersToRepositories(module, shaderRepos); - } - - void RemoveModuleShadersFromRepositories(us::Module *module, - const std::vector &shaderRepos) - { - for (const auto &shaderRepo : shaderRepos) - { - std::map> &moduleIdToShaderIds = m_ModuleIdToShaderIds[shaderRepo]; - std::map>::iterator shaderIdsIter = moduleIdToShaderIds.find(module->GetModuleId()); - if (shaderIdsIter != moduleIdToShaderIds.end()) - { - for (std::vector::iterator idIter = shaderIdsIter->second.begin(); idIter != shaderIdsIter->second.end(); - ++idIter) - { - (shaderRepo)->UnloadShader(*idIter); - } - moduleIdToShaderIds.erase(shaderIdsIter); - } - } - } - -private: - // Maps to each shader repository a map containing module ids and related - // shader registration ids - std::map>> m_ModuleIdToShaderIds; - std::vector m_ShaderRepositories; -}; - class FixedNiftiImageIO : public itk::NiftiImageIO { public: /** Standard class typedefs. */ typedef FixedNiftiImageIO Self; typedef itk::NiftiImageIO Superclass; typedef itk::SmartPointer Pointer; /** Method for creation through the object factory. */ itkNewMacro(Self) /** Run-time type information (and related methods). */ itkTypeMacro(FixedNiftiImageIO, Superclass) virtual bool SupportsDimension(unsigned long dim) override { return dim > 1 && dim < 5; } }; void MitkCoreActivator::Load(us::ModuleContext *context) { // Handle messages from CppMicroServices us::installMsgHandler(HandleMicroServicesMessages); this->m_Context = context; // Add the current application directory to the auto-load paths. // This is useful for third-party executables. std::string programPath = mitk::IOUtil::GetProgramPath(); if (programPath.empty()) { MITK_WARN << "Could not get the program path."; } else { AddMitkAutoLoadPaths(programPath); } - m_ShaderRepositoryTracker.reset(new ShaderRepositoryTracker); - // m_RenderingManager = mitk::RenderingManager::New(); // context->RegisterService(renderingManager.GetPointer()); m_PlanePositionManager.reset(new mitk::PlanePositionManagerService); context->RegisterService(m_PlanePositionManager.get()); m_PropertyAliases.reset(new mitk::PropertyAliases); context->RegisterService(m_PropertyAliases.get()); m_PropertyDescriptions.reset(new mitk::PropertyDescriptions); context->RegisterService(m_PropertyDescriptions.get()); m_PropertyExtensions.reset(new mitk::PropertyExtensions); context->RegisterService(m_PropertyExtensions.get()); m_PropertyFilters.reset(new mitk::PropertyFilters); context->RegisterService(m_PropertyFilters.get()); m_PropertyPersistence.reset(new mitk::PropertyPersistence); context->RegisterService(m_PropertyPersistence.get()); m_MimeTypeProvider.reset(new mitk::MimeTypeProvider); m_MimeTypeProvider->Start(); m_MimeTypeProviderReg = context->RegisterService(m_MimeTypeProvider.get()); this->RegisterDefaultMimeTypes(); this->RegisterItkReaderWriter(); this->RegisterVtkReaderWriter(); // Add custom Reader / Writer Services m_FileReaders.push_back(new mitk::PointSetReaderService()); m_FileWriters.push_back(new mitk::PointSetWriterService()); m_FileReaders.push_back(new mitk::GeometryDataReaderService()); m_FileWriters.push_back(new mitk::GeometryDataWriterService()); m_FileReaders.push_back(new mitk::DicomSeriesReaderService()); m_FileReaders.push_back(new mitk::RawImageFileReaderService()); - m_ShaderRepositoryTracker->Open(); - /* There IS an option to exchange ALL vtkTexture instances against vtkNeverTranslucentTextureFactory. This code is left here as a reminder, just in case we might need to do that some time. vtkNeverTranslucentTextureFactory* textureFactory = vtkNeverTranslucentTextureFactory::New(); vtkObjectFactory::RegisterFactory( textureFactory ); textureFactory->Delete(); */ this->RegisterLegacyWriter(); } void MitkCoreActivator::Unload(us::ModuleContext *) { for (auto &elem : m_FileReaders) { delete elem; } for (auto &elem : m_FileWriters) { delete elem; } for (auto &elem : m_FileIOs) { delete elem; } for (auto &elem : m_LegacyWriters) { delete elem; } // The mitk::ModuleContext* argument of the Unload() method // will always be 0 for the Mitk library. It makes no sense // to use it at this stage anyway, since all libraries which // know about the module system have already been unloaded. // we need to close the internal service tracker of the // MimeTypeProvider class here. Otherwise it // would hold on to the ModuleContext longer than it is // actually valid. m_MimeTypeProviderReg.Unregister(); m_MimeTypeProvider->Stop(); for (std::vector::const_iterator mimeTypeIter = m_DefaultMimeTypes.begin(), iterEnd = m_DefaultMimeTypes.end(); mimeTypeIter != iterEnd; ++mimeTypeIter) { delete *mimeTypeIter; } - - m_ShaderRepositoryTracker->Close(); } void MitkCoreActivator::RegisterDefaultMimeTypes() { // Register some default mime-types std::vector mimeTypes = mitk::IOMimeTypes::Get(); for (std::vector::const_iterator mimeTypeIter = mimeTypes.begin(), iterEnd = mimeTypes.end(); mimeTypeIter != iterEnd; ++mimeTypeIter) { m_DefaultMimeTypes.push_back(*mimeTypeIter); m_Context->RegisterService(m_DefaultMimeTypes.back()); } } void MitkCoreActivator::RegisterItkReaderWriter() { std::list allobjects = itk::ObjectFactoryBase::CreateAllInstance("itkImageIOBase"); for (auto &allobject : allobjects) { itk::ImageIOBase *io = dynamic_cast(allobject.GetPointer()); // NiftiImageIO does not provide a correct "SupportsDimension()" methods // and the supported read/write extensions are not ordered correctly if (dynamic_cast(io)) continue; // Use a custom mime-type for GDCMImageIO below if (dynamic_cast(allobject.GetPointer())) { // MITK provides its own DICOM reader (which internally uses GDCMImageIO). continue; } if (io) { m_FileIOs.push_back(new mitk::ItkImageIO(io)); } else { MITK_WARN << "Error ImageIO factory did not return an ImageIOBase: " << (allobject)->GetNameOfClass(); } } FixedNiftiImageIO::Pointer itkNiftiIO = FixedNiftiImageIO::New(); mitk::ItkImageIO *niftiIO = new mitk::ItkImageIO(mitk::IOMimeTypes::NIFTI_MIMETYPE(), itkNiftiIO.GetPointer(), 0); m_FileIOs.push_back(niftiIO); } void MitkCoreActivator::RegisterVtkReaderWriter() { m_FileIOs.push_back(new mitk::SurfaceVtkXmlIO()); m_FileIOs.push_back(new mitk::SurfaceStlIO()); m_FileIOs.push_back(new mitk::SurfaceVtkLegacyIO()); m_FileIOs.push_back(new mitk::ImageVtkXmlIO()); m_FileIOs.push_back(new mitk::ImageVtkLegacyIO()); } void MitkCoreActivator::RegisterLegacyWriter() { std::list allobjects = itk::ObjectFactoryBase::CreateAllInstance("IOWriter"); for (std::list::iterator i = allobjects.begin(); i != allobjects.end(); ++i) { mitk::FileWriter::Pointer io = dynamic_cast(i->GetPointer()); if (io) { std::string description = std::string("Legacy ") + io->GetNameOfClass() + " Writer"; mitk::IFileWriter *writer = new mitk::LegacyFileWriterService(io, description); m_LegacyWriters.push_back(writer); } else { MITK_ERROR << "Error IOWriter override is not of type mitk::FileWriter: " << (*i)->GetNameOfClass() << std::endl; } } } US_EXPORT_MODULE_ACTIVATOR(MitkCoreActivator) // Call CppMicroservices initialization code at the end of the file. // This especially ensures that VTK object factories have already // been registered (VTK initialization code is injected by implicitly // include VTK header files at the top of this file). US_INITIALIZE_MODULE diff --git a/Modules/Core/src/mitkCoreActivator.h b/Modules/Core/src/mitkCoreActivator.h index a6c274a997..7cdbce2b57 100644 --- a/Modules/Core/src/mitkCoreActivator.h +++ b/Modules/Core/src/mitkCoreActivator.h @@ -1,86 +1,82 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKCOREACTIVATOR_H_ #define MITKCOREACTIVATOR_H_ // File IO #include #include #include -#include - #include #include #include #include #include #include #include // Micro Services #include #include #include #include #include /* * This is the module activator for the "Mitk" module. It registers core services * like ... */ class MitkCoreActivator : public us::ModuleActivator { public: void Load(us::ModuleContext *context) override; void Unload(us::ModuleContext *) override; private: void HandleModuleEvent(const us::ModuleEvent moduleEvent); void RegisterDefaultMimeTypes(); void RegisterItkReaderWriter(); void RegisterVtkReaderWriter(); void RegisterLegacyWriter(); - std::unique_ptr> m_ShaderRepositoryTracker; - // mitk::RenderingManager::Pointer m_RenderingManager; std::unique_ptr m_PlanePositionManager; std::unique_ptr m_PropertyAliases; std::unique_ptr m_PropertyDescriptions; std::unique_ptr m_PropertyExtensions; std::unique_ptr m_PropertyFilters; std::unique_ptr m_PropertyPersistence; std::unique_ptr m_MimeTypeProvider; // File IO std::vector m_FileReaders; std::vector m_FileWriters; std::vector m_FileIOs; std::vector m_LegacyWriters; std::vector m_DefaultMimeTypes; us::ServiceRegistration m_MimeTypeProviderReg; us::ModuleContext *m_Context; }; #endif // MITKCOREACTIVATOR_H_ diff --git a/Modules/Core/src/mitkCoreServices.cpp b/Modules/Core/src/mitkCoreServices.cpp index 827a650b88..030ce40ecd 100644 --- a/Modules/Core/src/mitkCoreServices.cpp +++ b/Modules/Core/src/mitkCoreServices.cpp @@ -1,134 +1,126 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkCoreServices.h" #include #include #include #include #include #include -#include #include #include #include #include #include #include namespace mitk { itk::SimpleFastMutexLock &s_ContextToServicesMapMutex() { static itk::SimpleFastMutexLock mutex; return mutex; } std::map> &s_ContextToServicesMap() { static std::map> serviceMap; return serviceMap; } template static S *GetCoreService(us::ModuleContext *context) { if (context == nullptr) context = us::GetModuleContext(); S *coreService = nullptr; us::ServiceReference serviceRef = context->GetServiceReference(); if (serviceRef) { coreService = context->GetService(serviceRef); } assert(coreService && "Asserting non-nullptr MITK core service"); { itk::MutexLockHolder l(s_ContextToServicesMapMutex()); s_ContextToServicesMap()[context].insert(std::make_pair(coreService, serviceRef)); } return coreService; } - IShaderRepository *CoreServices::GetShaderRepository() - { - static us::ServiceTracker tracker(us::GetModuleContext()); - tracker.Open(); - return tracker.GetService(); - } - IPropertyAliases *CoreServices::GetPropertyAliases(us::ModuleContext *context) { return GetCoreService(context); } IPropertyDescriptions *CoreServices::GetPropertyDescriptions(us::ModuleContext *context) { return GetCoreService(context); } IPropertyExtensions *CoreServices::GetPropertyExtensions(us::ModuleContext *context) { return GetCoreService(context); } IPropertyFilters *CoreServices::GetPropertyFilters(us::ModuleContext *context) { return GetCoreService(context); } IPropertyPersistence *CoreServices::GetPropertyPersistence(us::ModuleContext *context) { return GetCoreService(context); } IMimeTypeProvider *CoreServices::GetMimeTypeProvider(us::ModuleContext *context) { return GetCoreService(context); } bool CoreServices::Unget(us::ModuleContext *context, const std::string & /*interfaceId*/, void *service) { bool success = false; itk::MutexLockHolder l(s_ContextToServicesMapMutex()); std::map>::iterator iter = s_ContextToServicesMap().find(context); if (iter != s_ContextToServicesMap().end()) { std::map::iterator iter2 = iter->second.find(service); if (iter2 != iter->second.end()) { us::ServiceReferenceU serviceRef = iter2->second; if (serviceRef) { success = context->UngetService(serviceRef); if (success) { iter->second.erase(iter2); } } } } return success; } } diff --git a/Modules/Core/test/files.cmake b/Modules/Core/test/files.cmake index a79faa1555..ccf17821cc 100644 --- a/Modules/Core/test/files.cmake +++ b/Modules/Core/test/files.cmake @@ -1,200 +1,199 @@ # tests with no extra command line parameter set(MODULE_TESTS # IMPORTANT: If you plan to deactivate / comment out a test please write a bug number to the commented out line of code. # # Example: #mitkMyTest #this test is commented out because of bug 12345 # # It is important that the bug is open and that the test will be activated again before the bug is closed. This assures that # no test is forgotten after it was commented out. If there is no bug for your current problem, please add a new one and # mark it as critical. ################## DISABLED TESTS ################################################# #mitkAbstractTransformGeometryTest.cpp #seems as tested class mitkExternAbstractTransformGeometry doesnt exist any more #mitkStateMachineContainerTest.cpp #rewrite test, indirect since no longer exported Bug 14529 #mitkRegistrationBaseTest.cpp #tested class mitkRegistrationBase doesn't exist any more #mitkSegmentationInterpolationTest.cpp #file doesn't exist! #mitkPipelineSmartPointerCorrectnessTest.cpp #file doesn't exist! #mitkITKThreadingTest.cpp #test outdated because itk::Semaphore was removed from ITK #mitkAbstractTransformPlaneGeometryTest.cpp #mitkVtkAbstractTransformPlaneGeometry doesn't exist any more #mitkTestUtilSharedLibrary.cpp #Linker problem with this test... #mitkTextOverlay2DSymbolsRenderingTest.cpp #Implementation of the tested feature is not finished yet. Ask Christoph or see bug 15104 for details. ################# RUNNING TESTS ################################################### mitkAccessByItkTest.cpp mitkCoreObjectFactoryTest.cpp mitkDataNodeTest.cpp mitkMaterialTest.cpp mitkActionTest.cpp mitkDispatcherTest.cpp mitkEnumerationPropertyTest.cpp mitkFileReaderRegistryTest.cpp #mitkFileWriterRegistryTest.cpp mitkFloatToStringTest.cpp mitkGenericPropertyTest.cpp mitkGeometry3DTest.cpp mitkGeometry3DEqualTest.cpp mitkGeometryDataIOTest.cpp mitkGeometryDataToSurfaceFilterTest.cpp mitkImageCastTest.cpp mitkImageEqualTest.cpp mitkImageDataItemTest.cpp mitkImageGeneratorTest.cpp mitkIOUtilTest.cpp mitkBaseDataTest.cpp mitkImportItkImageTest.cpp mitkGrabItkImageMemoryTest.cpp mitkInstantiateAccessFunctionTest.cpp mitkLevelWindowTest.cpp mitkMessageTest.cpp mitkPixelTypeTest.cpp mitkPlaneGeometryTest.cpp mitkPointSetTest.cpp mitkPointSetEqualTest.cpp mitkPointSetFileIOTest.cpp mitkPointSetOnEmptyTest.cpp mitkPointSetLocaleTest.cpp mitkPointSetWriterTest.cpp mitkPointSetReaderTest.cpp mitkPointSetPointOperationsTest.cpp mitkProgressBarTest.cpp mitkPropertyTest.cpp mitkPropertyListTest.cpp mitkPropertyPersistenceTest.cpp mitkPropertyPersistenceInfoTest.cpp mitkSlicedGeometry3DTest.cpp mitkSliceNavigationControllerTest.cpp mitkSurfaceTest.cpp mitkSurfaceEqualTest.cpp mitkSurfaceToSurfaceFilterTest.cpp mitkTimeGeometryTest.cpp mitkProportionalTimeGeometryTest.cpp mitkUndoControllerTest.cpp mitkVtkWidgetRenderingTest.cpp mitkVerboseLimitedLinearUndoTest.cpp mitkWeakPointerTest.cpp mitkTransferFunctionTest.cpp mitkStepperTest.cpp mitkRenderingManagerTest.cpp mitkCompositePixelValueToStringTest.cpp vtkMitkThickSlicesFilterTest.cpp mitkNodePredicateSourceTest.cpp mitkNodePredicateDataPropertyTest.cpp mitkVectorTest.cpp mitkClippedSurfaceBoundsCalculatorTest.cpp mitkExceptionTest.cpp mitkExtractSliceFilterTest.cpp mitkLogTest.cpp mitkImageDimensionConverterTest.cpp mitkLoggingAdapterTest.cpp mitkUIDGeneratorTest.cpp - mitkShaderRepositoryTest.cpp mitkPlanePositionManagerTest.cpp mitkAffineTransformBaseTest.cpp mitkPropertyAliasesTest.cpp mitkPropertyDescriptionsTest.cpp mitkPropertyExtensionsTest.cpp mitkPropertyFiltersTest.cpp mitkTinyXMLTest.cpp mitkRawImageFileReaderTest.cpp mitkInteractionEventTest.cpp mitkLookupTableTest.cpp mitkSTLFileReaderTest.cpp mitkPointTypeConversionTest.cpp mitkVectorTypeConversionTest.cpp mitkMatrixTypeConversionTest.cpp mitkArrayTypeConversionTest.cpp mitkSurfaceToImageFilterTest.cpp mitkBaseGeometryTest.cpp mitkImageToSurfaceFilterTest.cpp mitkEqualTest.cpp mitkLineTest.cpp mitkArbitraryTimeGeometryTest mitkItkImageIOTest.cpp mitkRotatedSlice4DTest.cpp mitkLevelWindowManagerCppUnitTest.cpp mitkVectorPropertyTest.cpp mitkTemporoSpatialStringPropertyTest.cpp mitkPropertyNameHelperTest.cpp mitkNodePredicateGeometryTest.cpp mitkPreferenceListReaderOptionsFunctorTest.cpp ) if(MITK_ENABLE_RENDERING_TESTING) set(MODULE_TESTS ${MODULE_TESTS} mitkPlaneGeometryDataMapper2DTest.cpp mitkPointSetDataInteractorTest.cpp #since mitkInteractionTestHelper is currently creating a vtkRenderWindow mitkSurfaceVtkMapper2DTest.cpp #new rendering test in CppUnit style mitkSurfaceVtkMapper2D3DTest.cpp # comparisons/consistency 2D/3D ) endif() # test with image filename as an extra command line parameter set(MODULE_IMAGE_TESTS mitkImageTimeSelectorTest.cpp #only runs on images mitkImageAccessorTest.cpp #only runs on images ) set(MODULE_SURFACE_TESTS mitkSurfaceVtkWriterTest.cpp #only runs on surfaces ) # list of images for which the tests are run set(MODULE_TESTIMAGE US4DCyl.nrrd Pic3D.nrrd Pic2DplusT.nrrd BallBinary30x30x30.nrrd Png2D-bw.png ) set(MODULE_TESTSURFACE binary.stl ball.stl ) set(MODULE_CUSTOM_TESTS mitkDataStorageTest.cpp mitkDicomSeriesReaderTest.cpp mitkDICOMLocaleTest.cpp mitkDataNodeTest.cpp mitkEventConfigTest.cpp mitkPointSetLocaleTest.cpp mitkImageTest.cpp mitkImageVtkMapper2DTest.cpp mitkImageVtkMapper2DLevelWindowTest.cpp mitkImageVtkMapper2DOpacityTest.cpp mitkImageVtkMapper2DResliceInterpolationPropertyTest.cpp mitkImageVtkMapper2DColorTest.cpp mitkImageVtkMapper2DSwivelTest.cpp mitkImageVtkMapper2DTransferFunctionTest.cpp mitkImageVtkMapper2DOpacityTransferFunctionTest.cpp mitkImageVtkMapper2DLookupTableTest.cpp mitkSurfaceVtkMapper3DTest mitkSurfaceVtkMapper3DTexturedSphereTest.cpp mitkVolumeCalculatorTest.cpp mitkLevelWindowManagerTest.cpp mitkPointSetVtkMapper2DTest.cpp mitkPointSetVtkMapper2DImageTest.cpp mitkPointSetVtkMapper2DGlyphTypeTest.cpp mitkPointSetVtkMapper2DTransformedPointsTest.cpp mitkVTKRenderWindowSizeTest.cpp mitkMultiComponentImageDataComparisonFilterTest.cpp mitkImageToItkTest.cpp mitkImageSliceSelectorTest.cpp mitkSurfaceDepthPeelingTest.cpp ) # Currently not working on windows because of a rendering timing issue # see bug 18083 for details if(NOT WIN32) set(MODULE_CUSTOM_TESTS ${MODULE_CUSTOM_TESTS} mitkSurfaceDepthSortingTest.cpp) endif() set(RESOURCE_FILES Interactions/AddAndRemovePoints.xml Interactions/globalConfig.xml Interactions/StatemachineTest.xml Interactions/StatemachineConfigTest.xml ) diff --git a/Modules/Core/test/mitkShaderRepositoryTest.cpp b/Modules/Core/test/mitkShaderRepositoryTest.cpp deleted file mode 100644 index 2a9ec98641..0000000000 --- a/Modules/Core/test/mitkShaderRepositoryTest.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkIShaderRepository.h" - -#include "usGetModuleContext.h" -#include "usModuleContext.h" -#include "usServiceReference.h" - -#include "mitkTestingMacros.h" - -#include - -int mitkShaderRepositoryTest(int /*argc*/, char * /*argv*/ []) -{ - MITK_TEST_BEGIN("ShaderRepository") - - us::ModuleContext *context = us::GetModuleContext(); - us::ServiceReference serviceRef = context->GetServiceReference(); - MITK_TEST_CONDITION_REQUIRED(serviceRef, "IShaderRepository service ref") - - mitk::IShaderRepository *shaderRepo = context->GetService(serviceRef); - MITK_TEST_CONDITION_REQUIRED(shaderRepo, "Check non-empty IShaderRepositry") - - mitk::IShaderRepository::Shader::Pointer shader = shaderRepo->GetShader("mitkShaderLighting"); - MITK_TEST_CONDITION_REQUIRED(shader.IsNotNull(), "Non-null mitkShaderLighting shader") - - MITK_TEST_CONDITION(shader->GetName() == "mitkShaderLighting", "Shader name") - MITK_TEST_CONDITION(!shader->GetMaterialXml().empty(), "Shader content") - - const std::string testShader = - "" - "" - "" - "" - ""; - - const std::size_t shaderCount = shaderRepo->GetShaders().size(); - - std::stringstream testShaderStream(testShader); - const std::string testShaderName = "SmoothPlastic"; - int id = shaderRepo->LoadShader(testShaderStream, testShaderName); - MITK_TEST_CONDITION_REQUIRED(id > -1, "New shader id") - MITK_TEST_CONDITION(shaderRepo->GetShaders().size() == shaderCount + 1, "Shader count") - mitk::IShaderRepository::Shader::Pointer shader2 = shaderRepo->GetShader(testShaderName); - MITK_TEST_CONDITION_REQUIRED(shader2.IsNotNull(), "Non-null shader") - MITK_TEST_CONDITION(shader2->GetId() == id, "Shader id") - MITK_TEST_CONDITION(shader2->GetName() == testShaderName, "Shader name") - mitk::IShaderRepository::Shader::Pointer shader3 = shaderRepo->GetShader(id); - MITK_TEST_CONDITION_REQUIRED(shader3.IsNotNull(), "Non-null shader") - MITK_TEST_CONDITION(shader3->GetId() == id, "Shader id") - MITK_TEST_CONDITION(shader3->GetName() == testShaderName, "Shader name") - - MITK_TEST_CONDITION_REQUIRED(shaderRepo->UnloadShader(id), "Unload shader") - MITK_TEST_CONDITION(shaderRepo->GetShader(testShaderName).IsNull(), "Null shader") - MITK_TEST_CONDITION(shaderRepo->GetShader(id).IsNull(), "Null shader") - - MITK_TEST_END() -} diff --git a/Modules/DicomRT/src/mitkDoseImageVtkMapper2D.cpp b/Modules/DicomRT/src/mitkDoseImageVtkMapper2D.cpp index 4df91056d9..078253370d 100644 --- a/Modules/DicomRT/src/mitkDoseImageVtkMapper2D.cpp +++ b/Modules/DicomRT/src/mitkDoseImageVtkMapper2D.cpp @@ -1,1106 +1,1167 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ -//MITK +// MITK +#include "mitkImageStatisticsHolder.h" +#include "mitkPlaneClipping.h" +#include "mitkPropertyNameHelper.h" #include #include #include #include #include #include #include #include #include #include #include +#include #include #include -#include #include #include -#include "mitkImageStatisticsHolder.h" -#include "mitkPlaneClipping.h" -#include "mitkPropertyNameHelper.h" -//MITK Rendering +// MITK Rendering #include "mitkDoseImageVtkMapper2D.h" -#include "vtkMitkThickSlicesFilter.h" #include "vtkMitkLevelWindowFilter.h" +#include "vtkMitkThickSlicesFilter.h" #include "vtkNeverTranslucentTexture.h" -//VTK +// VTK #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include -//ITK +// ITK #include mitk::DoseImageVtkMapper2D::DoseImageVtkMapper2D() { } mitk::DoseImageVtkMapper2D::~DoseImageVtkMapper2D() { - //The 3D RW Mapper (PlaneGeometryDataVtkMapper3D) is listening to this event, - //in order to delete the images from the 3D RW. - this->InvokeEvent( itk::DeleteEvent() ); + // The 3D RW Mapper (PlaneGeometryDataVtkMapper3D) is listening to this event, + // in order to delete the images from the 3D RW. + this->InvokeEvent(itk::DeleteEvent()); } -//set the two points defining the textured plane according to the dimension and spacing -void mitk::DoseImageVtkMapper2D::GeneratePlane(mitk::BaseRenderer* renderer, double planeBounds[6]) +// set the two points defining the textured plane according to the dimension and spacing +void mitk::DoseImageVtkMapper2D::GeneratePlane(mitk::BaseRenderer *renderer, double planeBounds[6]) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); float depth = this->CalculateLayerDepth(renderer); - //Set the origin to (xMin; yMin; depth) of the plane. This is necessary for obtaining the correct - //plane size in crosshair rotation and swivel mode. + // Set the origin to (xMin; yMin; depth) of the plane. This is necessary for obtaining the correct + // plane size in crosshair rotation and swivel mode. localStorage->m_Plane->SetOrigin(planeBounds[0], planeBounds[2], depth); - //These two points define the axes of the plane in combination with the origin. - //Point 1 is the x-axis and point 2 the y-axis. - //Each plane is transformed according to the view (axial, coronal and saggital) afterwards. - localStorage->m_Plane->SetPoint1(planeBounds[1] , planeBounds[2], depth); //P1: (xMax, yMin, depth) - localStorage->m_Plane->SetPoint2(planeBounds[0], planeBounds[3], depth); //P2: (xMin, yMax, depth) + // These two points define the axes of the plane in combination with the origin. + // Point 1 is the x-axis and point 2 the y-axis. + // Each plane is transformed according to the view (axial, coronal and saggital) afterwards. + localStorage->m_Plane->SetPoint1(planeBounds[1], planeBounds[2], depth); // P1: (xMax, yMin, depth) + localStorage->m_Plane->SetPoint2(planeBounds[0], planeBounds[3], depth); // P2: (xMin, yMax, depth) } -float mitk::DoseImageVtkMapper2D::CalculateLayerDepth(mitk::BaseRenderer* renderer) +float mitk::DoseImageVtkMapper2D::CalculateLayerDepth(mitk::BaseRenderer *renderer) { - //get the clipping range to check how deep into z direction we can render images + // get the clipping range to check how deep into z direction we can render images double maxRange = renderer->GetVtkRenderer()->GetActiveCamera()->GetClippingRange()[1]; - //Due to a VTK bug, we cannot use the whole clipping range. /100 is empirically determined - float depth = -maxRange*0.01; // divide by 100 + // Due to a VTK bug, we cannot use the whole clipping range. /100 is empirically determined + float depth = -maxRange * 0.01; // divide by 100 int layer = 0; - GetDataNode()->GetIntProperty( "layer", layer, renderer); - //add the layer property for each image to render images with a higher layer on top of the others - depth += layer*10; //*10: keep some room for each image (e.g. for QBalls in between) - if(depth > 0.0f) { + GetDataNode()->GetIntProperty("layer", layer, renderer); + // add the layer property for each image to render images with a higher layer on top of the others + depth += layer * 10; //*10: keep some room for each image (e.g. for QBalls in between) + if (depth > 0.0f) + { depth = 0.0f; MITK_WARN << "Layer value exceeds clipping range. Set to minimum instead."; } return depth; } -const mitk::Image* mitk::DoseImageVtkMapper2D::GetInput( void ) +const mitk::Image *mitk::DoseImageVtkMapper2D::GetInput(void) { - return static_cast< const mitk::Image * >( GetDataNode()->GetData() ); + return static_cast(GetDataNode()->GetData()); } -vtkProp* mitk::DoseImageVtkMapper2D::GetVtkProp(mitk::BaseRenderer* renderer) +vtkProp *mitk::DoseImageVtkMapper2D::GetVtkProp(mitk::BaseRenderer *renderer) { - //return the actor corresponding to the renderer + // return the actor corresponding to the renderer return m_LSH.GetLocalStorage(renderer)->m_Actors; } -void mitk::DoseImageVtkMapper2D::GenerateDataForRenderer( mitk::BaseRenderer *renderer ) +void mitk::DoseImageVtkMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { - LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); - mitk::Image *input = const_cast< mitk::Image * >( this->GetInput() ); - mitk::DataNode* datanode = this->GetDataNode(); + mitk::Image *input = const_cast(this->GetInput()); + mitk::DataNode *datanode = this->GetDataNode(); - if ( input == nullptr || input->IsInitialized() == false ) + if (input == NULL || input->IsInitialized() == false) { return; } - //check if there is a valid worldGeometry + // check if there is a valid worldGeometry const PlaneGeometry *worldGeometry = renderer->GetCurrentWorldPlaneGeometry(); - if( ( worldGeometry == nullptr ) || ( !worldGeometry->IsValid() ) || ( !worldGeometry->HasReferenceGeometry() )) + if ((worldGeometry == NULL) || (!worldGeometry->IsValid()) || (!worldGeometry->HasReferenceGeometry())) { return; } input->Update(); // early out if there is no intersection of the current rendering geometry // and the geometry of the image that is to be rendered. - if ( !RenderingGeometryIntersectsImage( worldGeometry, input->GetSlicedGeometry() ) ) + if (!RenderingGeometryIntersectsImage(worldGeometry, input->GetSlicedGeometry())) { // set image to nullptr, to clear the texture in 3D, because // the latest image is used there if the plane is out of the geometry // see bug-13275 - localStorage->m_ReslicedImage = nullptr; - localStorage->m_Mapper->SetInputData( localStorage->m_EmptyPolyData ); + localStorage->m_ReslicedImage = NULL; + localStorage->m_Mapper->SetInputData(localStorage->m_EmptyPolyData); return; } - //set main input for ExtractSliceFilter + // set main input for ExtractSliceFilter localStorage->m_Reslicer->SetInput(input); localStorage->m_Reslicer->SetWorldGeometry(worldGeometry); - localStorage->m_Reslicer->SetTimeStep( this->GetTimestep() ); + localStorage->m_Reslicer->SetTimeStep(this->GetTimestep()); - //set the transformation of the image to adapt reslice axis - localStorage->m_Reslicer->SetResliceTransformByGeometry( input->GetTimeGeometry()->GetGeometryForTimeStep( this->GetTimestep() ) ); + // set the transformation of the image to adapt reslice axis + localStorage->m_Reslicer->SetResliceTransformByGeometry( + input->GetTimeGeometry()->GetGeometryForTimeStep(this->GetTimestep())); - //is the geometry of the slice based on the input image or the worldgeometry? + // is the geometry of the slice based on the input image or the worldgeometry? bool inPlaneResampleExtentByGeometry = false; datanode->GetBoolProperty("in plane resample extent by geometry", inPlaneResampleExtentByGeometry, renderer); localStorage->m_Reslicer->SetInPlaneResampleExtentByGeometry(inPlaneResampleExtentByGeometry); // Initialize the interpolation mode for resampling; switch to nearest // neighbor if the input image is too small. - if ( (input->GetDimension() >= 3) && (input->GetDimension(2) > 1) ) + if ((input->GetDimension() >= 3) && (input->GetDimension(2) > 1)) { VtkResliceInterpolationProperty *resliceInterpolationProperty; - datanode->GetProperty( - resliceInterpolationProperty, "reslice interpolation" ); + datanode->GetProperty(resliceInterpolationProperty, "reslice interpolation"); int interpolationMode = VTK_RESLICE_NEAREST; - if ( resliceInterpolationProperty != nullptr ) + if (resliceInterpolationProperty != NULL) { interpolationMode = resliceInterpolationProperty->GetInterpolation(); } - switch ( interpolationMode ) + switch (interpolationMode) { - case VTK_RESLICE_NEAREST: - localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_NEAREST); - break; - case VTK_RESLICE_LINEAR: - localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_LINEAR); - break; - case VTK_RESLICE_CUBIC: - localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_CUBIC); - break; + case VTK_RESLICE_NEAREST: + localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_NEAREST); + break; + case VTK_RESLICE_LINEAR: + localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_LINEAR); + break; + case VTK_RESLICE_CUBIC: + localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_CUBIC); + break; } } else { localStorage->m_Reslicer->SetInterpolationMode(ExtractSliceFilter::RESLICE_NEAREST); } - //set the vtk output property to true, makes sure that no unneeded mitk image convertion - //is done. + // set the vtk output property to true, makes sure that no unneeded mitk image convertion + // is done. localStorage->m_Reslicer->SetVtkOutputRequest(true); - //Thickslicing + // Thickslicing int thickSlicesMode = 0; int thickSlicesNum = 1; // Thick slices parameters - if( input->GetPixelType().GetNumberOfComponents() == 1 ) // for now only single component are allowed + if (input->GetPixelType().GetNumberOfComponents() == 1) // for now only single component are allowed { - DataNode *dn=renderer->GetCurrentWorldPlaneGeometryNode(); - if(dn) + DataNode *dn = renderer->GetCurrentWorldPlaneGeometryNode(); + if (dn) { - ResliceMethodProperty *resliceMethodEnumProperty=0; + ResliceMethodProperty *resliceMethodEnumProperty = 0; - if( dn->GetProperty( resliceMethodEnumProperty, "reslice.thickslices" ) && resliceMethodEnumProperty ) + if (dn->GetProperty(resliceMethodEnumProperty, "reslice.thickslices") && resliceMethodEnumProperty) thickSlicesMode = resliceMethodEnumProperty->GetValueAsId(); - IntProperty *intProperty=0; - if( dn->GetProperty( intProperty, "reslice.thickslices.num" ) && intProperty ) + IntProperty *intProperty = 0; + if (dn->GetProperty(intProperty, "reslice.thickslices.num") && intProperty) { thickSlicesNum = intProperty->GetValue(); - if(thickSlicesNum < 1) thickSlicesNum=1; - if(thickSlicesNum > 10) thickSlicesNum=10; + if (thickSlicesNum < 1) + thickSlicesNum = 1; + if (thickSlicesNum > 10) + thickSlicesNum = 10; } } else { MITK_WARN << "no associated widget plane data tree node found"; } } - const PlaneGeometry *planeGeometry = dynamic_cast< const PlaneGeometry * >( worldGeometry ); + const PlaneGeometry *planeGeometry = dynamic_cast(worldGeometry); - if(thickSlicesMode > 0) + if (thickSlicesMode > 0) { double dataZSpacing = 1.0; Vector3D normInIndex, normal; - if ( planeGeometry != nullptr ){ + if (planeGeometry != NULL) + { normal = planeGeometry->GetNormal(); - }else{ - const mitk::AbstractTransformGeometry* abstractGeometry = dynamic_cast< const AbstractTransformGeometry * >(worldGeometry); - if(abstractGeometry != nullptr) + } + else + { + const mitk::AbstractTransformGeometry *abstractGeometry = + dynamic_cast(worldGeometry); + if (abstractGeometry != NULL) normal = abstractGeometry->GetPlane()->GetNormal(); else - return; //no fitting geometry set + return; // no fitting geometry set } normal.Normalize(); - input->GetTimeGeometry()->GetGeometryForTimeStep( this->GetTimestep() )->WorldToIndex( normal, normInIndex ); + input->GetTimeGeometry()->GetGeometryForTimeStep(this->GetTimestep())->WorldToIndex(normal, normInIndex); dataZSpacing = 1.0 / normInIndex.GetNorm(); - localStorage->m_Reslicer->SetOutputDimensionality( 3 ); + localStorage->m_Reslicer->SetOutputDimensionality(3); localStorage->m_Reslicer->SetOutputSpacingZDirection(dataZSpacing); - localStorage->m_Reslicer->SetOutputExtentZDirection( -thickSlicesNum, 0+thickSlicesNum ); + localStorage->m_Reslicer->SetOutputExtentZDirection(-thickSlicesNum, 0 + thickSlicesNum); // Do the reslicing. Modified() is called to make sure that the reslicer is // executed even though the input geometry information did not change; this // is necessary when the input /em data, but not the /em geometry changes. - localStorage->m_TSFilter->SetThickSliceMode( thickSlicesMode-1 ); - localStorage->m_TSFilter->SetInputData( localStorage->m_Reslicer->GetVtkOutput() ); + localStorage->m_TSFilter->SetThickSliceMode(thickSlicesMode - 1); + localStorage->m_TSFilter->SetInputData(localStorage->m_Reslicer->GetVtkOutput()); - //vtkFilter=>mitkFilter=>vtkFilter update mechanism will fail without calling manually + // vtkFilter=>mitkFilter=>vtkFilter update mechanism will fail without calling manually localStorage->m_Reslicer->Modified(); localStorage->m_Reslicer->Update(); localStorage->m_TSFilter->Modified(); localStorage->m_TSFilter->Update(); localStorage->m_ReslicedImage = localStorage->m_TSFilter->GetOutput(); } else { - //this is needed when thick mode was enable bevore. These variable have to be reset to default values - localStorage->m_Reslicer->SetOutputDimensionality( 2 ); + // this is needed when thick mode was enable bevore. These variable have to be reset to default values + localStorage->m_Reslicer->SetOutputDimensionality(2); localStorage->m_Reslicer->SetOutputSpacingZDirection(1.0); - localStorage->m_Reslicer->SetOutputExtentZDirection( 0, 0 ); - + localStorage->m_Reslicer->SetOutputExtentZDirection(0, 0); localStorage->m_Reslicer->Modified(); - //start the pipeline with updating the largest possible, needed if the geometry of the input has changed + // start the pipeline with updating the largest possible, needed if the geometry of the input has changed localStorage->m_Reslicer->UpdateLargestPossibleRegion(); localStorage->m_ReslicedImage = localStorage->m_Reslicer->GetVtkOutput(); } // Bounds information for reslicing (only reuqired if reference geometry // is present) - //this used for generating a vtkPLaneSource with the right size + // this used for generating a vtkPLaneSource with the right size double sliceBounds[6]; - for ( int i = 0; i < 6; ++i ) + for (int i = 0; i < 6; ++i) { sliceBounds[i] = 0.0; } localStorage->m_Reslicer->GetClippedPlaneBounds(sliceBounds); - //get the spacing of the slice + // get the spacing of the slice localStorage->m_mmPerPixel = localStorage->m_Reslicer->GetOutputSpacing(); // calculate minimum bounding rect of IMAGE in texture { double textureClippingBounds[6]; - for ( int i = 0; i < 6; ++i ) + for (int i = 0; i < 6; ++i) { textureClippingBounds[i] = 0.0; } // Calculate the actual bounds of the transformed plane clipped by the // dataset bounding box; this is required for drawing the texture at the // correct position during 3D mapping. - mitk::PlaneClipping::CalculateClippedPlaneBounds( input->GetGeometry(), planeGeometry, textureClippingBounds ); + mitk::PlaneClipping::CalculateClippedPlaneBounds(input->GetGeometry(), planeGeometry, textureClippingBounds); - textureClippingBounds[0] = static_cast< int >( textureClippingBounds[0] / localStorage->m_mmPerPixel[0] + 0.5 ); - textureClippingBounds[1] = static_cast< int >( textureClippingBounds[1] / localStorage->m_mmPerPixel[0] + 0.5 ); - textureClippingBounds[2] = static_cast< int >( textureClippingBounds[2] / localStorage->m_mmPerPixel[1] + 0.5 ); - textureClippingBounds[3] = static_cast< int >( textureClippingBounds[3] / localStorage->m_mmPerPixel[1] + 0.5 ); + textureClippingBounds[0] = static_cast(textureClippingBounds[0] / localStorage->m_mmPerPixel[0] + 0.5); + textureClippingBounds[1] = static_cast(textureClippingBounds[1] / localStorage->m_mmPerPixel[0] + 0.5); + textureClippingBounds[2] = static_cast(textureClippingBounds[2] / localStorage->m_mmPerPixel[1] + 0.5); + textureClippingBounds[3] = static_cast(textureClippingBounds[3] / localStorage->m_mmPerPixel[1] + 0.5); - //clipping bounds for cutting the image + // clipping bounds for cutting the image localStorage->m_LevelWindowFilter->SetClippingBounds(textureClippingBounds); } - //get the number of scalar components to distinguish between different image types + // get the number of scalar components to distinguish between different image types int numberOfComponents = localStorage->m_ReslicedImage->GetNumberOfScalarComponents(); - //get the showIsoLines property + // get the showIsoLines property bool showIsoLines = false; - datanode->GetBoolProperty( "dose.showIsoLines", showIsoLines, renderer ); + datanode->GetBoolProperty("dose.showIsoLines", showIsoLines, renderer); - if(showIsoLines) //contour rendering + if (showIsoLines) // contour rendering { - //generate contours/outlines + // generate contours/outlines localStorage->m_OutlinePolyData = CreateOutlinePolyData(renderer); float binaryOutlineWidth(1.0); - if ( datanode->GetFloatProperty( "outline width", binaryOutlineWidth, renderer ) ) + if (datanode->GetFloatProperty("outline width", binaryOutlineWidth, renderer)) { - if ( localStorage->m_Actors->GetNumberOfPaths() > 1 ) + if (localStorage->m_Actors->GetNumberOfPaths() > 1) { float binaryOutlineShadowWidth(1.5); - datanode->GetFloatProperty( "outline shadow width", binaryOutlineShadowWidth, renderer ); + datanode->GetFloatProperty("outline shadow width", binaryOutlineShadowWidth, renderer); - dynamic_cast(localStorage->m_Actors->GetParts()->GetItemAsObject(0)) - ->GetProperty()->SetLineWidth( binaryOutlineWidth * binaryOutlineShadowWidth ); + dynamic_cast(localStorage->m_Actors->GetParts()->GetItemAsObject(0)) + ->GetProperty() + ->SetLineWidth(binaryOutlineWidth * binaryOutlineShadowWidth); } - localStorage->m_Actor->GetProperty()->SetLineWidth( binaryOutlineWidth ); + localStorage->m_Actor->GetProperty()->SetLineWidth(binaryOutlineWidth); } } else { - localStorage->m_ReslicedImage = nullptr; - localStorage->m_Mapper->SetInputData( localStorage->m_EmptyPolyData ); + localStorage->m_ReslicedImage = NULL; + localStorage->m_Mapper->SetInputData(localStorage->m_EmptyPolyData); return; } - this->ApplyOpacity( renderer ); + this->ApplyOpacity(renderer); this->ApplyRenderingMode(renderer); // do not use a VTK lookup table (we do that ourselves in m_LevelWindowFilter) localStorage->m_Texture->MapColorScalarsThroughLookupTableOff(); int displayedComponent = 0; if (datanode->GetIntProperty("Image.Displayed Component", displayedComponent, renderer) && numberOfComponents > 1) { localStorage->m_VectorComponentExtractor->SetComponents(displayedComponent); localStorage->m_VectorComponentExtractor->SetInputData(localStorage->m_ReslicedImage); localStorage->m_LevelWindowFilter->SetInputConnection(localStorage->m_VectorComponentExtractor->GetOutputPort(0)); } else { - //connect the input with the levelwindow filter + // connect the input with the levelwindow filter localStorage->m_LevelWindowFilter->SetInputData(localStorage->m_ReslicedImage); } // check for texture interpolation property bool textureInterpolation = false; - GetDataNode()->GetBoolProperty( "texture interpolation", textureInterpolation, renderer ); + GetDataNode()->GetBoolProperty("texture interpolation", textureInterpolation, renderer); - //set the interpolation modus according to the property + // set the interpolation modus according to the property localStorage->m_Texture->SetInterpolate(textureInterpolation); // connect the texture with the output of the levelwindow filter localStorage->m_Texture->SetInputConnection(localStorage->m_LevelWindowFilter->GetOutputPort()); - this->TransformActor( renderer ); + this->TransformActor(renderer); - vtkActor* contourShadowActor = dynamic_cast (localStorage->m_Actors->GetParts()->GetItemAsObject(0)); + vtkActor *contourShadowActor = dynamic_cast(localStorage->m_Actors->GetParts()->GetItemAsObject(0)); - if(showIsoLines) //connect the mapper with the polyData which contains the lines + if (showIsoLines) // connect the mapper with the polyData which contains the lines { - //We need the contour for the binary outline property as actor + // We need the contour for the binary outline property as actor localStorage->m_Mapper->SetInputData(localStorage->m_OutlinePolyData); - localStorage->m_Actor->SetTexture(nullptr); //no texture for contours + localStorage->m_Actor->SetTexture(NULL); // no texture for contours - bool binaryOutlineShadow( false ); - datanode->GetBoolProperty( "outline binary shadow", binaryOutlineShadow, renderer ); + bool binaryOutlineShadow(false); + datanode->GetBoolProperty("outline binary shadow", binaryOutlineShadow, renderer); - if ( binaryOutlineShadow ) - contourShadowActor->SetVisibility( true ); + if (binaryOutlineShadow) + contourShadowActor->SetVisibility(true); else - contourShadowActor->SetVisibility( false ); + contourShadowActor->SetVisibility(false); } else - { //Connect the mapper with the input texture. This is the standard case. - //setup the textured plane - this->GeneratePlane( renderer, sliceBounds ); - //set the plane as input for the mapper + { // Connect the mapper with the input texture. This is the standard case. + // setup the textured plane + this->GeneratePlane(renderer, sliceBounds); + // set the plane as input for the mapper localStorage->m_Mapper->SetInputConnection(localStorage->m_Plane->GetOutputPort()); - //set the texture for the actor + // set the texture for the actor localStorage->m_Actor->SetTexture(localStorage->m_Texture); - contourShadowActor->SetVisibility( false ); + contourShadowActor->SetVisibility(false); } // We have been modified => save this for next Update() localStorage->m_LastUpdateTime.Modified(); } void mitk::DoseImageVtkMapper2D::ApplyLevelWindow(mitk::BaseRenderer *renderer) { - LocalStorage *localStorage = this->GetLocalStorage( renderer ); + LocalStorage *localStorage = this->GetLocalStorage(renderer); LevelWindow levelWindow; - this->GetDataNode()->GetLevelWindow( levelWindow, renderer, "levelwindow" ); - localStorage->m_LevelWindowFilter->GetLookupTable()->SetRange( levelWindow.GetLowerWindowBound(), levelWindow.GetUpperWindowBound() ); + this->GetDataNode()->GetLevelWindow(levelWindow, renderer, "levelwindow"); + localStorage->m_LevelWindowFilter->GetLookupTable()->SetRange(levelWindow.GetLowerWindowBound(), + levelWindow.GetUpperWindowBound()); mitk::LevelWindow opacLevelWindow; - if( this->GetDataNode()->GetLevelWindow( opacLevelWindow, renderer, "opaclevelwindow" ) ) + if (this->GetDataNode()->GetLevelWindow(opacLevelWindow, renderer, "opaclevelwindow")) { - //pass the opaque level window to the filter + // pass the opaque level window to the filter localStorage->m_LevelWindowFilter->SetMinOpacity(opacLevelWindow.GetLowerWindowBound()); localStorage->m_LevelWindowFilter->SetMaxOpacity(opacLevelWindow.GetUpperWindowBound()); } else { - //no opaque level window + // no opaque level window localStorage->m_LevelWindowFilter->SetMinOpacity(0.0); localStorage->m_LevelWindowFilter->SetMaxOpacity(255.0); } } -void mitk::DoseImageVtkMapper2D::ApplyColor( mitk::BaseRenderer* renderer ) +void mitk::DoseImageVtkMapper2D::ApplyColor(mitk::BaseRenderer *renderer) { - LocalStorage *localStorage = this->GetLocalStorage( renderer ); + LocalStorage *localStorage = this->GetLocalStorage(renderer); - float rgb[3]= { 1.0f, 1.0f, 1.0f }; + float rgb[3] = {1.0f, 1.0f, 1.0f}; // check for color prop and use it for rendering if it exists // binary image hovering & binary image selection - bool hover = false; + bool hover = false; bool selected = false; GetDataNode()->GetBoolProperty("binaryimage.ishovering", hover, renderer); GetDataNode()->GetBoolProperty("selected", selected, renderer); - if(hover && !selected) + if (hover && !selected) { - mitk::ColorProperty::Pointer colorprop = dynamic_cast(GetDataNode()->GetProperty - ("binaryimage.hoveringcolor", renderer)); - if(colorprop.IsNotNull()) + mitk::ColorProperty::Pointer colorprop = + dynamic_cast(GetDataNode()->GetProperty("binaryimage.hoveringcolor", renderer)); + if (colorprop.IsNotNull()) { - memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float)); + memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3 * sizeof(float)); } else { - GetDataNode()->GetColor( rgb, renderer, "color" ); + GetDataNode()->GetColor(rgb, renderer, "color"); } } - if(selected) + if (selected) { - mitk::ColorProperty::Pointer colorprop = dynamic_cast(GetDataNode()->GetProperty - ("binaryimage.selectedcolor", renderer)); - if(colorprop.IsNotNull()) { - memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float)); + mitk::ColorProperty::Pointer colorprop = + dynamic_cast(GetDataNode()->GetProperty("binaryimage.selectedcolor", renderer)); + if (colorprop.IsNotNull()) + { + memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3 * sizeof(float)); } else { GetDataNode()->GetColor(rgb, renderer, "color"); } } - if(!hover && !selected) + if (!hover && !selected) { - GetDataNode()->GetColor( rgb, renderer, "color" ); + GetDataNode()->GetColor(rgb, renderer, "color"); } - double rgbConv[3] = {(double)rgb[0], (double)rgb[1], (double)rgb[2]}; //conversion to double for VTK - dynamic_cast (localStorage->m_Actors->GetParts()->GetItemAsObject(0))->GetProperty()->SetColor(rgbConv); + double rgbConv[3] = {(double)rgb[0], (double)rgb[1], (double)rgb[2]}; // conversion to double for VTK + dynamic_cast(localStorage->m_Actors->GetParts()->GetItemAsObject(0))->GetProperty()->SetColor(rgbConv); localStorage->m_Actor->GetProperty()->SetColor(rgbConv); - if ( localStorage->m_Actors->GetParts()->GetNumberOfItems() > 1 ) + if (localStorage->m_Actors->GetParts()->GetNumberOfItems() > 1) { - float rgb[3]= { 1.0f, 1.0f, 1.0f }; - mitk::ColorProperty::Pointer colorprop = dynamic_cast(GetDataNode()->GetProperty - ("outline binary shadow color", renderer)); - if(colorprop.IsNotNull()) + float rgb[3] = {1.0f, 1.0f, 1.0f}; + mitk::ColorProperty::Pointer colorprop = + dynamic_cast(GetDataNode()->GetProperty("outline binary shadow color", renderer)); + if (colorprop.IsNotNull()) { - memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3*sizeof(float)); + memcpy(rgb, colorprop->GetColor().GetDataPointer(), 3 * sizeof(float)); } - double rgbConv[3] = {(double)rgb[0], (double)rgb[1], (double)rgb[2]}; //conversion to double for VTK - dynamic_cast( localStorage->m_Actors->GetParts()->GetItemAsObject(0) )->GetProperty()->SetColor(rgbConv); + double rgbConv[3] = {(double)rgb[0], (double)rgb[1], (double)rgb[2]}; // conversion to double for VTK + dynamic_cast(localStorage->m_Actors->GetParts()->GetItemAsObject(0))->GetProperty()->SetColor(rgbConv); } } -void mitk::DoseImageVtkMapper2D::ApplyOpacity( mitk::BaseRenderer* renderer ) +void mitk::DoseImageVtkMapper2D::ApplyOpacity(mitk::BaseRenderer *renderer) { - LocalStorage* localStorage = this->GetLocalStorage( renderer ); + LocalStorage *localStorage = this->GetLocalStorage(renderer); float opacity = 1.0f; // check for opacity prop and use it for rendering if it exists - GetDataNode()->GetOpacity( opacity, renderer, "opacity" ); - //set the opacity according to the properties + GetDataNode()->GetOpacity(opacity, renderer, "opacity"); + // set the opacity according to the properties localStorage->m_Actor->GetProperty()->SetOpacity(opacity); - if ( localStorage->m_Actors->GetParts()->GetNumberOfItems() > 1 ) + if (localStorage->m_Actors->GetParts()->GetNumberOfItems() > 1) { - dynamic_cast( localStorage->m_Actors->GetParts()->GetItemAsObject(0) )->GetProperty()->SetOpacity(opacity); + dynamic_cast(localStorage->m_Actors->GetParts()->GetItemAsObject(0)) + ->GetProperty() + ->SetOpacity(opacity); } } -void mitk::DoseImageVtkMapper2D::ApplyRenderingMode( mitk::BaseRenderer* renderer ) +void mitk::DoseImageVtkMapper2D::ApplyRenderingMode(mitk::BaseRenderer *renderer) { - LocalStorage* localStorage = m_LSH.GetLocalStorage(renderer); + LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); bool binary = false; - this->GetDataNode()->GetBoolProperty( "binary", binary, renderer ); - if(binary) // is it a binary image? + this->GetDataNode()->GetBoolProperty("binary", binary, renderer); + if (binary) // is it a binary image? { - //for binary images, we always use our default LuT and map every value to (0,1) - //the opacity of 0 will always be 0.0. We never a apply a LuT/TfF nor a level window. + // for binary images, we always use our default LuT and map every value to (0,1) + // the opacity of 0 will always be 0.0. We never a apply a LuT/TfF nor a level window. localStorage->m_LevelWindowFilter->SetLookupTable(localStorage->m_BinaryLookupTable); } else { - //all other image types can make use of the rendering mode + // all other image types can make use of the rendering mode int renderingMode = mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR; - mitk::RenderingModeProperty::Pointer mode = dynamic_cast(this->GetDataNode()->GetProperty( "Image Rendering.Mode", renderer )); - if(mode.IsNotNull()) + mitk::RenderingModeProperty::Pointer mode = + dynamic_cast(this->GetDataNode()->GetProperty("Image Rendering.Mode", renderer)); + if (mode.IsNotNull()) { renderingMode = mode->GetRenderingMode(); } - switch(renderingMode) + switch (renderingMode) { - case mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR: - MITK_DEBUG << "'Image Rendering.Mode' = LevelWindow_LookupTable_Color"; - this->ApplyLookuptable( renderer ); - this->ApplyLevelWindow( renderer ); - break; - case mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR: - MITK_DEBUG << "'Image Rendering.Mode' = LevelWindow_ColorTransferFunction_Color"; - this->ApplyColorTransferFunction( renderer ); - this->ApplyLevelWindow( renderer ); - break; - case mitk::RenderingModeProperty::LOOKUPTABLE_COLOR: - MITK_DEBUG << "'Image Rendering.Mode' = LookupTable_Color"; - this->ApplyLookuptable( renderer ); - break; - case mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_COLOR: - MITK_DEBUG << "'Image Rendering.Mode' = ColorTransferFunction_Color"; - this->ApplyColorTransferFunction( renderer ); - break; - default: - MITK_ERROR << "No valid 'Image Rendering.Mode' set. Using LOOKUPTABLE_LEVELWINDOW_COLOR instead."; - this->ApplyLookuptable( renderer ); - this->ApplyLevelWindow( renderer ); - break; + case mitk::RenderingModeProperty::LOOKUPTABLE_LEVELWINDOW_COLOR: + MITK_DEBUG << "'Image Rendering.Mode' = LevelWindow_LookupTable_Color"; + this->ApplyLookuptable(renderer); + this->ApplyLevelWindow(renderer); + break; + case mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_LEVELWINDOW_COLOR: + MITK_DEBUG << "'Image Rendering.Mode' = LevelWindow_ColorTransferFunction_Color"; + this->ApplyColorTransferFunction(renderer); + this->ApplyLevelWindow(renderer); + break; + case mitk::RenderingModeProperty::LOOKUPTABLE_COLOR: + MITK_DEBUG << "'Image Rendering.Mode' = LookupTable_Color"; + this->ApplyLookuptable(renderer); + break; + case mitk::RenderingModeProperty::COLORTRANSFERFUNCTION_COLOR: + MITK_DEBUG << "'Image Rendering.Mode' = ColorTransferFunction_Color"; + this->ApplyColorTransferFunction(renderer); + break; + default: + MITK_ERROR << "No valid 'Image Rendering.Mode' set. Using LOOKUPTABLE_LEVELWINDOW_COLOR instead."; + this->ApplyLookuptable(renderer); + this->ApplyLevelWindow(renderer); + break; } } - //we apply color for all images (including binaries). - this->ApplyColor( renderer ); + // we apply color for all images (including binaries). + this->ApplyColor(renderer); } -void mitk::DoseImageVtkMapper2D::ApplyLookuptable( mitk::BaseRenderer* renderer ) +void mitk::DoseImageVtkMapper2D::ApplyLookuptable(mitk::BaseRenderer *renderer) { - LocalStorage* localStorage = m_LSH.GetLocalStorage(renderer); - vtkLookupTable* usedLookupTable = localStorage->m_ColorLookupTable; + LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); + vtkLookupTable *usedLookupTable = localStorage->m_ColorLookupTable; // If lookup table or transferfunction use is requested... - mitk::LookupTableProperty::Pointer lookupTableProp = dynamic_cast(this->GetDataNode()->GetProperty("LookupTable")); + mitk::LookupTableProperty::Pointer lookupTableProp = + dynamic_cast(this->GetDataNode()->GetProperty("LookupTable")); - if( lookupTableProp.IsNotNull() ) // is a lookuptable set? + if (lookupTableProp.IsNotNull()) // is a lookuptable set? { usedLookupTable = lookupTableProp->GetLookupTable()->GetVtkLookupTable(); } else { //"Image Rendering.Mode was set to use a lookup table but there is no property 'LookupTable'. - //A default (rainbow) lookup table will be used. - //Here have to do nothing. Warning for the user has been removed, due to unwanted console output - //in every interation of the rendering. + // A default (rainbow) lookup table will be used. + // Here have to do nothing. Warning for the user has been removed, due to unwanted console output + // in every interation of the rendering. } localStorage->m_LevelWindowFilter->SetLookupTable(usedLookupTable); } void mitk::DoseImageVtkMapper2D::ApplyColorTransferFunction(mitk::BaseRenderer *renderer) { - mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast(this->GetDataNode()->GetProperty("Image Rendering.Transfer Function",renderer )); + mitk::TransferFunctionProperty::Pointer transferFunctionProp = dynamic_cast( + this->GetDataNode()->GetProperty("Image Rendering.Transfer Function", renderer)); - if( transferFunctionProp.IsNull() ) + if (transferFunctionProp.IsNull()) { - MITK_ERROR << "'Image Rendering.Mode'' was set to use a color transfer function but there is no property 'Image Rendering.Transfer Function'. Nothing will be done."; + MITK_ERROR << "'Image Rendering.Mode'' was set to use a color transfer function but there is no property 'Image " + "Rendering.Transfer Function'. Nothing will be done."; return; } - LocalStorage* localStorage = m_LSH.GetLocalStorage(renderer); - //pass the transfer function to our level window filter + LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); + // pass the transfer function to our level window filter localStorage->m_LevelWindowFilter->SetLookupTable(transferFunctionProp->GetValue()->GetColorTransferFunction()); } -void mitk::DoseImageVtkMapper2D::Update(mitk::BaseRenderer* renderer) +void mitk::DoseImageVtkMapper2D::Update(mitk::BaseRenderer *renderer) { - bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); - if ( !visible ) + if (!visible) { return; } - mitk::Image* data = const_cast( this->GetInput() ); - if ( data == nullptr ) + mitk::Image *data = const_cast(this->GetInput()); + if (data == NULL) { return; } // Calculate time step of the input data for the specified renderer (integer value) - this->CalculateTimeStep( renderer ); + this->CalculateTimeStep(renderer); // Check if time step is valid const TimeGeometry *dataTimeGeometry = data->GetTimeGeometry(); - if ( ( dataTimeGeometry == nullptr ) - || ( dataTimeGeometry->CountTimeSteps() == 0 ) - || ( !dataTimeGeometry->IsValidTimeStep( this->GetTimestep() ) ) ) + if ((dataTimeGeometry == NULL) || (dataTimeGeometry->CountTimeSteps() == 0) || + (!dataTimeGeometry->IsValidTimeStep(this->GetTimestep()))) { return; } const DataNode *node = this->GetDataNode(); data->UpdateOutputInformation(); LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); - //check if something important has changed and we need to rerender - if ( (localStorage->m_LastUpdateTime < node->GetMTime()) //was the node modified? - || (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) //Was the data modified? - || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometryUpdateTime()) //was the geometry modified? - || (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometry()->GetMTime()) - || (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) //was a property modified? - || (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime()) ) + // check if something important has changed and we need to rerender + if ((localStorage->m_LastUpdateTime < node->GetMTime()) // was the node modified? + || + (localStorage->m_LastUpdateTime < data->GetPipelineMTime()) // Was the data modified? + || + (localStorage->m_LastUpdateTime < + renderer->GetCurrentWorldPlaneGeometryUpdateTime()) // was the geometry modified? + || + (localStorage->m_LastUpdateTime < renderer->GetCurrentWorldPlaneGeometry()->GetMTime()) || + (localStorage->m_LastUpdateTime < node->GetPropertyList()->GetMTime()) // was a property modified? + || + (localStorage->m_LastUpdateTime < node->GetPropertyList(renderer)->GetMTime())) { - this->GenerateDataForRenderer( renderer ); + this->GenerateDataForRenderer(renderer); } // since we have checked that nothing important has changed, we can set // m_LastUpdateTime to the current time localStorage->m_LastUpdateTime.Modified(); } -void mitk::DoseImageVtkMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) +void mitk::DoseImageVtkMapper2D::SetDefaultProperties(mitk::DataNode *node, + mitk::BaseRenderer *renderer, + bool overwrite) { - mitk::Image::Pointer image = dynamic_cast(node->GetData()); + mitk::Image::Pointer image = dynamic_cast(node->GetData()); // Properties common for both images and segmentations - node->AddProperty( "depthOffset", mitk::FloatProperty::New( 0.0 ), renderer, overwrite ); - node->AddProperty( "outline binary", mitk::BoolProperty::New( false ), renderer, overwrite ); - node->AddProperty( "outline width", mitk::FloatProperty::New( 1.0 ), renderer, overwrite ); - node->AddProperty( "outline binary shadow", mitk::BoolProperty::New( false ), renderer, overwrite ); - node->AddProperty( "outline binary shadow color", ColorProperty::New(0.0,0.0,0.0), renderer, overwrite ); - node->AddProperty( "outline shadow width", mitk::FloatProperty::New( 1.5 ), renderer, overwrite ); - if(image->IsRotated()) node->AddProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New(VTK_RESLICE_CUBIC) ); - else node->AddProperty( "reslice interpolation", mitk::VtkResliceInterpolationProperty::New() ); - node->AddProperty( "texture interpolation", mitk::BoolProperty::New( mitk::DataNodeFactory::m_TextureInterpolationActive ) ); // set to user configurable default value (see global options) - node->AddProperty( "in plane resample extent by geometry", mitk::BoolProperty::New( false ) ); - node->AddProperty( "bounding box", mitk::BoolProperty::New( false ) ); + node->AddProperty("depthOffset", mitk::FloatProperty::New(0.0), renderer, overwrite); + node->AddProperty("outline binary", mitk::BoolProperty::New(false), renderer, overwrite); + node->AddProperty("outline width", mitk::FloatProperty::New(1.0), renderer, overwrite); + node->AddProperty("outline binary shadow", mitk::BoolProperty::New(false), renderer, overwrite); + node->AddProperty("outline binary shadow color", ColorProperty::New(0.0, 0.0, 0.0), renderer, overwrite); + node->AddProperty("outline shadow width", mitk::FloatProperty::New(1.5), renderer, overwrite); + if (image->IsRotated()) + node->AddProperty("reslice interpolation", mitk::VtkResliceInterpolationProperty::New(VTK_RESLICE_CUBIC)); + else + node->AddProperty("reslice interpolation", mitk::VtkResliceInterpolationProperty::New()); + node->AddProperty("texture interpolation", + mitk::BoolProperty::New(mitk::DataNodeFactory::m_TextureInterpolationActive)); // set to user + // configurable + // default value (see + // global options) + node->AddProperty("in plane resample extent by geometry", mitk::BoolProperty::New(false)); + node->AddProperty("bounding box", mitk::BoolProperty::New(false)); mitk::RenderingModeProperty::Pointer renderingModeProperty = mitk::RenderingModeProperty::New(); - node->AddProperty( "Image Rendering.Mode", renderingModeProperty); + node->AddProperty("Image Rendering.Mode", renderingModeProperty); // Set default grayscale look-up table mitk::LookupTable::Pointer mitkLut = mitk::LookupTable::New(); mitkLut->SetType(mitk::LookupTable::GRAYSCALE); mitk::LookupTableProperty::Pointer mitkLutProp = mitk::LookupTableProperty::New(); mitkLutProp->SetLookupTable(mitkLut); node->SetProperty("LookupTable", mitkLutProp); std::string photometricInterpretation; // DICOM tag telling us how pixel values should be displayed - if ( node->GetStringProperty( "dicom.pixel.PhotometricInterpretation", photometricInterpretation ) ) + if (node->GetStringProperty("dicom.pixel.PhotometricInterpretation", photometricInterpretation)) { // modality provided by DICOM or other reader - if ( photometricInterpretation.find("MONOCHROME1") != std::string::npos ) // meaning: display MINIMUM pixels as WHITE + if (photometricInterpretation.find("MONOCHROME1") != std::string::npos) // meaning: display MINIMUM pixels as WHITE { // Set inverse grayscale look-up table mitkLut->SetType(mitk::LookupTable::INVERSE_GRAYSCALE); mitkLutProp->SetLookupTable(mitkLut); node->SetProperty("LookupTable", mitkLutProp); } // Otherwise do nothing - the default grayscale look-up table has already been set } bool isBinaryImage(false); - if ( ! node->GetBoolProperty("binary", isBinaryImage) ) + if (!node->GetBoolProperty("binary", isBinaryImage)) { - // ok, property is not set, use heuristic to determine if this // is a binary image mitk::Image::Pointer centralSliceImage; ScalarType minValue = 0.0; ScalarType maxValue = 0.0; ScalarType min2ndValue = 0.0; ScalarType max2ndValue = 0.0; mitk::ImageSliceSelector::Pointer sliceSelector = mitk::ImageSliceSelector::New(); sliceSelector->SetInput(image); - sliceSelector->SetSliceNr(image->GetDimension(2)/2); - sliceSelector->SetTimeNr(image->GetDimension(3)/2); - sliceSelector->SetChannelNr(image->GetDimension(4)/2); + sliceSelector->SetSliceNr(image->GetDimension(2) / 2); + sliceSelector->SetTimeNr(image->GetDimension(3) / 2); + sliceSelector->SetChannelNr(image->GetDimension(4) / 2); sliceSelector->Update(); centralSliceImage = sliceSelector->GetOutput(); - if ( centralSliceImage.IsNotNull() && centralSliceImage->IsInitialized() ) + if (centralSliceImage.IsNotNull() && centralSliceImage->IsInitialized()) { - minValue = centralSliceImage->GetStatistics()->GetScalarValueMin(); - maxValue = centralSliceImage->GetStatistics()->GetScalarValueMax(); + minValue = centralSliceImage->GetStatistics()->GetScalarValueMin(); + maxValue = centralSliceImage->GetStatistics()->GetScalarValueMax(); min2ndValue = centralSliceImage->GetStatistics()->GetScalarValue2ndMin(); max2ndValue = centralSliceImage->GetStatistics()->GetScalarValue2ndMax(); } if ((maxValue == min2ndValue && minValue == max2ndValue) || minValue == maxValue) { // centralSlice is strange, lets look at all data - minValue = image->GetStatistics()->GetScalarValueMin(); - maxValue = image->GetStatistics()->GetScalarValueMaxNoRecompute(); + minValue = image->GetStatistics()->GetScalarValueMin(); + maxValue = image->GetStatistics()->GetScalarValueMaxNoRecompute(); min2ndValue = image->GetStatistics()->GetScalarValue2ndMinNoRecompute(); max2ndValue = image->GetStatistics()->GetScalarValue2ndMaxNoRecompute(); } - isBinaryImage = ( maxValue == min2ndValue && minValue == max2ndValue ); + isBinaryImage = (maxValue == min2ndValue && minValue == max2ndValue); } // some more properties specific for a binary... if (isBinaryImage) { - node->AddProperty( "opacity", mitk::FloatProperty::New(0.3f), renderer, overwrite ); - node->AddProperty( "color", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); - node->AddProperty( "binaryimage.selectedcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); - node->AddProperty( "binaryimage.selectedannotationcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); - node->AddProperty( "binaryimage.hoveringcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); - node->AddProperty( "binaryimage.hoveringannotationcolor", ColorProperty::New(1.0,0.0,0.0), renderer, overwrite ); - node->AddProperty( "binary", mitk::BoolProperty::New( true ), renderer, overwrite ); + node->AddProperty("opacity", mitk::FloatProperty::New(0.3f), renderer, overwrite); + node->AddProperty("color", ColorProperty::New(1.0, 0.0, 0.0), renderer, overwrite); + node->AddProperty("binaryimage.selectedcolor", ColorProperty::New(1.0, 0.0, 0.0), renderer, overwrite); + node->AddProperty("binaryimage.selectedannotationcolor", ColorProperty::New(1.0, 0.0, 0.0), renderer, overwrite); + node->AddProperty("binaryimage.hoveringcolor", ColorProperty::New(1.0, 0.0, 0.0), renderer, overwrite); + node->AddProperty("binaryimage.hoveringannotationcolor", ColorProperty::New(1.0, 0.0, 0.0), renderer, overwrite); + node->AddProperty("binary", mitk::BoolProperty::New(true), renderer, overwrite); node->AddProperty("layer", mitk::IntProperty::New(10), renderer, overwrite); } - else //...or image type object + else //...or image type object { - node->AddProperty( "opacity", mitk::FloatProperty::New(1.0f), renderer, overwrite ); - node->AddProperty( "color", ColorProperty::New(1.0,1.0,1.0), renderer, overwrite ); - node->AddProperty( "binary", mitk::BoolProperty::New( false ), renderer, overwrite ); + node->AddProperty("opacity", mitk::FloatProperty::New(1.0f), renderer, overwrite); + node->AddProperty("color", ColorProperty::New(1.0, 1.0, 1.0), renderer, overwrite); + node->AddProperty("binary", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("layer", mitk::IntProperty::New(0), renderer, overwrite); std::string className = image->GetNameOfClass(); if (className != "TensorImage" && className != "QBallImage") { PixelType pixelType = image->GetPixelType(); size_t numComponents = pixelType.GetNumberOfComponents(); - if ((pixelType.GetPixelTypeAsString() == "vector" && numComponents > 1) || numComponents == 2 || numComponents > 4) + if ((pixelType.GetPixelTypeAsString() == "vector" && numComponents > 1) || numComponents == 2 || + numComponents > 4) node->AddProperty("Image.Displayed Component", mitk::IntProperty::New(0), renderer, overwrite); } } - if(image.IsNotNull() && image->IsInitialized()) + if (image.IsNotNull() && image->IsInitialized()) { - if((overwrite) || (node->GetProperty("levelwindow", renderer)==nullptr)) + if ((overwrite) || (node->GetProperty("levelwindow", renderer) == NULL)) { /* initialize level/window from DICOM tags */ std::string sLevel; std::string sWindow; - if (GetBackwardsCompatibleDICOMProperty(0x0028, 0x1050, "dicom.voilut.WindowCenter", image->GetPropertyList(), sLevel) - && GetBackwardsCompatibleDICOMProperty(0x0028, 0x1051, "dicom.voilut.WindowWidth", image->GetPropertyList(), sWindow)) + if (GetBackwardsCompatibleDICOMProperty( + 0x0028, 0x1050, "dicom.voilut.WindowCenter", image->GetPropertyList(), sLevel) && + GetBackwardsCompatibleDICOMProperty( + 0x0028, 0x1051, "dicom.voilut.WindowWidth", image->GetPropertyList(), sWindow)) { - float level = atof( sLevel.c_str() ); - float window = atof( sWindow.c_str() ); + float level = atof(sLevel.c_str()); + float window = atof(sWindow.c_str()); mitk::LevelWindow contrast; std::string sSmallestPixelValueInSeries; std::string sLargestPixelValueInSeries; - if (GetBackwardsCompatibleDICOMProperty(0x0028, 0x0108, "dicom.series.SmallestPixelValueInSeries", image->GetPropertyList(), sSmallestPixelValueInSeries) - && GetBackwardsCompatibleDICOMProperty(0x0028, 0x0109, "dicom.series.LargestPixelValueInSeries", image->GetPropertyList(), sLargestPixelValueInSeries)) + if (GetBackwardsCompatibleDICOMProperty(0x0028, + 0x0108, + "dicom.series.SmallestPixelValueInSeries", + image->GetPropertyList(), + sSmallestPixelValueInSeries) && + GetBackwardsCompatibleDICOMProperty(0x0028, + 0x0109, + "dicom.series.LargestPixelValueInSeries", + image->GetPropertyList(), + sLargestPixelValueInSeries)) { - float smallestPixelValueInSeries = atof( sSmallestPixelValueInSeries.c_str() ); - float largestPixelValueInSeries = atof( sLargestPixelValueInSeries.c_str() ); - contrast.SetRangeMinMax( smallestPixelValueInSeries-1, largestPixelValueInSeries+1 ); // why not a little buffer? + float smallestPixelValueInSeries = atof(sSmallestPixelValueInSeries.c_str()); + float largestPixelValueInSeries = atof(sLargestPixelValueInSeries.c_str()); + contrast.SetRangeMinMax(smallestPixelValueInSeries - 1, + largestPixelValueInSeries + 1); // why not a little buffer? // might remedy some l/w widget challenges } else { - contrast.SetAuto( static_cast(node->GetData()), false, true ); // we need this as a fallback + contrast.SetAuto(static_cast(node->GetData()), false, true); // we need this as a fallback } - contrast.SetLevelWindow( level, window, true ); - node->SetProperty( "levelwindow", LevelWindowProperty::New( contrast ), renderer ); + contrast.SetLevelWindow(level, window, true); + node->SetProperty("levelwindow", LevelWindowProperty::New(contrast), renderer); } } - if(((overwrite) || (node->GetProperty("opaclevelwindow", renderer)==nullptr)) - && (image->GetPixelType().GetPixelType() == itk::ImageIOBase::RGBA) - && (image->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR) ) + if (((overwrite) || (node->GetProperty("opaclevelwindow", renderer) == NULL)) && + (image->GetPixelType().GetPixelType() == itk::ImageIOBase::RGBA) && + (image->GetPixelType().GetComponentType() == itk::ImageIOBase::UCHAR)) { mitk::LevelWindow opaclevwin; - opaclevwin.SetRangeMinMax(0,255); - opaclevwin.SetWindowBounds(0,255); + opaclevwin.SetRangeMinMax(0, 255); + opaclevwin.SetWindowBounds(0, 255); mitk::LevelWindowProperty::Pointer prop = mitk::LevelWindowProperty::New(opaclevwin); - node->SetProperty( "opaclevelwindow", prop, renderer ); + node->SetProperty("opaclevelwindow", prop, renderer); } } Superclass::SetDefaultProperties(node, renderer, overwrite); } -mitk::DoseImageVtkMapper2D::LocalStorage* mitk::DoseImageVtkMapper2D::GetLocalStorage(mitk::BaseRenderer* renderer) +mitk::DoseImageVtkMapper2D::LocalStorage *mitk::DoseImageVtkMapper2D::GetLocalStorage(mitk::BaseRenderer *renderer) { return m_LSH.GetLocalStorage(renderer); } - -vtkSmartPointer mitk::DoseImageVtkMapper2D::CreateOutlinePolyData(mitk::BaseRenderer* renderer ) +vtkSmartPointer mitk::DoseImageVtkMapper2D::CreateOutlinePolyData(mitk::BaseRenderer *renderer) { - vtkSmartPointer points = vtkSmartPointer::New(); //the points to draw - vtkSmartPointer lines = vtkSmartPointer::New(); //the lines to connect the points + vtkSmartPointer points = vtkSmartPointer::New(); // the points to draw + vtkSmartPointer lines = vtkSmartPointer::New(); // the lines to connect the points vtkSmartPointer colors = vtkSmartPointer::New(); colors->SetNumberOfComponents(3); colors->SetName("Colors"); float pref; - this->GetDataNode()->GetFloatProperty(mitk::RTConstants::REFERENCE_DOSE_PROPERTY_NAME.c_str(),pref); + this->GetDataNode()->GetFloatProperty(mitk::RTConstants::REFERENCE_DOSE_PROPERTY_NAME.c_str(), pref); - mitk::IsoDoseLevelSetProperty::Pointer propIsoSet = dynamic_cast(GetDataNode()->GetProperty(mitk::RTConstants::DOSE_ISO_LEVELS_PROPERTY_NAME.c_str())); + mitk::IsoDoseLevelSetProperty::Pointer propIsoSet = dynamic_cast( + GetDataNode()->GetProperty(mitk::RTConstants::DOSE_ISO_LEVELS_PROPERTY_NAME.c_str())); mitk::IsoDoseLevelSet::Pointer isoDoseLevelSet = propIsoSet->GetValue(); - for(mitk::IsoDoseLevelSet::ConstIterator doseIT = isoDoseLevelSet->Begin(); doseIT!=isoDoseLevelSet->End();++doseIT) + for (mitk::IsoDoseLevelSet::ConstIterator doseIT = isoDoseLevelSet->Begin(); doseIT != isoDoseLevelSet->End(); + ++doseIT) { - if(doseIT->GetVisibleIsoLine()) + if (doseIT->GetVisibleIsoLine()) { this->CreateLevelOutline(renderer, &(doseIT.Value()), pref, points, lines, colors); - }//end of if visible dose value - }//end of loop over all does values + } // end of if visible dose value + } // end of loop over all does values - mitk::IsoDoseLevelVectorProperty::Pointer propfreeIsoVec = dynamic_cast(GetDataNode()->GetProperty(mitk::RTConstants::DOSE_FREE_ISO_VALUES_PROPERTY_NAME.c_str())); + mitk::IsoDoseLevelVectorProperty::Pointer propfreeIsoVec = dynamic_cast( + GetDataNode()->GetProperty(mitk::RTConstants::DOSE_FREE_ISO_VALUES_PROPERTY_NAME.c_str())); mitk::IsoDoseLevelVector::Pointer frereIsoDoseLevelVec = propfreeIsoVec->GetValue(); - for(mitk::IsoDoseLevelVector::ConstIterator freeDoseIT = frereIsoDoseLevelVec->Begin(); freeDoseIT!=frereIsoDoseLevelVec->End();++freeDoseIT) + for (mitk::IsoDoseLevelVector::ConstIterator freeDoseIT = frereIsoDoseLevelVec->Begin(); + freeDoseIT != frereIsoDoseLevelVec->End(); + ++freeDoseIT) { - if(freeDoseIT->Value()->GetVisibleIsoLine()) + if (freeDoseIT->Value()->GetVisibleIsoLine()) { this->CreateLevelOutline(renderer, freeDoseIT->Value(), pref, points, lines, colors); - }//end of if visible dose value - }//end of loop over all does values + } // end of if visible dose value + } // end of loop over all does values // Create a polydata to store everything in vtkSmartPointer polyData = vtkSmartPointer::New(); // Add the points to the dataset polyData->SetPoints(points); // Add the lines to the dataset polyData->SetLines(lines); polyData->GetCellData()->SetScalars(colors); return polyData; } -void mitk::DoseImageVtkMapper2D::CreateLevelOutline(mitk::BaseRenderer* renderer, const mitk::IsoDoseLevel* level, float pref, vtkSmartPointer points, vtkSmartPointer lines, vtkSmartPointer colors) +void mitk::DoseImageVtkMapper2D::CreateLevelOutline(mitk::BaseRenderer *renderer, + const mitk::IsoDoseLevel *level, + float pref, + vtkSmartPointer points, + vtkSmartPointer lines, + vtkSmartPointer colors) { - LocalStorage* localStorage = this->GetLocalStorage(renderer); + LocalStorage *localStorage = this->GetLocalStorage(renderer); - //get the min and max index values of each direction - int* extent = localStorage->m_ReslicedImage->GetExtent(); + // get the min and max index values of each direction + int *extent = localStorage->m_ReslicedImage->GetExtent(); int xMin = extent[0]; int xMax = extent[1]; int yMin = extent[2]; int yMax = extent[3]; - int* dims = localStorage->m_ReslicedImage->GetDimensions(); //dimensions of the image - int line = dims[0]; //how many pixels per line? - //get the depth for each contour + int *dims = localStorage->m_ReslicedImage->GetDimensions(); // dimensions of the image + int line = dims[0]; // how many pixels per line? + // get the depth for each contour float depth = CalculateLayerDepth(renderer); - double doseValue = level->GetDoseValue()*pref; + double doseValue = level->GetDoseValue() * pref; mitk::IsoDoseLevel::ColorType isoColor = level->GetColor(); - unsigned char colorLine[3] = {static_cast(isoColor.GetRed()*255), - static_cast(isoColor.GetGreen()*255), - static_cast(isoColor.GetBlue()*255)}; + unsigned char colorLine[3] = {static_cast(isoColor.GetRed() * 255), + static_cast(isoColor.GetGreen() * 255), + static_cast(isoColor.GetBlue() * 255)}; - int x = xMin; //pixel index x - int y = yMin; //pixel index y - float* currentPixel; + int x = xMin; // pixel index x + int y = yMin; // pixel index y + float *currentPixel; // We take the pointer to the first pixel of the image - currentPixel = static_cast(localStorage->m_ReslicedImage->GetScalarPointer() ); + currentPixel = static_cast(localStorage->m_ReslicedImage->GetScalarPointer()); while (y <= yMax) { - //if the current pixel value is set to something + // if the current pixel value is set to something if ((currentPixel) && (*currentPixel >= doseValue)) { - //check in which direction a line is necessary - //a line is added if the neighbor of the current pixel has the value 0 - //and if the pixel is located at the edge of the image - - //if vvvvv not the first line vvvvv - if (y > yMin && *(currentPixel-line) < doseValue) - { //x direction - bottom edge of the pixel - //add the 2 points - vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); - vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); - //add the line between both points + // check in which direction a line is necessary + // a line is added if the neighbor of the current pixel has the value 0 + // and if the pixel is located at the edge of the image + + // if vvvvv not the first line vvvvv + if (y > yMin && *(currentPixel - line) < doseValue) + { // x direction - bottom edge of the pixel + // add the 2 points + vtkIdType p1 = + points->InsertNextPoint(x * localStorage->m_mmPerPixel[0], y * localStorage->m_mmPerPixel[1], depth); + vtkIdType p2 = + points->InsertNextPoint((x + 1) * localStorage->m_mmPerPixel[0], y * localStorage->m_mmPerPixel[1], depth); + // add the line between both points lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); - colors->InsertNextTupleValue(colorLine); + colors->InsertNextTypedTuple(colorLine); } - //if vvvvv not the last line vvvvv - if (y < yMax && *(currentPixel+line) < doseValue) - { //x direction - top edge of the pixel - vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); - vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); + // if vvvvv not the last line vvvvv + if (y < yMax && *(currentPixel + line) < doseValue) + { // x direction - top edge of the pixel + vtkIdType p1 = + points->InsertNextPoint(x * localStorage->m_mmPerPixel[0], (y + 1) * localStorage->m_mmPerPixel[1], depth); + vtkIdType p2 = points->InsertNextPoint( + (x + 1) * localStorage->m_mmPerPixel[0], (y + 1) * localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); - colors->InsertNextTupleValue(colorLine); + colors->InsertNextTypedTuple(colorLine); } - //if vvvvv not the first pixel vvvvv - if ( (x > xMin || y > yMin) && *(currentPixel-1) < doseValue) - { //y direction - left edge of the pixel - vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); - vtkIdType p2 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); + // if vvvvv not the first pixel vvvvv + if ((x > xMin || y > yMin) && *(currentPixel - 1) < doseValue) + { // y direction - left edge of the pixel + vtkIdType p1 = + points->InsertNextPoint(x * localStorage->m_mmPerPixel[0], y * localStorage->m_mmPerPixel[1], depth); + vtkIdType p2 = + points->InsertNextPoint(x * localStorage->m_mmPerPixel[0], (y + 1) * localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); - colors->InsertNextTupleValue(colorLine); + colors->InsertNextTypedTuple(colorLine); } - //if vvvvv not the last pixel vvvvv - if ( (y < yMax || (x < xMax) ) && *(currentPixel+1) < doseValue) - { //y direction - right edge of the pixel - vtkIdType p1 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); - vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); + // if vvvvv not the last pixel vvvvv + if ((y < yMax || (x < xMax)) && *(currentPixel + 1) < doseValue) + { // y direction - right edge of the pixel + vtkIdType p1 = + points->InsertNextPoint((x + 1) * localStorage->m_mmPerPixel[0], y * localStorage->m_mmPerPixel[1], depth); + vtkIdType p2 = points->InsertNextPoint( + (x + 1) * localStorage->m_mmPerPixel[0], (y + 1) * localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); - colors->InsertNextTupleValue(colorLine); + colors->InsertNextTypedTuple(colorLine); } /* now consider pixels at the edge of the image */ - //if vvvvv left edge of image vvvvv + // if vvvvv left edge of image vvvvv if (x == xMin) - { //draw left edge of the pixel - vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); - vtkIdType p2 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); + { // draw left edge of the pixel + vtkIdType p1 = + points->InsertNextPoint(x * localStorage->m_mmPerPixel[0], y * localStorage->m_mmPerPixel[1], depth); + vtkIdType p2 = + points->InsertNextPoint(x * localStorage->m_mmPerPixel[0], (y + 1) * localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); - colors->InsertNextTupleValue(colorLine); + colors->InsertNextTypedTuple(colorLine); } - //if vvvvv right edge of image vvvvv + // if vvvvv right edge of image vvvvv if (x == xMax) - { //draw right edge of the pixel - vtkIdType p1 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); - vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); + { // draw right edge of the pixel + vtkIdType p1 = + points->InsertNextPoint((x + 1) * localStorage->m_mmPerPixel[0], y * localStorage->m_mmPerPixel[1], depth); + vtkIdType p2 = points->InsertNextPoint( + (x + 1) * localStorage->m_mmPerPixel[0], (y + 1) * localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); - colors->InsertNextTupleValue(colorLine); + colors->InsertNextTypedTuple(colorLine); } - //if vvvvv bottom edge of image vvvvv + // if vvvvv bottom edge of image vvvvv if (y == yMin) - { //draw bottom edge of the pixel - vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); - vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], y*localStorage->m_mmPerPixel[1], depth); + { // draw bottom edge of the pixel + vtkIdType p1 = + points->InsertNextPoint(x * localStorage->m_mmPerPixel[0], y * localStorage->m_mmPerPixel[1], depth); + vtkIdType p2 = + points->InsertNextPoint((x + 1) * localStorage->m_mmPerPixel[0], y * localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); - colors->InsertNextTupleValue(colorLine); + colors->InsertNextTypedTuple(colorLine); } - //if vvvvv top edge of image vvvvv + // if vvvvv top edge of image vvvvv if (y == yMax) - { //draw top edge of the pixel - vtkIdType p1 = points->InsertNextPoint(x*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); - vtkIdType p2 = points->InsertNextPoint((x+1)*localStorage->m_mmPerPixel[0], (y+1)*localStorage->m_mmPerPixel[1], depth); + { // draw top edge of the pixel + vtkIdType p1 = + points->InsertNextPoint(x * localStorage->m_mmPerPixel[0], (y + 1) * localStorage->m_mmPerPixel[1], depth); + vtkIdType p2 = points->InsertNextPoint( + (x + 1) * localStorage->m_mmPerPixel[0], (y + 1) * localStorage->m_mmPerPixel[1], depth); lines->InsertNextCell(2); lines->InsertCellPoint(p1); lines->InsertCellPoint(p2); - colors->InsertNextTupleValue(colorLine); + colors->InsertNextTypedTuple(colorLine); } - }//end if currentpixel is set + } // end if currentpixel is set x++; if (x > xMax) - { //reached end of line + { // reached end of line x = xMin; y++; } // Increase the pointer-position to the next pixel. // This is safe, as the while-loop and the x-reset logic above makes // sure we do not exceed the bounds of the image currentPixel++; - }//end of while + } // end of while } -void mitk::DoseImageVtkMapper2D::TransformActor(mitk::BaseRenderer* renderer) +void mitk::DoseImageVtkMapper2D::TransformActor(mitk::BaseRenderer *renderer) { LocalStorage *localStorage = m_LSH.GetLocalStorage(renderer); - //get the transformation matrix of the reslicer in order to render the slice as axial, coronal or saggital + // get the transformation matrix of the reslicer in order to render the slice as axial, coronal or saggital vtkSmartPointer trans = vtkSmartPointer::New(); vtkSmartPointer matrix = localStorage->m_Reslicer->GetResliceAxes(); trans->SetMatrix(matrix); - //transform the plane/contour (the actual actor) to the corresponding view (axial, coronal or saggital) + // transform the plane/contour (the actual actor) to the corresponding view (axial, coronal or saggital) localStorage->m_Actor->SetUserTransform(trans); - //transform the origin to center based coordinates, because MITK is center based. - localStorage->m_Actor->SetPosition( -0.5*localStorage->m_mmPerPixel[0], -0.5*localStorage->m_mmPerPixel[1], 0.0); + // transform the origin to center based coordinates, because MITK is center based. + localStorage->m_Actor->SetPosition(-0.5 * localStorage->m_mmPerPixel[0], -0.5 * localStorage->m_mmPerPixel[1], 0.0); - if ( localStorage->m_Actors->GetNumberOfPaths() > 1 ) + if (localStorage->m_Actors->GetNumberOfPaths() > 1) { - vtkActor* secondaryActor = dynamic_cast( localStorage->m_Actors->GetParts()->GetItemAsObject(0) ); + vtkActor *secondaryActor = dynamic_cast(localStorage->m_Actors->GetParts()->GetItemAsObject(0)); secondaryActor->SetUserTransform(trans); - secondaryActor->SetPosition( -0.5*localStorage->m_mmPerPixel[0], -0.5*localStorage->m_mmPerPixel[1], 0.0); + secondaryActor->SetPosition(-0.5 * localStorage->m_mmPerPixel[0], -0.5 * localStorage->m_mmPerPixel[1], 0.0); } } -bool mitk::DoseImageVtkMapper2D::RenderingGeometryIntersectsImage( const PlaneGeometry* renderingGeometry, SlicedGeometry3D* imageGeometry ) +bool mitk::DoseImageVtkMapper2D::RenderingGeometryIntersectsImage(const PlaneGeometry *renderingGeometry, + SlicedGeometry3D *imageGeometry) { // if either one of the two geometries is nullptr we return true // for safety reasons - if ( renderingGeometry == nullptr || imageGeometry == nullptr ) + if (renderingGeometry == NULL || imageGeometry == NULL) return true; // get the distance for the first cornerpoint - ScalarType initialDistance = renderingGeometry->SignedDistance( imageGeometry->GetCornerPoint( 0 ) ); - for( int i=1; i<8; i++ ) + ScalarType initialDistance = renderingGeometry->SignedDistance(imageGeometry->GetCornerPoint(0)); + for (int i = 1; i < 8; i++) { - mitk::Point3D cornerPoint = imageGeometry->GetCornerPoint( i ); + mitk::Point3D cornerPoint = imageGeometry->GetCornerPoint(i); // get the distance to the other cornerpoints - ScalarType distance = renderingGeometry->SignedDistance( cornerPoint ); + ScalarType distance = renderingGeometry->SignedDistance(cornerPoint); // if it has not the same signing as the distance of the first point - if ( initialDistance * distance < 0 ) + if (initialDistance * distance < 0) { // we have an intersection and return true return true; } } // all distances have the same sign, no intersection and we return false return false; } mitk::DoseImageVtkMapper2D::LocalStorage::~LocalStorage() { } mitk::DoseImageVtkMapper2D::LocalStorage::LocalStorage() -: m_VectorComponentExtractor(vtkSmartPointer::New()) + : m_VectorComponentExtractor(vtkSmartPointer::New()) { - m_LevelWindowFilter = vtkSmartPointer::New(); - //Do as much actions as possible in here to avoid double executions. + // Do as much actions as possible in here to avoid double executions. m_Plane = vtkSmartPointer::New(); m_Texture = vtkSmartPointer::New().GetPointer(); m_DefaultLookupTable = vtkSmartPointer::New(); m_BinaryLookupTable = vtkSmartPointer::New(); m_ColorLookupTable = vtkSmartPointer::New(); m_Mapper = vtkSmartPointer::New(); m_Actor = vtkSmartPointer::New(); m_Actors = vtkSmartPointer::New(); m_Reslicer = mitk::ExtractSliceFilter::New(); m_TSFilter = vtkSmartPointer::New(); m_OutlinePolyData = vtkSmartPointer::New(); m_ReslicedImage = vtkSmartPointer::New(); m_EmptyPolyData = vtkSmartPointer::New(); - //the following actions are always the same and thus can be performed - //in the constructor for each image (i.e. the image-corresponding local storage) + // the following actions are always the same and thus can be performed + // in the constructor for each image (i.e. the image-corresponding local storage) m_TSFilter->ReleaseDataFlagOn(); mitk::LookupTable::Pointer mitkLUT = mitk::LookupTable::New(); - //built a default lookuptable + // built a default lookuptable mitkLUT->SetType(mitk::LookupTable::GRAYSCALE); m_DefaultLookupTable = mitkLUT->GetVtkLookupTable(); mitkLUT->SetType(mitk::LookupTable::LEGACY_BINARY); m_BinaryLookupTable = mitkLUT->GetVtkLookupTable(); mitkLUT->SetType(mitk::LookupTable::LEGACY_RAINBOW_COLOR); m_ColorLookupTable = mitkLUT->GetVtkLookupTable(); - //do not repeat the texture (the image) + // do not repeat the texture (the image) m_Texture->RepeatOff(); - //set the mapper for the actor - m_Actor->SetMapper( m_Mapper ); + // set the mapper for the actor + m_Actor->SetMapper(m_Mapper); vtkSmartPointer outlineShadowActor = vtkSmartPointer::New(); - outlineShadowActor->SetMapper( m_Mapper ); + outlineShadowActor->SetMapper(m_Mapper); - m_Actors->AddPart( outlineShadowActor ); - m_Actors->AddPart( m_Actor ); + m_Actors->AddPart(outlineShadowActor); + m_Actors->AddPart(m_Actor); } diff --git a/Modules/DiffusionImaging/DiffusionCore/src/Algorithms/mitkPartialVolumeAnalysisHistogramCalculator.cpp b/Modules/DiffusionImaging/DiffusionCore/src/Algorithms/mitkPartialVolumeAnalysisHistogramCalculator.cpp index 8951458069..1c4de5612d 100644 --- a/Modules/DiffusionImaging/DiffusionCore/src/Algorithms/mitkPartialVolumeAnalysisHistogramCalculator.cpp +++ b/Modules/DiffusionImaging/DiffusionCore/src/Algorithms/mitkPartialVolumeAnalysisHistogramCalculator.cpp @@ -1,1271 +1,1270 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPartialVolumeAnalysisHistogramCalculator.h" #include "mitkImageAccessByItk.h" #include "mitkExtractImageFilter.h" #include #include #include #include #include #include "itkResampleImageFilter.h" #include "itkGaussianInterpolateImageFunction.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "itkGaussianInterpolateImageFunction.h" #include "itkBSplineInterpolateImageFunction.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkImageMaskSpatialObject.h" #include "itkRegionOfInterestImageFilter.h" #include "itkListSample.h" #include "mitkAbstractTransformGeometry.h" #include #include -#include namespace mitk { PartialVolumeAnalysisHistogramCalculator::PartialVolumeAnalysisHistogramCalculator() : m_MaskingMode( MASKING_MODE_NONE ), m_MaskingModeChanged( false ), m_NumberOfBins(256), m_UpsamplingFactor(1), m_GaussianSigma(0), m_ForceUpdate(false), m_PlanarFigureThickness(0) { m_EmptyHistogram = HistogramType::New(); m_EmptyHistogram->SetMeasurementVectorSize(1); HistogramType::SizeType histogramSize(1); histogramSize.Fill( 256 ); m_EmptyHistogram->Initialize( histogramSize ); m_EmptyStatistics.Reset(); } PartialVolumeAnalysisHistogramCalculator::~PartialVolumeAnalysisHistogramCalculator() { } void PartialVolumeAnalysisHistogramCalculator::SetImage( const mitk::Image *image ) { if ( m_Image != image ) { m_Image = image; this->Modified(); m_ImageStatisticsTimeStamp.Modified(); m_ImageStatisticsCalculationTriggerBool = true; } } void PartialVolumeAnalysisHistogramCalculator::AddAdditionalResamplingImage( const mitk::Image *image ) { m_AdditionalResamplingImages.push_back(image); this->Modified(); m_ImageStatisticsTimeStamp.Modified(); m_ImageStatisticsCalculationTriggerBool = true; } void PartialVolumeAnalysisHistogramCalculator::SetModified( ) { this->Modified(); m_ImageStatisticsTimeStamp.Modified(); m_ImageStatisticsCalculationTriggerBool = true; m_MaskedImageStatisticsTimeStamp.Modified(); m_MaskedImageStatisticsCalculationTriggerBool = true; m_PlanarFigureStatisticsTimeStamp.Modified(); m_PlanarFigureStatisticsCalculationTriggerBool = true; } void PartialVolumeAnalysisHistogramCalculator::SetImageMask( const mitk::Image *imageMask ) { if ( m_Image.IsNull() ) { itkExceptionMacro( << "Image needs to be set first!" ); } if ( m_Image->GetTimeSteps() != imageMask->GetTimeSteps() ) { itkExceptionMacro( << "Image and image mask need to have equal number of time steps!" ); } if ( m_ImageMask != imageMask ) { m_ImageMask = imageMask; this->Modified(); m_MaskedImageStatisticsTimeStamp.Modified(); m_MaskedImageStatisticsCalculationTriggerBool = true; } } void PartialVolumeAnalysisHistogramCalculator::SetPlanarFigure( const mitk::PlanarFigure *planarFigure ) { if ( m_Image.IsNull() ) { itkExceptionMacro( << "Image needs to be set first!" ); } if ( m_PlanarFigure != planarFigure ) { m_PlanarFigure = planarFigure; this->Modified(); m_PlanarFigureStatisticsTimeStamp.Modified(); m_PlanarFigureStatisticsCalculationTriggerBool = true; } } void PartialVolumeAnalysisHistogramCalculator::SetMaskingMode( unsigned int mode ) { if ( m_MaskingMode != mode ) { m_MaskingMode = mode; m_MaskingModeChanged = true; this->Modified(); } } void PartialVolumeAnalysisHistogramCalculator::SetMaskingModeToNone() { if ( m_MaskingMode != MASKING_MODE_NONE ) { m_MaskingMode = MASKING_MODE_NONE; m_MaskingModeChanged = true; this->Modified(); } } void PartialVolumeAnalysisHistogramCalculator::SetMaskingModeToImage() { if ( m_MaskingMode != MASKING_MODE_IMAGE ) { m_MaskingMode = MASKING_MODE_IMAGE; m_MaskingModeChanged = true; this->Modified(); } } void PartialVolumeAnalysisHistogramCalculator::SetMaskingModeToPlanarFigure() { if ( m_MaskingMode != MASKING_MODE_PLANARFIGURE ) { m_MaskingMode = MASKING_MODE_PLANARFIGURE; m_MaskingModeChanged = true; this->Modified(); } } bool PartialVolumeAnalysisHistogramCalculator::ComputeStatistics() { MITK_DEBUG << "ComputeStatistics() start"; if ( m_Image.IsNull() ) { itkExceptionMacro( << "Image not set!" ); } if ( m_Image->GetReferenceCount() == 1 ) { MITK_DEBUG << "No Stats calculated; no one else holds a reference on it"; return false; } // If a mask was set but we are the only ones to still hold a reference on // it, delete it. if ( m_ImageMask.IsNotNull() && (m_ImageMask->GetReferenceCount() == 1) ) { m_ImageMask = nullptr; } // Check if statistics is already up-to-date unsigned long imageMTime = m_ImageStatisticsTimeStamp.GetMTime(); unsigned long maskedImageMTime = m_MaskedImageStatisticsTimeStamp.GetMTime(); unsigned long planarFigureMTime = m_PlanarFigureStatisticsTimeStamp.GetMTime(); bool imageStatisticsCalculationTrigger = m_ImageStatisticsCalculationTriggerBool; bool maskedImageStatisticsCalculationTrigger = m_MaskedImageStatisticsCalculationTriggerBool; bool planarFigureStatisticsCalculationTrigger = m_PlanarFigureStatisticsCalculationTriggerBool; if ( /*prevent calculation without mask*/!m_ForceUpdate &&( m_MaskingMode == MASKING_MODE_NONE || ( ((m_MaskingMode != MASKING_MODE_NONE) || (imageMTime > m_Image->GetMTime() && !imageStatisticsCalculationTrigger)) && ((m_MaskingMode != MASKING_MODE_IMAGE) || (m_ImageMask.IsNotNull() && maskedImageMTime > m_ImageMask->GetMTime() && !maskedImageStatisticsCalculationTrigger)) && ((m_MaskingMode != MASKING_MODE_PLANARFIGURE) || (m_PlanarFigure.IsNotNull() && planarFigureMTime > m_PlanarFigure->GetMTime() && !planarFigureStatisticsCalculationTrigger)) ) ) ) { MITK_DEBUG << "Returning, statistics already up to date!"; if ( m_MaskingModeChanged ) { m_MaskingModeChanged = false; return true; } else { return false; } } // Reset state changed flag m_MaskingModeChanged = false; // Depending on masking mode, extract and/or generate the required image // and mask data from the user input this->ExtractImageAndMask( ); Statistics *statistics; HistogramType::ConstPointer *histogram; switch ( m_MaskingMode ) { case MASKING_MODE_NONE: default: statistics = &m_ImageStatistics; histogram = &m_ImageHistogram; m_ImageStatisticsTimeStamp.Modified(); m_ImageStatisticsCalculationTriggerBool = false; break; case MASKING_MODE_IMAGE: statistics = &m_MaskedImageStatistics; histogram = &m_MaskedImageHistogram; m_MaskedImageStatisticsTimeStamp.Modified(); m_MaskedImageStatisticsCalculationTriggerBool = false; break; case MASKING_MODE_PLANARFIGURE: statistics = &m_PlanarFigureStatistics; histogram = &m_PlanarFigureHistogram; m_PlanarFigureStatisticsTimeStamp.Modified(); m_PlanarFigureStatisticsCalculationTriggerBool = false; break; } // Calculate statistics and histogram(s) if ( m_InternalImage->GetDimension() == 3 ) { if ( m_MaskingMode == MASKING_MODE_NONE ) { // Reset state changed flag AccessFixedDimensionByItk_2( m_InternalImage, InternalCalculateStatisticsUnmasked, 3, *statistics, histogram ); } else { AccessFixedDimensionByItk_3( m_InternalImage, InternalCalculateStatisticsMasked, 3, m_InternalImageMask3D.GetPointer(), *statistics, histogram ); } } else if ( m_InternalImage->GetDimension() == 2 ) { if ( m_MaskingMode == MASKING_MODE_NONE ) { AccessFixedDimensionByItk_2( m_InternalImage, InternalCalculateStatisticsUnmasked, 2, *statistics, histogram ); } else { AccessFixedDimensionByItk_3( m_InternalImage, InternalCalculateStatisticsMasked, 2, m_InternalImageMask2D.GetPointer(), *statistics, histogram ); } } else { MITK_ERROR << "ImageStatistics: Image dimension not supported!"; } // Release unused image smart pointers to free memory // m_InternalImage = mitk::Image::Pointer(); m_InternalImageMask3D = MaskImage3DType::Pointer(); m_InternalImageMask2D = MaskImage2DType::Pointer(); return true; } const PartialVolumeAnalysisHistogramCalculator::HistogramType * PartialVolumeAnalysisHistogramCalculator::GetHistogram( ) const { if ( m_Image.IsNull() ) { return nullptr; } switch ( m_MaskingMode ) { case MASKING_MODE_NONE: default: return m_ImageHistogram; case MASKING_MODE_IMAGE: return m_MaskedImageHistogram; case MASKING_MODE_PLANARFIGURE: return m_PlanarFigureHistogram; } } const PartialVolumeAnalysisHistogramCalculator::Statistics & PartialVolumeAnalysisHistogramCalculator::GetStatistics( ) const { if ( m_Image.IsNull() ) { return m_EmptyStatistics; } switch ( m_MaskingMode ) { case MASKING_MODE_NONE: default: return m_ImageStatistics; case MASKING_MODE_IMAGE: return m_MaskedImageStatistics; case MASKING_MODE_PLANARFIGURE: return m_PlanarFigureStatistics; } } void PartialVolumeAnalysisHistogramCalculator::ExtractImageAndMask( ) { MITK_DEBUG << "ExtractImageAndMask( ) start"; if ( m_Image.IsNull() ) { throw std::runtime_error( "Error: image empty!" ); } mitk::Image *timeSliceImage = const_cast(m_Image.GetPointer());//imageTimeSelector->GetOutput(); switch ( m_MaskingMode ) { case MASKING_MODE_NONE: { m_InternalImage = timeSliceImage; int s = m_AdditionalResamplingImages.size(); m_InternalAdditionalResamplingImages.resize(s); for(int i=0; i(m_AdditionalResamplingImages[i].GetPointer()); } m_InternalImageMask2D = nullptr; m_InternalImageMask3D = nullptr; break; } case MASKING_MODE_IMAGE: { if ( m_ImageMask.IsNotNull() && (m_ImageMask->GetReferenceCount() > 1) ) { ImageTimeSelector::Pointer maskedImageTimeSelector = ImageTimeSelector::New(); maskedImageTimeSelector->SetInput( m_ImageMask ); maskedImageTimeSelector->SetTimeNr( 0 ); maskedImageTimeSelector->UpdateLargestPossibleRegion(); mitk::Image *timeSliceMaskedImage = maskedImageTimeSelector->GetOutput(); InternalMaskImage(timeSliceMaskedImage); if(m_UpsamplingFactor != 1) { InternalResampleImage(m_InternalImageMask3D); } AccessFixedDimensionByItk_1( timeSliceImage, InternalResampleImageFromMask, 3, -1 ); int s = m_AdditionalResamplingImages.size(); m_InternalAdditionalResamplingImages.resize(s); for(int i=0; iIsClosed() ) { throw std::runtime_error( "Masking not possible for non-closed figures" ); } const BaseGeometry *imageGeometry = timeSliceImage->GetUpdatedGeometry(); if ( imageGeometry == nullptr ) { throw std::runtime_error( "Image geometry invalid!" ); } const PlaneGeometry *planarFigureGeometry2D = m_PlanarFigure->GetPlaneGeometry(); if ( planarFigureGeometry2D == nullptr ) { throw std::runtime_error( "Planar-Figure not yet initialized!" ); } const PlaneGeometry *planarFigureGeometry = dynamic_cast< const PlaneGeometry * >( planarFigureGeometry2D ); const AbstractTransformGeometry *abstrTransfGeometry = dynamic_cast< const AbstractTransformGeometry * >( planarFigureGeometry2D ); if ( !planarFigureGeometry || abstrTransfGeometry ) { throw std::runtime_error( "Only PlaneGeometry supported." ); } // unsigned int axis = 2; // unsigned int slice = 0; AccessFixedDimensionByItk_3( timeSliceImage, InternalReorientImagePlane, 3, timeSliceImage->GetGeometry(), m_PlanarFigure->GetGeometry(), -1 ); AccessFixedDimensionByItk_1( m_InternalImage, InternalCalculateMaskFromPlanarFigure, 3, 2 ); int s = m_AdditionalResamplingImages.size(); for(int i=0; iGetGeometry(), m_PlanarFigure->GetGeometry(), i ); AccessFixedDimensionByItk_1( m_InternalAdditionalResamplingImages[i], InternalCropAdditionalImage, 3, i ); } } } } bool PartialVolumeAnalysisHistogramCalculator::GetPrincipalAxis( const Geometry3D *geometry, Vector3D vector, unsigned int &axis ) { vector.Normalize(); for ( unsigned int i = 0; i < 3; ++i ) { Vector3D axisVector = geometry->GetAxisVector( i ); axisVector.Normalize(); if ( fabs( fabs( axisVector * vector ) - 1.0) < mitk::eps ) { axis = i; return true; } } return false; } void PartialVolumeAnalysisHistogramCalculator::InternalMaskImage( mitk::Image *image ) { typedef itk::ImageMaskSpatialObject<3> ImageMaskSpatialObject; typedef itk::Image< unsigned char, 3 > ImageType; typedef mitk::ImageToItk CastType; CastType::Pointer caster = CastType::New(); caster->SetInput(image); caster->Update(); ImageMaskSpatialObject::Pointer maskSO = ImageMaskSpatialObject::New(); maskSO->SetImage ( caster->GetOutput() ); m_InternalMask3D = maskSO->GetAxisAlignedBoundingBoxRegion(); // check if bounding box is empty, if so set it to 1,1,1 // to prevent empty mask image if (m_InternalMask3D.GetSize()[0] == 0 ) { m_InternalMask3D.SetSize(0,1); m_InternalMask3D.SetSize(1,1); m_InternalMask3D.SetSize(2,1); } MITK_DEBUG << "Bounding Box Region: " << m_InternalMask3D; // crop the mask image to the BoundingBoxRegion extracted via the spatial masking object typedef itk::RegionOfInterestImageFilter< ImageType, MaskImage3DType > ROIFilterType; ROIFilterType::Pointer roi = ROIFilterType::New(); roi->SetRegionOfInterest(m_InternalMask3D); roi->SetInput(caster->GetOutput()); roi->Update(); m_InternalImageMask3D = roi->GetOutput(); MITK_DEBUG << "Created m_InternalImageMask3D"; } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalReorientImagePlane( const itk::Image< TPixel, VImageDimension > *image, mitk::BaseGeometry* , mitk::BaseGeometry* planegeo3D, int additionalIndex ) { MITK_DEBUG << "InternalReorientImagePlane() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::Image< float, VImageDimension > FloatImageType; typedef itk::ResampleImageFilter ResamplerType; typename ResamplerType::Pointer resampler = ResamplerType::New(); mitk::PlaneGeometry* planegeo = dynamic_cast(planegeo3D); if ( !planegeo ) { throw std::runtime_error( "Unexpected null pointer returned for pointer to PlaneGeometry." ); } else { mitk::AbstractTransformGeometry* abstrGeo = dynamic_cast(planegeo3D); if ( abstrGeo ) { throw std::runtime_error( "Unexpected pointer to AbstractTransformGeometry returned." ); } } float upsamp = m_UpsamplingFactor; float gausssigma = m_GaussianSigma; // Spacing typename ResamplerType::SpacingType spacing = planegeo->GetSpacing(); spacing[0] = image->GetSpacing()[0] / upsamp; spacing[1] = image->GetSpacing()[1] / upsamp; spacing[2] = image->GetSpacing()[2]; if(m_PlanarFigureThickness) { spacing[2] = image->GetSpacing()[2] / upsamp; } resampler->SetOutputSpacing( spacing ); // Size typename ResamplerType::SizeType size; size[0] = planegeo->GetExtentInMM(0) / spacing[0]; size[1] = planegeo->GetExtentInMM(1) / spacing[1]; size[2] = 1+2*m_PlanarFigureThickness; // klaus add +2*m_PlanarFigureThickness MITK_DEBUG << "setting size2:="<SetSize( size ); // Origin typename mitk::Point3D orig = planegeo->GetOrigin(); typename mitk::Point3D corrorig; planegeo3D->WorldToIndex(orig,corrorig); corrorig[0] += 0.5/upsamp; corrorig[1] += 0.5/upsamp; if(m_PlanarFigureThickness) { float thickyyy = m_PlanarFigureThickness; thickyyy/=upsamp; corrorig[2] -= thickyyy; // klaus add -= (float)m_PlanarFigureThickness/upsamp statt += 0 } planegeo3D->IndexToWorld(corrorig,corrorig); resampler->SetOutputOrigin(corrorig ); // Direction typename ResamplerType::DirectionType direction; typename mitk::AffineTransform3D::MatrixType matrix = planegeo->GetIndexToWorldTransform()->GetMatrix(); for(unsigned int c = 0; c < matrix.ColumnDimensions; ++c) { double sum = 0; for(unsigned int r = 0 ; rSetOutputDirection( direction ); // Gaussian interpolation if(gausssigma != 0) { double sigma[3]; for( unsigned int d = 0; d < 3; d++ ) { sigma[d] = gausssigma * image->GetSpacing()[d]; } double alpha = 2.0; typedef itk::GaussianInterpolateImageFunction GaussianInterpolatorType; typename GaussianInterpolatorType::Pointer interpolator = GaussianInterpolatorType::New(); interpolator->SetInputImage( image ); interpolator->SetParameters( sigma, alpha ); resampler->SetInterpolator( interpolator ); } else { - // typedef typename itk::BSplineInterpolateImageFunction - // InterpolatorType; + // typedef typename itk::BSplineInterpolateImageFunction + // InterpolatorType; typedef typename itk::LinearInterpolateImageFunction InterpolatorType; typename InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage( image ); resampler->SetInterpolator( interpolator ); } // Other resampling options resampler->SetInput( image ); resampler->SetDefaultPixelValue(0); MITK_DEBUG << "Resampling requested image plane ... "; resampler->Update(); MITK_DEBUG << " ... done"; if(additionalIndex < 0) { this->m_InternalImage = mitk::Image::New(); this->m_InternalImage->InitializeByItk( resampler->GetOutput() ); this->m_InternalImage->SetVolume( resampler->GetOutput()->GetBufferPointer() ); } else { unsigned int myIndex = additionalIndex; this->m_InternalAdditionalResamplingImages.push_back(mitk::Image::New()); this->m_InternalAdditionalResamplingImages[myIndex]->InitializeByItk( resampler->GetOutput() ); this->m_InternalAdditionalResamplingImages[myIndex]->SetVolume( resampler->GetOutput()->GetBufferPointer() ); } } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalResampleImageFromMask( const itk::Image< TPixel, VImageDimension > *image, int additionalIndex ) { typedef itk::Image< TPixel, VImageDimension > ImageType; typename ImageType::Pointer outImage = ImageType::New(); outImage->SetSpacing( m_InternalImageMask3D->GetSpacing() ); // Set the image spacing outImage->SetOrigin( m_InternalImageMask3D->GetOrigin() ); // Set the image origin outImage->SetDirection( m_InternalImageMask3D->GetDirection() ); // Set the image direction outImage->SetRegions( m_InternalImageMask3D->GetLargestPossibleRegion() ); outImage->Allocate(); outImage->FillBuffer(0); typedef itk::InterpolateImageFunction BaseInterpType; typedef itk::GaussianInterpolateImageFunction GaussianInterpolatorType; typedef itk::LinearInterpolateImageFunction LinearInterpolatorType; typename BaseInterpType::Pointer interpolator; if(m_GaussianSigma != 0) { double sigma[3]; for( unsigned int d = 0; d < 3; d++ ) { sigma[d] = m_GaussianSigma * image->GetSpacing()[d]; } double alpha = 2.0; interpolator = GaussianInterpolatorType::New(); dynamic_cast(interpolator.GetPointer())->SetParameters( sigma, alpha ); } else { interpolator = LinearInterpolatorType::New(); } interpolator->SetInputImage( image ); itk::ImageRegionConstIterator itmask(m_InternalImageMask3D, m_InternalImageMask3D->GetLargestPossibleRegion()); itk::ImageRegionIterator itimage(outImage, outImage->GetLargestPossibleRegion()); itmask.GoToBegin(); itimage.GoToBegin(); itk::Point< double, 3 > point; itk::ContinuousIndex< double, 3 > index; while( !itmask.IsAtEnd() ) { if(itmask.Get() != 0) { outImage->TransformIndexToPhysicalPoint (itimage.GetIndex(), point); image->TransformPhysicalPointToContinuousIndex(point, index); itimage.Set(interpolator->EvaluateAtContinuousIndex(index)); } ++itmask; ++itimage; } if(additionalIndex < 0) { this->m_InternalImage = mitk::Image::New(); this->m_InternalImage->InitializeByItk( outImage.GetPointer() ); this->m_InternalImage->SetVolume( outImage->GetBufferPointer() ); } else { this->m_InternalAdditionalResamplingImages[additionalIndex] = mitk::Image::New(); this->m_InternalAdditionalResamplingImages[additionalIndex]->InitializeByItk( outImage.GetPointer() ); this->m_InternalAdditionalResamplingImages[additionalIndex]->SetVolume( outImage->GetBufferPointer() ); } } void PartialVolumeAnalysisHistogramCalculator::InternalResampleImage( const MaskImage3DType *image ) { typedef itk::ResampleImageFilter ResamplerType; ResamplerType::Pointer resampler = ResamplerType::New(); // Size ResamplerType::SizeType size; size[0] = m_UpsamplingFactor * image->GetLargestPossibleRegion().GetSize()[0]; size[1] = m_UpsamplingFactor * image->GetLargestPossibleRegion().GetSize()[1]; size[2] = m_UpsamplingFactor * image->GetLargestPossibleRegion().GetSize()[2];; resampler->SetSize( size ); // Origin mitk::Point3D orig = image->GetOrigin(); resampler->SetOutputOrigin(orig ); // Spacing ResamplerType::SpacingType spacing; spacing[0] = image->GetSpacing()[0] / m_UpsamplingFactor; spacing[1] = image->GetSpacing()[1] / m_UpsamplingFactor; spacing[2] = image->GetSpacing()[2] / m_UpsamplingFactor; resampler->SetOutputSpacing( spacing ); resampler->SetOutputDirection( image->GetDirection() ); typedef itk::NearestNeighborInterpolateImageFunction InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetInputImage( image ); resampler->SetInterpolator( interpolator ); // Other resampling options resampler->SetInput( image ); resampler->SetDefaultPixelValue(0); resampler->Update(); m_InternalImageMask3D = resampler->GetOutput(); } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalCalculateStatisticsUnmasked( const itk::Image< TPixel, VImageDimension > *image, Statistics &statistics, typename HistogramType::ConstPointer *histogram ) { MITK_DEBUG << "InternalCalculateStatisticsUnmasked()"; typedef itk::Image< TPixel, VImageDimension > ImageType; // Progress listening... typedef itk::SimpleMemberCommand< PartialVolumeAnalysisHistogramCalculator > ITKCommandType; ITKCommandType::Pointer progressListener; progressListener = ITKCommandType::New(); progressListener->SetCallbackFunction( this, &PartialVolumeAnalysisHistogramCalculator::UnmaskedStatisticsProgressUpdate ); // Issue 100 artificial progress events since ScalarIMageToHistogramGenerator // does not (yet?) support progress reporting this->InvokeEvent( itk::StartEvent() ); for ( unsigned int i = 0; i < 100; ++i ) { this->UnmaskedStatisticsProgressUpdate(); } // Calculate statistics (separate filter) typedef itk::StatisticsImageFilter< ImageType > StatisticsFilterType; typename StatisticsFilterType::Pointer statisticsFilter = StatisticsFilterType::New(); statisticsFilter->SetInput( image ); unsigned long observerTag = statisticsFilter->AddObserver( itk::ProgressEvent(), progressListener ); statisticsFilter->Update(); statisticsFilter->RemoveObserver( observerTag ); this->InvokeEvent( itk::EndEvent() ); statistics.N = image->GetBufferedRegion().GetNumberOfPixels(); statistics.Min = statisticsFilter->GetMinimum(); statistics.Max = statisticsFilter->GetMaximum(); statistics.Mean = statisticsFilter->GetMean(); statistics.Median = 0.0; statistics.Sigma = statisticsFilter->GetSigma(); statistics.RMS = sqrt( statistics.Mean * statistics.Mean + statistics.Sigma * statistics.Sigma ); typename ImageType::Pointer inImage = const_cast(image); // Calculate histogram typedef itk::Statistics::ScalarImageToHistogramGenerator< ImageType > HistogramGeneratorType; typename HistogramGeneratorType::Pointer histogramGenerator = HistogramGeneratorType::New(); histogramGenerator->SetInput( inImage ); histogramGenerator->SetMarginalScale( 10 ); // Defines y-margin width of histogram histogramGenerator->SetNumberOfBins( m_NumberOfBins ); // CT range [-1024, +2048] --> bin size 4 values histogramGenerator->SetHistogramMin( statistics.Min ); histogramGenerator->SetHistogramMax( statistics.Max ); histogramGenerator->Compute(); *histogram = histogramGenerator->GetOutput(); } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalCalculateStatisticsMasked( const itk::Image< TPixel, VImageDimension > *image, itk::Image< unsigned char, VImageDimension > *maskImage, Statistics &, typename HistogramType::ConstPointer *histogram ) { MITK_DEBUG << "InternalCalculateStatisticsMasked() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::Image< unsigned char, VImageDimension > MaskImageType; // generate a list sample of angles at positions // where the fiber-prob is higher than .2*maxprob typedef TPixel MeasurementType; const unsigned int MeasurementVectorLength = 1; typedef itk::Vector< MeasurementType , MeasurementVectorLength > MeasurementVectorType; typedef itk::Statistics::ListSample< MeasurementVectorType > ListSampleType; typename ListSampleType::Pointer listSample = ListSampleType::New(); listSample->SetMeasurementVectorSize( MeasurementVectorLength ); itk::ImageRegionConstIterator itmask(maskImage, maskImage->GetLargestPossibleRegion()); itk::ImageRegionConstIterator itimage(image, image->GetLargestPossibleRegion()); itmask.GoToBegin(); itimage.GoToBegin(); while( !itmask.IsAtEnd() ) { if(itmask.Get() != 0) { // apend to list MeasurementVectorType mv; mv[0] = ( MeasurementType ) itimage.Get(); listSample->PushBack(mv); } ++itmask; ++itimage; } // generate a histogram from the list sample typedef double HistogramMeasurementType; typedef itk::Statistics::Histogram< HistogramMeasurementType, itk::Statistics::DenseFrequencyContainer2 > HistogramType; typedef itk::Statistics::SampleToHistogramFilter< ListSampleType, HistogramType > GeneratorType; typename GeneratorType::Pointer generator = GeneratorType::New(); typename GeneratorType::HistogramType::SizeType size(MeasurementVectorLength); size.Fill(m_NumberOfBins); generator->SetHistogramSize( size ); generator->SetInput( listSample ); generator->SetMarginalScale( 10.0 ); generator->Update(); *histogram = generator->GetOutput(); } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalCropAdditionalImage( itk::Image< TPixel, VImageDimension > *image, int additionalIndex ) { typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::RegionOfInterestImageFilter< ImageType, ImageType > ROIFilterType; typename ROIFilterType::Pointer roi = ROIFilterType::New(); roi->SetRegionOfInterest(m_CropRegion); roi->SetInput(image); roi->Update(); m_InternalAdditionalResamplingImages[additionalIndex] = mitk::Image::New(); m_InternalAdditionalResamplingImages[additionalIndex]->InitializeByItk(roi->GetOutput()); m_InternalAdditionalResamplingImages[additionalIndex]->SetVolume(roi->GetOutput()->GetBufferPointer()); } template < typename TPixel, unsigned int VImageDimension > void PartialVolumeAnalysisHistogramCalculator::InternalCalculateMaskFromPlanarFigure( itk::Image< TPixel, VImageDimension > *image, unsigned int axis ) { MITK_DEBUG << "InternalCalculateMaskFromPlanarFigure() start"; typedef itk::Image< TPixel, VImageDimension > ImageType; // Generate mask image as new image with same header as input image and // initialize with "1". MaskImage3DType::Pointer newMaskImage = MaskImage3DType::New(); newMaskImage->SetSpacing( image->GetSpacing() ); // Set the image spacing newMaskImage->SetOrigin( image->GetOrigin() ); // Set the image origin newMaskImage->SetDirection( image->GetDirection() ); // Set the image direction newMaskImage->SetRegions( image->GetLargestPossibleRegion() ); newMaskImage->Allocate(); newMaskImage->FillBuffer( 1 ); // Generate VTK polygon from (closed) PlanarFigure polyline // (The polyline points are shifted by -0.5 in z-direction to make sure // that the extrusion filter, which afterwards elevates all points by +0.5 // in z-direction, creates a 3D object which is cut by the the plane z=0) const mitk::PlaneGeometry *planarFigureGeometry2D = m_PlanarFigure->GetPlaneGeometry(); const typename PlanarFigure::PolyLineType planarFigurePolyline = m_PlanarFigure->GetPolyLine( 0 ); const mitk::BaseGeometry *imageGeometry3D = m_InternalImage->GetGeometry( 0 ); vtkPolyData *polyline = vtkPolyData::New(); polyline->Allocate( 1, 1 ); // Determine x- and y-dimensions depending on principal axis int i0, i1; switch ( axis ) { case 0: i0 = 1; i1 = 2; break; case 1: i0 = 0; i1 = 2; break; case 2: default: i0 = 0; i1 = 1; break; } // Create VTK polydata object of polyline contour bool outOfBounds = false; vtkPoints *points = vtkPoints::New(); typename PlanarFigure::PolyLineType::const_iterator it; for ( it = planarFigurePolyline.begin(); it != planarFigurePolyline.end(); ++it ) { Point3D point3D; // Convert 2D point back to the local index coordinates of the selected // image mitk::Point2D point2D = *it; planarFigureGeometry2D->WorldToIndex(point2D, point2D); point2D[0] -= 0.5/m_UpsamplingFactor; point2D[1] -= 0.5/m_UpsamplingFactor; planarFigureGeometry2D->IndexToWorld(point2D, point2D); planarFigureGeometry2D->Map( point2D, point3D ); // Polygons (partially) outside of the image bounds can not be processed // further due to a bug in vtkPolyDataToImageStencil if ( !imageGeometry3D->IsInside( point3D ) ) { outOfBounds = true; } imageGeometry3D->WorldToIndex( point3D, point3D ); point3D[i0] += 0.5; point3D[i1] += 0.5; // Add point to polyline array points->InsertNextPoint( point3D[i0], point3D[i1], -0.5 ); } polyline->SetPoints( points ); points->Delete(); if ( outOfBounds ) { polyline->Delete(); throw std::runtime_error( "Figure at least partially outside of image bounds!" ); } std::size_t numberOfPoints = planarFigurePolyline.size(); auto ptIds = new vtkIdType[numberOfPoints]; for ( std::size_t i = 0; i < numberOfPoints; ++i ) { ptIds[i] = i; } polyline->InsertNextCell( VTK_POLY_LINE, numberOfPoints, ptIds ); // Extrude the generated contour polygon vtkLinearExtrusionFilter *extrudeFilter = vtkLinearExtrusionFilter::New(); extrudeFilter->SetInputData( polyline ); extrudeFilter->SetScaleFactor( 1 ); extrudeFilter->SetExtrusionTypeToNormalExtrusion(); extrudeFilter->SetVector( 0.0, 0.0, 1.0 ); // Make a stencil from the extruded polygon vtkPolyDataToImageStencil *polyDataToImageStencil = vtkPolyDataToImageStencil::New(); polyDataToImageStencil->SetInputConnection( extrudeFilter->GetOutputPort() ); // Export from ITK to VTK (to use a VTK filter) typedef itk::VTKImageImport< MaskImage3DType > ImageImportType; typedef itk::VTKImageExport< MaskImage3DType > ImageExportType; typename ImageExportType::Pointer itkExporter = ImageExportType::New(); itkExporter->SetInput( newMaskImage ); vtkImageImport *vtkImporter = vtkImageImport::New(); this->ConnectPipelines( itkExporter, vtkImporter ); vtkImporter->Update(); // Apply the generated image stencil to the input image vtkImageStencil *imageStencilFilter = vtkImageStencil::New(); imageStencilFilter->SetInputData( vtkImporter->GetOutput() ); imageStencilFilter->SetStencilConnection(polyDataToImageStencil->GetOutputPort() ); imageStencilFilter->ReverseStencilOff(); imageStencilFilter->SetBackgroundValue( 0 ); imageStencilFilter->Update(); // Export from VTK back to ITK vtkImageExport *vtkExporter = vtkImageExport::New(); vtkExporter->SetInputData( imageStencilFilter->GetOutput() ); vtkExporter->Update(); typename ImageImportType::Pointer itkImporter = ImageImportType::New(); this->ConnectPipelines( vtkExporter, itkImporter ); itkImporter->Update(); // calculate cropping bounding box m_InternalImageMask3D = itkImporter->GetOutput(); m_InternalImageMask3D->SetDirection(image->GetDirection()); itk::ImageRegionIterator itmask(m_InternalImageMask3D, m_InternalImageMask3D->GetLargestPossibleRegion()); itmask.GoToBegin(); while( !itmask.IsAtEnd() ) { if(itmask.Get() != 0) { typename ImageType::IndexType index = itmask.GetIndex(); for(unsigned int thick=0; thick<2*m_PlanarFigureThickness+1; thick++) { index[axis] = thick; m_InternalImageMask3D->SetPixel(index, itmask.Get()); } } ++itmask; } itmask.GoToBegin(); itk::ImageRegionIterator itimage(image, image->GetLargestPossibleRegion()); itimage.GoToBegin(); typename ImageType::SizeType lowersize; lowersize.Fill(std::numeric_limits::max()); typename ImageType::SizeType uppersize; uppersize.Fill(std::numeric_limits::min()); while( !itmask.IsAtEnd() ) { if(itmask.Get() == 0) { itimage.Set(0); } else { typename ImageType::IndexType index = itimage.GetIndex(); typename ImageType::SizeType signedindex; signedindex[0] = index[0]; signedindex[1] = index[1]; signedindex[2] = index[2]; lowersize[0] = signedindex[0] < lowersize[0] ? signedindex[0] : lowersize[0]; lowersize[1] = signedindex[1] < lowersize[1] ? signedindex[1] : lowersize[1]; lowersize[2] = signedindex[2] < lowersize[2] ? signedindex[2] : lowersize[2]; uppersize[0] = signedindex[0] > uppersize[0] ? signedindex[0] : uppersize[0]; uppersize[1] = signedindex[1] > uppersize[1] ? signedindex[1] : uppersize[1]; uppersize[2] = signedindex[2] > uppersize[2] ? signedindex[2] : uppersize[2]; } ++itmask; ++itimage; } typename ImageType::IndexType index; index[0] = lowersize[0]; index[1] = lowersize[1]; index[2] = lowersize[2]; typename ImageType::SizeType size; size[0] = uppersize[0] - lowersize[0] + 1; size[1] = uppersize[1] - lowersize[1] + 1; size[2] = uppersize[2] - lowersize[2] + 1; m_CropRegion = itk::ImageRegion<3>(index, size); // crop internal image typedef itk::RegionOfInterestImageFilter< ImageType, ImageType > ROIFilterType; typename ROIFilterType::Pointer roi = ROIFilterType::New(); roi->SetRegionOfInterest(m_CropRegion); roi->SetInput(image); roi->Update(); m_InternalImage = mitk::Image::New(); m_InternalImage->InitializeByItk(roi->GetOutput()); m_InternalImage->SetVolume(roi->GetOutput()->GetBufferPointer()); // crop internal mask typedef itk::RegionOfInterestImageFilter< MaskImage3DType, MaskImage3DType > ROIMaskFilterType; typename ROIMaskFilterType::Pointer roi2 = ROIMaskFilterType::New(); roi2->SetRegionOfInterest(m_CropRegion); roi2->SetInput(m_InternalImageMask3D); roi2->Update(); m_InternalImageMask3D = roi2->GetOutput(); // Clean up VTK objects polyline->Delete(); extrudeFilter->Delete(); polyDataToImageStencil->Delete(); vtkImporter->Delete(); imageStencilFilter->Delete(); //vtkExporter->Delete(); // TODO: crashes when outcommented; memory leak?? delete[] ptIds; } void PartialVolumeAnalysisHistogramCalculator::UnmaskedStatisticsProgressUpdate() { // Need to throw away every second progress event to reach a final count of // 100 since two consecutive filters are used in this case static int updateCounter = 0; if ( updateCounter++ % 2 == 0 ) { this->InvokeEvent( itk::ProgressEvent() ); } } void PartialVolumeAnalysisHistogramCalculator::MaskedStatisticsProgressUpdate() { this->InvokeEvent( itk::ProgressEvent() ); } } diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleMapper2D.cpp b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleMapper2D.cpp index 1ba79aa637..4ce6bd00b2 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleMapper2D.cpp +++ b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleMapper2D.cpp @@ -1,198 +1,291 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkFiberBundleMapper2D.h" -#include +#include "mitkBaseRenderer.h" +#include "mitkDataNode.h" #include -#include +#include +#include +#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include -#include #include +class vtkShaderCallback : public vtkCommand +{ +public: + static vtkShaderCallback *New() + { + return new vtkShaderCallback; + } + mitk::BaseRenderer *renderer; + mitk::DataNode *node; + + virtual void Execute(vtkObject *, unsigned long, void*cbo) + { + vtkOpenGLHelper *cellBO = reinterpret_cast(cbo); + + float fiberOpacity; + int fiberFading = 300; + float fiberThickness; + + node->GetOpacity(fiberOpacity, nullptr); + node->GetFloatProperty("shader.mitkShaderFiberClipping.fiberThickness", fiberThickness); + node->GetIntProperty("shader.mitkShaderFiberClipping.fiberFadingON", fiberFading); + + cellBO->Program->SetUniformf("fiberOpacity", fiberOpacity); + cellBO->Program->SetUniformi("fiberFadingON", fiberFading); + cellBO->Program->SetUniformf("fiberThickness", fiberThickness); + + if (this->renderer) + { + //get information about current position of views + mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController(); + mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry(); + + //generate according cutting planes based on the view position + float planeNormal[3]; + planeNormal[0] = planeGeo->GetNormal()[0]; + planeNormal[1] = planeGeo->GetNormal()[1]; + planeNormal[2] = planeGeo->GetNormal()[2]; + + float tmp1 = planeGeo->GetOrigin()[0] * planeNormal[0]; + float tmp2 = planeGeo->GetOrigin()[1] * planeNormal[1]; + float tmp3 = planeGeo->GetOrigin()[2] * planeNormal[2]; + float thickness = tmp1 + tmp2 + tmp3; //attention, correct normalvector + + node->SetFloatProperty("shader.mitkShaderFiberClipping.slicingPlane.w", thickness, renderer); + node->SetFloatProperty("shader.mitkShaderFiberClipping.slicingPlane.x", planeNormal[0], renderer); + node->SetFloatProperty("shader.mitkShaderFiberClipping.slicingPlane.y", planeNormal[1], renderer); + node->SetFloatProperty("shader.mitkShaderFiberClipping.slicingPlane.z", planeNormal[2], renderer); + + float* a = new float[4]; + for (int i = 0; i < 3; ++i) + a[i] = planeNormal[i]; + + a[3] = thickness; + cellBO->Program->SetUniform4f("slicingPlane", a); + + } + } + + vtkShaderCallback() { this->renderer = 0; } +}; + + + mitk::FiberBundleMapper2D::FiberBundleMapper2D() : m_LineWidth(1) { m_lut = vtkLookupTable::New(); m_lut->Build(); } mitk::FiberBundleMapper2D::~FiberBundleMapper2D() { } mitk::FiberBundle* mitk::FiberBundleMapper2D::GetInput() { return dynamic_cast< mitk::FiberBundle * > ( GetDataNode()->GetData() ); } void mitk::FiberBundleMapper2D::Update(mitk::BaseRenderer * renderer) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if ( !visible ) return; // Calculate time step of the input data for the specified renderer (integer value) // this method is implemented in mitkMapper this->CalculateTimeStep( renderer ); //check if updates occured in the node or on the display FBXLocalStorage *localStorage = m_LocalStorageHandler.GetLocalStorage(renderer); //set renderer independent shader properties const DataNode::Pointer node = this->GetDataNode(); float thickness = 2.0; if(!this->GetDataNode()->GetPropertyValue("Fiber2DSliceThickness",thickness)) MITK_INFO << "FIBER2D SLICE THICKNESS PROPERTY ERROR"; bool fiberfading = false; if(!this->GetDataNode()->GetPropertyValue("Fiber2DfadeEFX",fiberfading)) MITK_INFO << "FIBER2D SLICE FADE EFX PROPERTY ERROR"; float fiberOpacity; this->GetDataNode()->GetOpacity(fiberOpacity, nullptr); node->SetFloatProperty("shader.mitkShaderFiberClipping.fiberThickness",thickness); node->SetIntProperty("shader.mitkShaderFiberClipping.fiberFadingON",fiberfading); node->SetFloatProperty("shader.mitkShaderFiberClipping.fiberOpacity",fiberOpacity); mitk::FiberBundle* fiberBundle = this->GetInput(); if (fiberBundle==nullptr) return; int lineWidth = 0; node->GetIntProperty("LineWidth", lineWidth); if (m_LineWidth!=lineWidth) { m_LineWidth = lineWidth; fiberBundle->RequestUpdate2D(); } if ( localStorage->m_LastUpdateTimeGetCurrentWorldPlaneGeometryUpdateTime() || localStorage->m_LastUpdateTimeGetUpdateTime2D() ) { this->UpdateShaderParameter(renderer); this->GenerateDataForRenderer( renderer ); } } void mitk::FiberBundleMapper2D::UpdateShaderParameter(mitk::BaseRenderer * renderer) { - //get information about current position of views - mitk::SliceNavigationController::Pointer sliceContr = renderer->GetSliceNavigationController(); - mitk::PlaneGeometry::ConstPointer planeGeo = sliceContr->GetCurrentPlaneGeometry(); - - //generate according cutting planes based on the view position - float planeNormal[3]; - planeNormal[0] = planeGeo->GetNormal()[0]; - planeNormal[1] = planeGeo->GetNormal()[1]; - planeNormal[2] = planeGeo->GetNormal()[2]; - - float tmp1 = planeGeo->GetOrigin()[0] * planeNormal[0]; - float tmp2 = planeGeo->GetOrigin()[1] * planeNormal[1]; - float tmp3 = planeGeo->GetOrigin()[2] * planeNormal[2]; - float thickness = tmp1 + tmp2 + tmp3; //attention, correct normalvector - - DataNode::Pointer node = this->GetDataNode(); - node->SetFloatProperty("shader.mitkShaderFiberClipping.slicingPlane.w",thickness,renderer); - node->SetFloatProperty("shader.mitkShaderFiberClipping.slicingPlane.x",planeNormal[0],renderer); - node->SetFloatProperty("shader.mitkShaderFiberClipping.slicingPlane.y",planeNormal[1],renderer); - node->SetFloatProperty("shader.mitkShaderFiberClipping.slicingPlane.z",planeNormal[2],renderer); + // see new vtkShaderCallback + } // vtkActors and Mappers are feeded here void mitk::FiberBundleMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { - mitk::FiberBundle* fiberBundle = this->GetInput(); - - //the handler of local storage gets feeded in this method with requested data for related renderwindow - FBXLocalStorage *localStorage = m_LocalStorageHandler.GetLocalStorage(renderer); - - mitk::DataNode* node = this->GetDataNode(); - if ( node == nullptr ) - return; - - vtkSmartPointer fiberPolyData = fiberBundle->GetFiberPolyData(); - if (fiberPolyData == nullptr) - return; - - fiberPolyData->GetPointData()->AddArray(fiberBundle->GetFiberColors()); - localStorage->m_FiberMapper->ScalarVisibilityOn(); - localStorage->m_FiberMapper->SetScalarModeToUsePointFieldData(); - localStorage->m_FiberMapper->SetLookupTable(m_lut); //apply the properties after the slice was set - localStorage->m_PointActor->GetProperty()->SetOpacity(0.999); - localStorage->m_FiberMapper->SelectColorArray("FIBER_COLORS"); - - localStorage->m_FiberMapper->SetInputData(fiberPolyData); - localStorage->m_PointActor->SetMapper(localStorage->m_FiberMapper); - localStorage->m_PointActor->GetProperty()->ShadingOn(); - localStorage->m_PointActor->GetProperty()->SetLineWidth(m_LineWidth); - - // Applying shading properties - this->ApplyShaderProperties(renderer); - - // We have been modified => save this for next Update() - localStorage->m_LastUpdateTime.Modified(); + mitk::FiberBundle* fiberBundle = this->GetInput(); + + //the handler of local storage gets feeded in this method with requested data for related renderwindow + FBXLocalStorage *localStorage = m_LocalStorageHandler.GetLocalStorage(renderer); + + mitk::DataNode* node = this->GetDataNode(); + if (node == nullptr) + return; + + vtkSmartPointer fiberPolyData = fiberBundle->GetFiberPolyData(); + if (fiberPolyData == nullptr) + return; + + fiberPolyData->GetPointData()->AddArray(fiberBundle->GetFiberColors()); + localStorage->m_FiberMapper->ScalarVisibilityOn(); + localStorage->m_FiberMapper->SetScalarModeToUsePointFieldData(); + localStorage->m_FiberMapper->SetLookupTable(m_lut); //apply the properties after the slice was set + localStorage->m_PointActor->GetProperty()->SetOpacity(0.999); + localStorage->m_FiberMapper->SelectColorArray("FIBER_COLORS"); + + localStorage->m_FiberMapper->SetInputData(fiberPolyData); + localStorage->m_FiberMapper->SetVertexShaderCode( + "//VTK::System::Dec\n" + "attribute vec4 vertexMC;\n" + + "//VTK::Normal::Dec\n" + "uniform mat4 MCDCMatrix;\n" + + "//VTK::Color::Dec\n" + + "varying vec4 positionWorld;\n" + "varying vec4 colorVertex;\n" + + "void main(void)\n" + "{\n" + " colorVertex = scalarColor;\n" + " positionWorld = vertexMC;\n" + " gl_Position = MCDCMatrix * vertexMC;\n" + "}\n" + ); + localStorage->m_FiberMapper->SetFragmentShaderCode( + "//VTK::System::Dec\n" // always start with this line + "//VTK::Output::Dec\n" // always have this line in your FS + "uniform vec4 slicingPlane;\n" + "uniform float fiberThickness;\n" + "uniform int fiberFadingON;\n" + "uniform float fiberOpacity;\n" + + "varying vec4 positionWorld;\n" + "varying vec4 colorVertex;\n" + + "void main(void)\n" + "{\n" + " float r1 = dot(positionWorld.xyz, slicingPlane.xyz) - slicingPlane.w;\n" + + " if (abs(r1) >= fiberThickness)\n" + " discard;\n" + + " if (fiberFadingON != 0)\n" + " {\n" + " float x = (r1 + fiberThickness) / (fiberThickness*2.0);\n" + " x = 1.0 - x;\n" + " gl_FragColor = vec4(colorVertex.xyz*x, fiberOpacity);\n" + " }\n" + " else{\n" + " gl_FragColor = vec4(colorVertex.xyz,fiberOpacity);\n" + " }\n" + "}\n" + ); + + vtkSmartPointer myCallback = vtkSmartPointer::New(); + myCallback->renderer = renderer; + myCallback->node = this->GetDataNode(); + localStorage->m_FiberMapper->AddObserver(vtkCommand::UpdateShaderEvent,myCallback); + + localStorage->m_PointActor->SetMapper(localStorage->m_FiberMapper); + localStorage->m_PointActor->GetProperty()->ShadingOn(); + localStorage->m_PointActor->GetProperty()->SetLineWidth(m_LineWidth); + + // Applying shading properties + this->ApplyShaderProperties(renderer); + + // We have been modified => save this for next Update() + localStorage->m_LastUpdateTime.Modified(); } vtkProp* mitk::FiberBundleMapper2D::GetVtkProp(mitk::BaseRenderer *renderer) { this->Update(renderer); return m_LocalStorageHandler.GetLocalStorage(renderer)->m_PointActor; } void mitk::FiberBundleMapper2D::SetDefaultProperties(mitk::DataNode* node, mitk::BaseRenderer* renderer, bool overwrite) { Superclass::SetDefaultProperties(node, renderer, overwrite); - node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping")); - - // Shaders - IShaderRepository* shaderRepo = CoreServices::GetShaderRepository(); - if (shaderRepo) - { - shaderRepo->AddDefaultProperties(node, renderer, overwrite); - } +// node->SetProperty("shader",mitk::ShaderProperty::New("mitkShaderFiberClipping")); //add other parameters to propertylist node->AddProperty( "Fiber2DSliceThickness", mitk::FloatProperty::New(1.0f), renderer, overwrite ); node->AddProperty( "Fiber2DfadeEFX", mitk::BoolProperty::New(true), renderer, overwrite ); node->AddProperty( "color", mitk::ColorProperty::New(1.0,1.0,1.0), renderer, overwrite); } mitk::FiberBundleMapper2D::FBXLocalStorage::FBXLocalStorage() { m_PointActor = vtkSmartPointer::New(); - m_FiberMapper = vtkSmartPointer::New(); + m_FiberMapper = vtkSmartPointer::New(); } diff --git a/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleMapper2D.h b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleMapper2D.h index 538174c223..984e79a0d0 100644 --- a/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleMapper2D.h +++ b/Modules/DiffusionImaging/DiffusionIO/mitkFiberBundleMapper2D.h @@ -1,109 +1,110 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef FiberBundleMAPPER2D_H_HEADER_INCLUDED #define FiberBundleMAPPER2D_H_HEADER_INCLUDED //MITK Rendering #include #include //#include #include #include #include +#define MITKFIBERBUNDLEMAPPER2D_POLYDATAMAPPER vtkOpenGLPolyDataMapper class vtkActor; //class vtkPropAssembly; //lets see if we need it class mitkBaseRenderer; -class vtkPolyDataMapper; +class MITKFIBERBUNDLEMAPPER2D_POLYDATAMAPPER; class vtkCutter; class vtkPlane; class vtkPolyData; namespace mitk { struct IShaderRepository; class FiberBundleMapper2D : public VtkMapper { public: mitkClassMacro(FiberBundleMapper2D, VtkMapper); itkFactorylessNewMacro(Self) itkCloneMacro(Self) mitk::FiberBundle* GetInput(); /** \brief Checks whether this mapper needs to update itself and generate data. */ virtual void Update(mitk::BaseRenderer * renderer) override; static void SetDefaultProperties(DataNode* node, BaseRenderer* renderer = nullptr, bool overwrite = false ); //### methods of MITK-VTK rendering pipeline virtual vtkProp* GetVtkProp(mitk::BaseRenderer* renderer) override; //### end of methods of MITK-VTK rendering pipeline class FBXLocalStorage : public mitk::Mapper::BaseLocalStorage { public: /** \brief Point Actor of a 2D render window. */ vtkSmartPointer m_PointActor; /** \brief Point Mapper of a 2D render window. */ - vtkSmartPointer m_FiberMapper; + vtkSmartPointer m_FiberMapper; vtkSmartPointer m_SlicingPlane; //needed later when optimized 2D mapper vtkSmartPointer m_SlicedResult; //might be depricated in optimized 2D mapper /** \brief Timestamp of last update of stored data. */ itk::TimeStamp m_LastUpdateTime; /** \brief Constructor of the local storage. Do as much actions as possible in here to avoid double executions. */ FBXLocalStorage(); //if u copy&paste from this 2Dmapper, be aware that the implementation of this constructor is in the cpp file ~FBXLocalStorage() { } }; /** \brief This member holds all three LocalStorages for the three 2D render windows. */ mitk::LocalStorageHandler m_LocalStorageHandler; protected: FiberBundleMapper2D(); virtual ~FiberBundleMapper2D(); /** Does the actual resampling, without rendering. */ virtual void GenerateDataForRenderer(mitk::BaseRenderer*) override; void UpdateShaderParameter(mitk::BaseRenderer*); private: vtkSmartPointer m_lut; int m_LineWidth; }; }//end namespace #endif diff --git a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkStreamlineTrackingFilter.h b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkStreamlineTrackingFilter.h index 7a74725311..c4a7b68b95 100644 --- a/Modules/DiffusionImaging/FiberTracking/Algorithms/itkStreamlineTrackingFilter.h +++ b/Modules/DiffusionImaging/FiberTracking/Algorithms/itkStreamlineTrackingFilter.h @@ -1,222 +1,221 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __itkMLBSTrackingFilter_h_ #define __itkMLBSTrackingFilter_h_ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace itk{ /** * \brief Performs streamline tracking on the input image. Depending on the tracking handler this can be a tensor, peak or machine learning based tracking. */ class MITKFIBERTRACKING_EXPORT StreamlineTrackingFilter : public ProcessObject { public: typedef StreamlineTrackingFilter Self; typedef SmartPointer Pointer; typedef SmartPointer ConstPointer; typedef ProcessObject Superclass; /** Method for creation through the object factory. */ itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** Runtime information support. */ itkTypeMacro(MLBSTrackingFilter, ImageToImageFilter) typedef itk::Image ItkUcharImgType; typedef itk::Image ItkDoubleImgType; typedef itk::Image ItkFloatImgType; typedef vtkSmartPointer< vtkPolyData > PolyDataType; typedef std::deque< itk::Point > FiberType; typedef std::vector< FiberType > BundleType; volatile bool m_PauseTracking; bool m_AbortTracking; bool m_BuildFibersFinished; int m_BuildFibersReady; volatile bool m_Stop; mitk::PointSet::Pointer m_SamplingPointset; mitk::PointSet::Pointer m_StopVotePointset; mitk::PointSet::Pointer m_AlternativePointset; void SetStepSize(float v) ///< Integration step size in voxels, default is 0.5 * voxel { m_StepSizeVox = v; } void SetAngularThreshold(float v) ///< Angular threshold per step (in degree), default is 90deg x stepsize { m_AngularThresholdDeg = v; } void SetSamplingDistance(float v) ///< Maximum distance of sampling points in voxels, default is 0.25 * voxel { m_SamplingDistanceVox = v; } itkGetMacro( OutputProbabilityMap, ItkDoubleImgType::Pointer) ///< Output probability map itkGetMacro( FiberPolyData, PolyDataType ) ///< Output fibers itkGetMacro( UseOutputProbabilityMap, bool) itkSetMacro( SeedImage, ItkUcharImgType::Pointer) ///< Seeds are only placed inside of this mask. itkSetMacro( MaskImage, ItkUcharImgType::Pointer) ///< Tracking is only performed inside of this mask image. itkSetMacro( TissueImage, ItkUcharImgType::Pointer) ///< itkSetMacro( SeedsPerVoxel, int) ///< One seed placed in the center of each voxel or multiple seeds randomly placed inside each voxel. itkSetMacro( MinTractLength, float ) ///< Shorter tracts are discarded. itkSetMacro( MaxTractLength, float ) ///< Streamline progression stops if tract is longer than specified. itkSetMacro( UseStopVotes, bool ) ///< Frontal sampling points can vote for stopping the streamline even if the remaining sampling points keep pushing itkSetMacro( OnlyForwardSamples, bool ) ///< Don't use sampling points behind the current position in progression direction itkSetMacro( DeflectionMod, float ) ///< Deflection distance modifier itkSetMacro( StoppingRegions, ItkUcharImgType::Pointer) ///< Streamlines entering a stopping region will stop immediately itkSetMacro( DemoMode, bool ) itkSetMacro( SeedOnlyGm, bool ) ///< place seed points only in the gray matter itkSetMacro( ControlGmEndings, bool ) ///< itkSetMacro( NumberOfSamples, unsigned int ) ///< Number of neighborhood sampling points itkSetMacro( AposterioriCurvCheck, bool ) ///< Checks fiber curvature (angular deviation across 5mm) is larger than 30°. If yes, the streamline progression is stopped. itkSetMacro( AvoidStop, bool ) ///< Use additional sampling points to avoid premature streamline termination itkSetMacro( RandomSampling, bool ) ///< If true, the sampling points are distributed randomly around the current position, not sphericall in the specified sampling distance. itkSetMacro( NumPreviousDirections, unsigned int ) ///< How many "old" steps do we want to consider in our decision where to go next? itkSetMacro( MaxNumTracts, unsigned int ) ///< Tracking is stopped if the maximum number of tracts is exceeded itkSetMacro( Random, bool ) ///< If true, seedpoints are shuffled randomly before tracking itkSetMacro( Verbose, bool ) ///< If true, output tracking progress (might be slower) itkSetMacro( UseOutputProbabilityMap, bool) ///< If true, no tractogram but a probability map is created as output. - itkSetMacro( StopTracking, bool) ///< Set flag to stop tractography - - void SetSeedPoints(std::vector< itk::Point > seedPoints) ///< Use manually defined points in physical space as seed points instead of seed image - { - m_SeedPoints = seedPoints; - this->Modified(); + itkSetMacro( StopTracking, bool ) + + ///< Use manually defined points in physical space as seed points instead of seed image + void SetSeedPoints( const std::vector< itk::Point >& sP) { + m_SeedPoints = sP; } void SetTrackingHandler( mitk::TrackingDataHandler* h ) ///< { m_TrackingHandler = h; } virtual void Update() override{ this->GenerateData(); } std::string GetStatusText(); protected: void GenerateData() override; StreamlineTrackingFilter(); ~StreamlineTrackingFilter() {} void InitGrayMatterEndings(); void CheckFiberForGmEnding(FiberType* fib); void FiberToProbmap(FiberType* fib); void GetSeedPointsFromSeedImage(); void CalculateNewPosition(itk::Point& pos, vnl_vector_fixed& dir); ///< Calculate next integration step. float FollowStreamline(itk::Point start_pos, vnl_vector_fixed dir, FiberType* fib, float tractLength, bool front); ///< Start streamline in one direction. bool IsValidPosition(const itk::Point& pos); ///< Are we outside of the mask image? bool IsInGm(const itk::Point &pos); vnl_vector_fixed GetNewDirection(itk::Point& pos, std::deque< vnl_vector_fixed >& olddirs, itk::Index<3>& oldIndex); ///< Determine new direction by sample voting at the current position taking the last progression direction into account. std::vector< vnl_vector_fixed > CreateDirections(int NPoints); void BeforeTracking(); void AfterTracking(); PolyDataType m_FiberPolyData; vtkSmartPointer m_Points; vtkSmartPointer m_Cells; BundleType m_Tractogram; BundleType m_GmStubs; ItkUcharImgType::Pointer m_StoppingRegions; ItkUcharImgType::Pointer m_SeedImage; ItkUcharImgType::Pointer m_MaskImage; ItkUcharImgType::Pointer m_TissueImage; ItkDoubleImgType::Pointer m_OutputProbabilityMap; float m_AngularThresholdDeg; float m_StepSizeVox; float m_SamplingDistanceVox; float m_AngularThreshold; float m_StepSize; int m_MaxLength; float m_MinTractLength; float m_MaxTractLength; int m_SeedsPerVoxel; bool m_AvoidStop; bool m_RandomSampling; float m_SamplingDistance; float m_DeflectionMod; bool m_OnlyForwardSamples; bool m_UseStopVotes; unsigned int m_NumberOfSamples; unsigned int m_NumPreviousDirections; int m_WmLabel; int m_GmLabel; bool m_SeedOnlyGm; bool m_ControlGmEndings; int m_MaxNumTracts; bool m_Verbose; bool m_AposterioriCurvCheck; bool m_DemoMode; bool m_Random; bool m_UseOutputProbabilityMap; std::vector< itk::Point > m_SeedPoints; unsigned int m_CurrentTracts; unsigned int m_Progress; bool m_StopTracking; void BuildFibers(bool check); int CheckCurvature(FiberType* fib, bool front); // decision forest mitk::TrackingDataHandler* m_TrackingHandler; std::vector< PolyDataType > m_PolyDataContainer; std::chrono::time_point m_StartTime; std::chrono::time_point m_EndTime; private: }; } //#ifndef ITK_MANUAL_INSTANTIATION //#include "itkMLBSTrackingFilter.cpp" //#endif #endif //__itkMLBSTrackingFilter_h_ diff --git a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundle/mitkFiberBundle.cpp b/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundle/mitkFiberBundle.cpp index 3941659fe4..980c99629b 100755 --- a/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundle/mitkFiberBundle.cpp +++ b/Modules/DiffusionImaging/FiberTracking/IODataStructures/FiberBundle/mitkFiberBundle.cpp @@ -1,2328 +1,2325 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #define _USE_MATH_DEFINES #include "mitkFiberBundle.h" #include #include #include #include "mitkImagePixelReadAccessor.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include const char* mitk::FiberBundle::FIBER_ID_ARRAY = "Fiber_IDs"; using namespace std; mitk::FiberBundle::FiberBundle( vtkPolyData* fiberPolyData ) : m_NumFibers(0) { m_FiberWeights = vtkSmartPointer::New(); m_FiberWeights->SetName("FIBER_WEIGHTS"); m_FiberPolyData = vtkSmartPointer::New(); if (fiberPolyData != nullptr) m_FiberPolyData = fiberPolyData; this->UpdateFiberGeometry(); this->GenerateFiberIds(); this->ColorFibersByOrientation(); } mitk::FiberBundle::~FiberBundle() { } mitk::FiberBundle::Pointer mitk::FiberBundle::GetDeepCopy() { mitk::FiberBundle::Pointer newFib = mitk::FiberBundle::New(m_FiberPolyData); newFib->SetFiberColors(this->m_FiberColors); newFib->SetFiberWeights(this->m_FiberWeights); return newFib; } vtkSmartPointer mitk::FiberBundle::GeneratePolyDataByIds(std::vector fiberIds) { vtkSmartPointer newFiberPolyData = vtkSmartPointer::New(); vtkSmartPointer newLineSet = vtkSmartPointer::New(); vtkSmartPointer newPointSet = vtkSmartPointer::New(); auto finIt = fiberIds.begin(); while ( finIt != fiberIds.end() ) { if (*finIt < 0 || *finIt>GetNumFibers()){ MITK_INFO << "FiberID can not be negative or >NumFibers!!! check id Extraction!" << *finIt; break; } vtkSmartPointer fiber = m_FiberIdDataSet->GetCell(*finIt);//->DeepCopy(fiber); vtkSmartPointer fibPoints = fiber->GetPoints(); vtkSmartPointer newFiber = vtkSmartPointer::New(); newFiber->GetPointIds()->SetNumberOfIds( fibPoints->GetNumberOfPoints() ); for(int i=0; iGetNumberOfPoints(); i++) { newFiber->GetPointIds()->SetId(i, newPointSet->GetNumberOfPoints()); newPointSet->InsertNextPoint(fibPoints->GetPoint(i)[0], fibPoints->GetPoint(i)[1], fibPoints->GetPoint(i)[2]); } newLineSet->InsertNextCell(newFiber); ++finIt; } newFiberPolyData->SetPoints(newPointSet); newFiberPolyData->SetLines(newLineSet); return newFiberPolyData; } // merge two fiber bundles mitk::FiberBundle::Pointer mitk::FiberBundle::AddBundle(mitk::FiberBundle* fib) { if (fib==nullptr) { MITK_WARN << "trying to call AddBundle with nullptr argument"; return nullptr; } MITK_INFO << "Adding fibers"; vtkSmartPointer vNewPolyData = vtkSmartPointer::New(); vtkSmartPointer vNewLines = vtkSmartPointer::New(); vtkSmartPointer vNewPoints = vtkSmartPointer::New(); // add current fiber bundle vtkSmartPointer weights = vtkSmartPointer::New(); weights->SetNumberOfValues(this->GetNumFibers()+fib->GetNumFibers()); unsigned int counter = 0; for (int i=0; iGetNumberOfCells(); i++) { vtkCell* cell = m_FiberPolyData->GetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); vtkSmartPointer container = vtkSmartPointer::New(); for (int j=0; jGetPoint(j, p); vtkIdType id = vNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } weights->InsertValue(counter, this->GetFiberWeight(i)); vNewLines->InsertNextCell(container); counter++; } // add new fiber bundle for (int i=0; iGetFiberPolyData()->GetNumberOfCells(); i++) { vtkCell* cell = fib->GetFiberPolyData()->GetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); vtkSmartPointer container = vtkSmartPointer::New(); for (int j=0; jGetPoint(j, p); vtkIdType id = vNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } weights->InsertValue(counter, fib->GetFiberWeight(i)); vNewLines->InsertNextCell(container); counter++; } // initialize PolyData vNewPolyData->SetPoints(vNewPoints); vNewPolyData->SetLines(vNewLines); // initialize fiber bundle mitk::FiberBundle::Pointer newFib = mitk::FiberBundle::New(vNewPolyData); newFib->SetFiberWeights(weights); return newFib; } // subtract two fiber bundles mitk::FiberBundle::Pointer mitk::FiberBundle::SubtractBundle(mitk::FiberBundle* fib) { MITK_INFO << "Subtracting fibers"; vtkSmartPointer vNewPolyData = vtkSmartPointer::New(); vtkSmartPointer vNewLines = vtkSmartPointer::New(); vtkSmartPointer vNewPoints = vtkSmartPointer::New(); std::vector< std::vector< itk::Point > > points1; for( int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); if (points==nullptr || numPoints<=0) continue; itk::Point start = GetItkPoint(points->GetPoint(0)); itk::Point end = GetItkPoint(points->GetPoint(numPoints-1)); points1.push_back( {start, end} ); } std::vector< std::vector< itk::Point > > points2; for( int i=0; iGetNumFibers(); i++ ) { vtkCell* cell = fib->GetFiberPolyData()->GetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); if (points==nullptr || numPoints<=0) continue; itk::Point start = GetItkPoint(points->GetPoint(0)); itk::Point end = GetItkPoint(points->GetPoint(numPoints-1)); points2.push_back( {start, end} ); } int progress = 0; std::vector< int > ids; #pragma omp parallel for for (int i=0; i<(int)points1.size(); i++) { #pragma omp critical { progress++; std::cout << (int)(100*(float)progress/points1.size()) << "%" << '\r'; cout.flush(); } bool match = false; for (unsigned int j=0; jGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); if (points==nullptr || numPoints<=0) continue; vtkSmartPointer container = vtkSmartPointer::New(); for( int j=0; jInsertNextPoint(points->GetPoint(j)); container->GetPointIds()->InsertNextId(id); } vNewLines->InsertNextCell(container); } if(vNewLines->GetNumberOfCells()==0) return nullptr; // initialize PolyData vNewPolyData->SetPoints(vNewPoints); vNewPolyData->SetLines(vNewLines); // initialize fiber bundle return mitk::FiberBundle::New(vNewPolyData); } itk::Point mitk::FiberBundle::GetItkPoint(double point[3]) { itk::Point itkPoint; itkPoint[0] = point[0]; itkPoint[1] = point[1]; itkPoint[2] = point[2]; return itkPoint; } /* * set PolyData (additional flag to recompute fiber geometry, default = true) */ void mitk::FiberBundle::SetFiberPolyData(vtkSmartPointer fiberPD, bool updateGeometry) { if (fiberPD == nullptr) this->m_FiberPolyData = vtkSmartPointer::New(); else m_FiberPolyData->DeepCopy(fiberPD); m_NumFibers = m_FiberPolyData->GetNumberOfLines(); if (updateGeometry) UpdateFiberGeometry(); GenerateFiberIds(); ColorFibersByOrientation(); } /* * return vtkPolyData */ vtkSmartPointer mitk::FiberBundle::GetFiberPolyData() const { return m_FiberPolyData; } void mitk::FiberBundle::ColorFibersByOrientation() { //===== FOR WRITING A TEST ======================== // colorT size == tupelComponents * tupelElements // compare color results // to cover this code 100% also PolyData needed, where colorarray already exists // + one fiber with exactly 1 point // + one fiber with 0 points //================================================= vtkPoints* extrPoints = nullptr; extrPoints = m_FiberPolyData->GetPoints(); int numOfPoints = 0; if (extrPoints!=nullptr) numOfPoints = extrPoints->GetNumberOfPoints(); //colors and alpha value for each single point, RGBA = 4 components unsigned char rgba[4] = {0,0,0,0}; int componentSize = 4; m_FiberColors = vtkSmartPointer::New(); m_FiberColors->Allocate(numOfPoints * componentSize); m_FiberColors->SetNumberOfComponents(componentSize); m_FiberColors->SetName("FIBER_COLORS"); int numOfFibers = m_FiberPolyData->GetNumberOfLines(); if (numOfFibers < 1) return; /* extract single fibers of fiberBundle */ vtkCellArray* fiberList = m_FiberPolyData->GetLines(); fiberList->InitTraversal(); for (int fi=0; fiGetNextCell(pointsPerFiber, idList); /* single fiber checkpoints: is number of points valid */ if (pointsPerFiber > 1) { /* operate on points of single fiber */ for (int i=0; i 0) { /* The color value of the current point is influenced by the previous point and next point. */ vnl_vector_fixed< double, 3 > currentPntvtk(extrPoints->GetPoint(idList[i])[0], extrPoints->GetPoint(idList[i])[1],extrPoints->GetPoint(idList[i])[2]); vnl_vector_fixed< double, 3 > nextPntvtk(extrPoints->GetPoint(idList[i+1])[0], extrPoints->GetPoint(idList[i+1])[1], extrPoints->GetPoint(idList[i+1])[2]); vnl_vector_fixed< double, 3 > prevPntvtk(extrPoints->GetPoint(idList[i-1])[0], extrPoints->GetPoint(idList[i-1])[1], extrPoints->GetPoint(idList[i-1])[2]); vnl_vector_fixed< double, 3 > diff1; diff1 = currentPntvtk - nextPntvtk; vnl_vector_fixed< double, 3 > diff2; diff2 = currentPntvtk - prevPntvtk; vnl_vector_fixed< double, 3 > diff; diff = (diff1 - diff2) / 2.0; diff.normalize(); rgba[0] = (unsigned char) (255.0 * std::fabs(diff[0])); rgba[1] = (unsigned char) (255.0 * std::fabs(diff[1])); rgba[2] = (unsigned char) (255.0 * std::fabs(diff[2])); rgba[3] = (unsigned char) (255.0); } else if (i==0) { /* First point has no previous point, therefore only diff1 is taken */ vnl_vector_fixed< double, 3 > currentPntvtk(extrPoints->GetPoint(idList[i])[0], extrPoints->GetPoint(idList[i])[1],extrPoints->GetPoint(idList[i])[2]); vnl_vector_fixed< double, 3 > nextPntvtk(extrPoints->GetPoint(idList[i+1])[0], extrPoints->GetPoint(idList[i+1])[1], extrPoints->GetPoint(idList[i+1])[2]); vnl_vector_fixed< double, 3 > diff1; diff1 = currentPntvtk - nextPntvtk; diff1.normalize(); rgba[0] = (unsigned char) (255.0 * std::fabs(diff1[0])); rgba[1] = (unsigned char) (255.0 * std::fabs(diff1[1])); rgba[2] = (unsigned char) (255.0 * std::fabs(diff1[2])); rgba[3] = (unsigned char) (255.0); } else if (i==pointsPerFiber-1) { /* Last point has no next point, therefore only diff2 is taken */ vnl_vector_fixed< double, 3 > currentPntvtk(extrPoints->GetPoint(idList[i])[0], extrPoints->GetPoint(idList[i])[1],extrPoints->GetPoint(idList[i])[2]); vnl_vector_fixed< double, 3 > prevPntvtk(extrPoints->GetPoint(idList[i-1])[0], extrPoints->GetPoint(idList[i-1])[1], extrPoints->GetPoint(idList[i-1])[2]); vnl_vector_fixed< double, 3 > diff2; diff2 = currentPntvtk - prevPntvtk; diff2.normalize(); rgba[0] = (unsigned char) (255.0 * std::fabs(diff2[0])); rgba[1] = (unsigned char) (255.0 * std::fabs(diff2[1])); rgba[2] = (unsigned char) (255.0 * std::fabs(diff2[2])); rgba[3] = (unsigned char) (255.0); } - m_FiberColors->InsertTupleValue(idList[i], rgba); + m_FiberColors->InsertTypedTuple(idList[i], rgba); } } else if (pointsPerFiber == 1) { /* a single point does not define a fiber (use vertex mechanisms instead */ continue; } else { MITK_DEBUG << "Fiber with 0 points detected... please check your tractography algorithm!" ; continue; } } m_UpdateTime3D.Modified(); m_UpdateTime2D.Modified(); } void mitk::FiberBundle::ColorFibersByCurvature(bool opacity, bool normalize) { double window = 5; //colors and alpha value for each single point, RGBA = 4 components unsigned char rgba[4] = {0,0,0,0}; int componentSize = 4; m_FiberColors = vtkSmartPointer::New(); m_FiberColors->Allocate(m_FiberPolyData->GetNumberOfPoints() * componentSize); m_FiberColors->SetNumberOfComponents(componentSize); m_FiberColors->SetName("FIBER_COLORS"); mitk::LookupTable::Pointer mitkLookup = mitk::LookupTable::New(); vtkSmartPointer lookupTable = vtkSmartPointer::New(); lookupTable->SetTableRange(0.0, 0.8); lookupTable->Build(); mitkLookup->SetVtkLookupTable(lookupTable); mitkLookup->SetType(mitk::LookupTable::JET); vector< double > values; double min = 1; double max = 0; MITK_INFO << "Coloring fibers by curvature"; boost::progress_display disp(m_FiberPolyData->GetNumberOfCells()); for (int i=0; iGetNumberOfCells(); i++) { ++disp; vtkCell* cell = m_FiberPolyData->GetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); // calculate curvatures for (int j=0; j > vectors; vnl_vector_fixed< float, 3 > meanV; meanV.fill(0.0); while(dist1) { double p1[3]; points->GetPoint(c-1, p1); double p2[3]; points->GetPoint(c, p2); vnl_vector_fixed< float, 3 > v; v[0] = p2[0]-p1[0]; v[1] = p2[1]-p1[1]; v[2] = p2[2]-p1[2]; dist += v.magnitude(); v.normalize(); vectors.push_back(v); if (c==j) meanV += v; c--; } c = j; dist = 0; while(distGetPoint(c, p1); double p2[3]; points->GetPoint(c+1, p2); vnl_vector_fixed< float, 3 > v; v[0] = p2[0]-p1[0]; v[1] = p2[1]-p1[1]; v[2] = p2[2]-p1[2]; dist += v.magnitude(); v.normalize(); vectors.push_back(v); if (c==j) meanV += v; c++; } meanV.normalize(); double dev = 0; for (unsigned int c=0; c1.0) angle = 1.0; if (angle<-1.0) angle = -1.0; dev += acos(angle)*180/M_PI; } if (vectors.size()>0) dev /= vectors.size(); dev = 1.0-dev/180.0; values.push_back(dev); if (devmax) max = dev; } } unsigned int count = 0; for (int i=0; iGetNumberOfCells(); i++) { vtkCell* cell = m_FiberPolyData->GetCell(i); int numPoints = cell->GetNumberOfPoints(); for (int j=0; j1) dev = 1; lookupTable->GetColor(dev, color); rgba[0] = (unsigned char) (255.0 * color[0]); rgba[1] = (unsigned char) (255.0 * color[1]); rgba[2] = (unsigned char) (255.0 * color[2]); - if (opacity) - rgba[3] = (unsigned char) (255.0 * dev); - else - rgba[3] = (unsigned char) (255.0); - m_FiberColors->InsertTupleValue(cell->GetPointId(j), rgba); + rgba[3] = (unsigned char) (255.0); + m_FiberColors->InsertTypedTuple(cell->GetPointId(j), rgba); count++; } } m_UpdateTime3D.Modified(); m_UpdateTime2D.Modified(); } void mitk::FiberBundle::SetFiberOpacity(vtkDoubleArray* FAValArray) { for(long i=0; iGetNumberOfTuples(); i++) { double faValue = FAValArray->GetValue(i); faValue = faValue * 255.0; m_FiberColors->SetComponent(i,3, (unsigned char) faValue ); } m_UpdateTime3D.Modified(); m_UpdateTime2D.Modified(); } void mitk::FiberBundle::ResetFiberOpacity() { for(long i=0; iGetNumberOfTuples(); i++) m_FiberColors->SetComponent(i,3, 255.0 ); m_UpdateTime3D.Modified(); m_UpdateTime2D.Modified(); } void mitk::FiberBundle::ColorFibersByScalarMap(mitk::Image::Pointer FAimage, bool opacity, bool normalize) { mitkPixelTypeMultiplex3( ColorFibersByScalarMap, FAimage->GetPixelType(), FAimage, opacity, normalize ); m_UpdateTime3D.Modified(); m_UpdateTime2D.Modified(); } template void mitk::FiberBundle::ColorFibersByScalarMap(const mitk::PixelType, mitk::Image::Pointer image, bool opacity, bool normalize) { m_FiberColors = vtkSmartPointer::New(); m_FiberColors->Allocate(m_FiberPolyData->GetNumberOfPoints() * 4); m_FiberColors->SetNumberOfComponents(4); m_FiberColors->SetName("FIBER_COLORS"); mitk::ImagePixelReadAccessor readimage(image, image->GetVolumeData(0)); unsigned char rgba[4] = {0,0,0,0}; vtkPoints* pointSet = m_FiberPolyData->GetPoints(); mitk::LookupTable::Pointer mitkLookup = mitk::LookupTable::New(); vtkSmartPointer lookupTable = vtkSmartPointer::New(); lookupTable->SetTableRange(0.0, 0.8); lookupTable->Build(); mitkLookup->SetVtkLookupTable(lookupTable); mitkLookup->SetType(mitk::LookupTable::JET); double min = 9999999; double max = -9999999; for(long i=0; iGetNumberOfPoints(); ++i) { Point3D px; px[0] = pointSet->GetPoint(i)[0]; px[1] = pointSet->GetPoint(i)[1]; px[2] = pointSet->GetPoint(i)[2]; double pixelValue = readimage.GetPixelByWorldCoordinates(px); if (pixelValue>max) max = pixelValue; if (pixelValueGetNumberOfPoints(); ++i) { Point3D px; px[0] = pointSet->GetPoint(i)[0]; px[1] = pointSet->GetPoint(i)[1]; px[2] = pointSet->GetPoint(i)[2]; double pixelValue = readimage.GetPixelByWorldCoordinates(px); if (normalize) pixelValue = (pixelValue-min)/(max-min); else if (pixelValue>1) pixelValue = 1; double color[3]; lookupTable->GetColor(1-pixelValue, color); rgba[0] = (unsigned char) (255.0 * color[0]); rgba[1] = (unsigned char) (255.0 * color[1]); rgba[2] = (unsigned char) (255.0 * color[2]); if (opacity) rgba[3] = (unsigned char) (255.0 * pixelValue); else rgba[3] = (unsigned char) (255.0); - m_FiberColors->InsertTupleValue(i, rgba); + m_FiberColors->InsertTypedTuple(i, rgba); } m_UpdateTime3D.Modified(); m_UpdateTime2D.Modified(); } void mitk::FiberBundle::ColorFibersByFiberWeights(bool opacity, bool normalize) { m_FiberColors = vtkSmartPointer::New(); m_FiberColors->Allocate(m_FiberPolyData->GetNumberOfPoints() * 4); m_FiberColors->SetNumberOfComponents(4); m_FiberColors->SetName("FIBER_COLORS"); mitk::LookupTable::Pointer mitkLookup = mitk::LookupTable::New(); vtkSmartPointer lookupTable = vtkSmartPointer::New(); lookupTable->SetTableRange(0.0, 0.8); lookupTable->Build(); mitkLookup->SetVtkLookupTable(lookupTable); mitkLookup->SetType(mitk::LookupTable::JET); unsigned char rgba[4] = {0,0,0,0}; unsigned int counter = 0; float max = -999999; float min = 999999; for (int i=0; iGetFiberWeight(i); if (weight>max) max = weight; if (weightGetCell(i); int numPoints = cell->GetNumberOfPoints(); double weight = this->GetFiberWeight(i); for (int j=0; j1) v = 1; double color[3]; lookupTable->GetColor(1-v, color); rgba[0] = (unsigned char) (255.0 * color[0]); rgba[1] = (unsigned char) (255.0 * color[1]); rgba[2] = (unsigned char) (255.0 * color[2]); if (opacity) rgba[3] = (unsigned char) (255.0 * v); else rgba[3] = (unsigned char) (255.0); - m_FiberColors->InsertTupleValue(counter, rgba); + m_FiberColors->InsertTypedTuple(counter, rgba); counter++; } } m_UpdateTime3D.Modified(); m_UpdateTime2D.Modified(); } void mitk::FiberBundle::SetFiberColors(float r, float g, float b, float alpha) { m_FiberColors = vtkSmartPointer::New(); m_FiberColors->Allocate(m_FiberPolyData->GetNumberOfPoints() * 4); m_FiberColors->SetNumberOfComponents(4); m_FiberColors->SetName("FIBER_COLORS"); unsigned char rgba[4] = {0,0,0,0}; for(long i=0; iGetNumberOfPoints(); ++i) { rgba[0] = (unsigned char) r; rgba[1] = (unsigned char) g; rgba[2] = (unsigned char) b; rgba[3] = (unsigned char) alpha; - m_FiberColors->InsertTupleValue(i, rgba); + m_FiberColors->InsertTypedTuple(i, rgba); } m_UpdateTime3D.Modified(); m_UpdateTime2D.Modified(); } void mitk::FiberBundle::GenerateFiberIds() { if (m_FiberPolyData == nullptr) return; vtkSmartPointer idFiberFilter = vtkSmartPointer::New(); idFiberFilter->SetInputData(m_FiberPolyData); idFiberFilter->CellIdsOn(); // idFiberFilter->PointIdsOn(); // point id's are not needed idFiberFilter->SetIdsArrayName(FIBER_ID_ARRAY); idFiberFilter->FieldDataOn(); idFiberFilter->Update(); m_FiberIdDataSet = idFiberFilter->GetOutput(); } mitk::FiberBundle::Pointer mitk::FiberBundle::ExtractFiberSubset(ItkUcharImgType* mask, bool anyPoint, bool invert, bool bothEnds, float fraction) { vtkSmartPointer PolyData = m_FiberPolyData; if (anyPoint) { float minSpacing = 1; if(mask->GetSpacing()[0]GetSpacing()[1] && mask->GetSpacing()[0]GetSpacing()[2]) minSpacing = mask->GetSpacing()[0]; else if (mask->GetSpacing()[1] < mask->GetSpacing()[2]) minSpacing = mask->GetSpacing()[1]; else minSpacing = mask->GetSpacing()[2]; mitk::FiberBundle::Pointer fibCopy = this->GetDeepCopy(); fibCopy->ResampleLinear(minSpacing/5); PolyData = fibCopy->GetFiberPolyData(); } vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); MITK_INFO << "Extracting fibers with mask image"; boost::progress_display disp(m_NumFibers); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); vtkCell* cellOriginal = m_FiberPolyData->GetCell(i); int numPointsOriginal = cellOriginal->GetNumberOfPoints(); vtkPoints* pointsOriginal = cellOriginal->GetPoints(); vtkSmartPointer container = vtkSmartPointer::New(); if (numPoints>1 && numPointsOriginal) { if (anyPoint) { int inside = 0; int outside = 0; if (!invert) { for (int j=0; jGetPoint(j); itk::Point itkP; itkP[0] = p[0]; itkP[1] = p[1]; itkP[2] = p[2]; itk::Index<3> idx; mask->TransformPhysicalPointToIndex(itkP, idx); if ( mask->GetLargestPossibleRegion().IsInside(idx) && mask->GetPixel(idx) != 0 ) { inside++; if (fraction==0) break; } else outside++; } float current_fraction = 0.0; if (inside+outside>0) current_fraction = (float)inside/(inside+outside); if (current_fraction>fraction) { for (int k=0; kGetPoint(k); vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } } } else { bool includeFiber = true; for (int j=0; jGetPoint(j); itk::Point itkP; itkP[0] = p[0]; itkP[1] = p[1]; itkP[2] = p[2]; itk::Index<3> idx; mask->TransformPhysicalPointToIndex(itkP, idx); if ( mask->GetPixel(idx) != 0 && mask->GetLargestPossibleRegion().IsInside(idx) ) { inside++; includeFiber = false; break; } else outside++; } if (includeFiber) { for (int k=0; kGetPoint(k); vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } } } } else { double* start = pointsOriginal->GetPoint(0); itk::Point itkStart; itkStart[0] = start[0]; itkStart[1] = start[1]; itkStart[2] = start[2]; itk::Index<3> idxStart; mask->TransformPhysicalPointToIndex(itkStart, idxStart); double* end = pointsOriginal->GetPoint(numPointsOriginal-1); itk::Point itkEnd; itkEnd[0] = end[0]; itkEnd[1] = end[1]; itkEnd[2] = end[2]; itk::Index<3> idxEnd; mask->TransformPhysicalPointToIndex(itkEnd, idxEnd); if (invert) { if (bothEnds) { if ( mask->GetPixel(idxStart) == 0 && mask->GetPixel(idxEnd) == 0 ) { for (int j=0; jGetPoint(j); vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } } } else if ( mask->GetPixel(idxStart) == 0 || mask->GetPixel(idxEnd) == 0 ) { for (int j=0; jGetPoint(j); vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } } } else { if (bothEnds) { if ( mask->GetPixel(idxStart) != 0 && mask->GetPixel(idxEnd) != 0 && mask->GetLargestPossibleRegion().IsInside(idxStart) && mask->GetLargestPossibleRegion().IsInside(idxEnd) ) { for (int j=0; jGetPoint(j); vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } } } else if ( (mask->GetPixel(idxStart) != 0 && mask->GetLargestPossibleRegion().IsInside(idxStart)) || (mask->GetPixel(idxEnd) != 0 && mask->GetLargestPossibleRegion().IsInside(idxEnd)) ) { for (int j=0; jGetPoint(j); vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } } } } } vtkNewCells->InsertNextCell(container); } if (vtkNewCells->GetNumberOfCells()<=0) return nullptr; vtkSmartPointer newPolyData = vtkSmartPointer::New(); newPolyData->SetPoints(vtkNewPoints); newPolyData->SetLines(vtkNewCells); return mitk::FiberBundle::New(newPolyData); } mitk::FiberBundle::Pointer mitk::FiberBundle::RemoveFibersOutside(ItkUcharImgType* mask, bool invert) { float minSpacing = 1; if(mask->GetSpacing()[0]GetSpacing()[1] && mask->GetSpacing()[0]GetSpacing()[2]) minSpacing = mask->GetSpacing()[0]; else if (mask->GetSpacing()[1] < mask->GetSpacing()[2]) minSpacing = mask->GetSpacing()[1]; else minSpacing = mask->GetSpacing()[2]; mitk::FiberBundle::Pointer fibCopy = this->GetDeepCopy(); fibCopy->ResampleLinear(minSpacing/10); vtkSmartPointer PolyData =fibCopy->GetFiberPolyData(); vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); MITK_INFO << "Cutting fibers"; boost::progress_display disp(m_NumFibers); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); vtkSmartPointer container = vtkSmartPointer::New(); if (numPoints>1) { int newNumPoints = 0; for (int j=0; jGetPoint(j); itk::Point itkP; itkP[0] = p[0]; itkP[1] = p[1]; itkP[2] = p[2]; itk::Index<3> idx; mask->TransformPhysicalPointToIndex(itkP, idx); if ( mask->GetPixel(idx) != 0 && mask->GetLargestPossibleRegion().IsInside(idx) && !invert ) { vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); newNumPoints++; } else if ( (mask->GetPixel(idx) == 0 || !mask->GetLargestPossibleRegion().IsInside(idx)) && invert ) { vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); newNumPoints++; } else if (newNumPoints>0) { vtkNewCells->InsertNextCell(container); newNumPoints = 0; container = vtkSmartPointer::New(); } } if (newNumPoints>0) vtkNewCells->InsertNextCell(container); } } if (vtkNewCells->GetNumberOfCells()<=0) return nullptr; vtkSmartPointer newPolyData = vtkSmartPointer::New(); newPolyData->SetPoints(vtkNewPoints); newPolyData->SetLines(vtkNewCells); mitk::FiberBundle::Pointer newFib = mitk::FiberBundle::New(newPolyData); newFib->Compress(0.1); return newFib; } mitk::FiberBundle::Pointer mitk::FiberBundle::ExtractFiberSubset(DataNode* roi, DataStorage* storage) { if (roi==nullptr || !(dynamic_cast(roi->GetData()) || dynamic_cast(roi->GetData())) ) return nullptr; std::vector tmp = ExtractFiberIdSubset(roi, storage); if (tmp.size()<=0) return mitk::FiberBundle::New(); vtkSmartPointer pTmp = GeneratePolyDataByIds(tmp); return mitk::FiberBundle::New(pTmp); } std::vector mitk::FiberBundle::ExtractFiberIdSubset(DataNode *roi, DataStorage* storage) { std::vector result; if (roi==nullptr || roi->GetData()==nullptr) return result; mitk::PlanarFigureComposite::Pointer pfc = dynamic_cast(roi->GetData()); if (!pfc.IsNull()) // handle composite { DataStorage::SetOfObjects::ConstPointer children = storage->GetDerivations(roi); if (children->size()==0) return result; switch (pfc->getOperationType()) { case 0: // AND { MITK_INFO << "AND"; result = this->ExtractFiberIdSubset(children->ElementAt(0), storage); std::vector::iterator it; for (unsigned int i=1; iSize(); ++i) { std::vector inRoi = this->ExtractFiberIdSubset(children->ElementAt(i), storage); std::vector rest(std::min(result.size(),inRoi.size())); it = std::set_intersection(result.begin(), result.end(), inRoi.begin(), inRoi.end(), rest.begin() ); rest.resize( it - rest.begin() ); result = rest; } break; } case 1: // OR { MITK_INFO << "OR"; result = ExtractFiberIdSubset(children->ElementAt(0), storage); std::vector::iterator it; for (unsigned int i=1; iSize(); ++i) { it = result.end(); std::vector inRoi = ExtractFiberIdSubset(children->ElementAt(i), storage); result.insert(it, inRoi.begin(), inRoi.end()); } // remove duplicates sort(result.begin(), result.end()); it = unique(result.begin(), result.end()); result.resize( it - result.begin() ); break; } case 2: // NOT { MITK_INFO << "NOT"; for(long i=0; iGetNumFibers(); i++) result.push_back(i); std::vector::iterator it; for (unsigned int i=0; iSize(); ++i) { std::vector inRoi = ExtractFiberIdSubset(children->ElementAt(i), storage); std::vector rest(result.size()-inRoi.size()); it = std::set_difference(result.begin(), result.end(), inRoi.begin(), inRoi.end(), rest.begin() ); rest.resize( it - rest.begin() ); result = rest; } break; } } } else if ( dynamic_cast(roi->GetData()) ) // actual extraction { if ( dynamic_cast(roi->GetData()) ) { mitk::PlanarFigure::Pointer planarPoly = dynamic_cast(roi->GetData()); //create vtkPolygon using controlpoints from planarFigure polygon vtkSmartPointer polygonVtk = vtkSmartPointer::New(); for (unsigned int i=0; iGetNumberOfControlPoints(); ++i) { itk::Point p = planarPoly->GetWorldControlPoint(i); vtkIdType id = polygonVtk->GetPoints()->InsertNextPoint(p[0], p[1], p[2] ); polygonVtk->GetPointIds()->InsertNextId(id); } MITK_INFO << "Extracting with polygon"; boost::progress_display disp(m_NumFibers); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); for (int j=0; jGetPoint(j, p1); double p2[3] = {0,0,0}; points->GetPoint(j+1, p2); double tolerance = 0.001; // Outputs double t = 0; // Parametric coordinate of intersection (0 (corresponding to p1) to 1 (corresponding to p2)) double x[3] = {0,0,0}; // The coordinate of the intersection double pcoords[3] = {0,0,0}; int subId = 0; int iD = polygonVtk->IntersectWithLine(p1, p2, tolerance, t, x, pcoords, subId); if (iD!=0) { result.push_back(i); break; } } } } else if ( dynamic_cast(roi->GetData()) ) { mitk::PlanarFigure::Pointer planarFigure = dynamic_cast(roi->GetData()); Vector3D planeNormal = planarFigure->GetPlaneGeometry()->GetNormal(); planeNormal.Normalize(); //calculate circle radius mitk::Point3D V1w = planarFigure->GetWorldControlPoint(0); //centerPoint mitk::Point3D V2w = planarFigure->GetWorldControlPoint(1); //radiusPoint double radius = V1w.EuclideanDistanceTo(V2w); radius *= radius; MITK_INFO << "Extracting with circle"; boost::progress_display disp(m_NumFibers); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); for (int j=0; jGetPoint(j, p1); double p2[3] = {0,0,0}; points->GetPoint(j+1, p2); // Outputs double t = 0; // Parametric coordinate of intersection (0 (corresponding to p1) to 1 (corresponding to p2)) double x[3] = {0,0,0}; // The coordinate of the intersection int iD = vtkPlane::IntersectWithLine(p1,p2,planeNormal.GetDataPointer(),V1w.GetDataPointer(),t,x); if (iD!=0) { double dist = (x[0]-V1w[0])*(x[0]-V1w[0])+(x[1]-V1w[1])*(x[1]-V1w[1])+(x[2]-V1w[2])*(x[2]-V1w[2]); if( dist <= radius) { result.push_back(i); break; } } } } } return result; } return result; } void mitk::FiberBundle::UpdateFiberGeometry() { vtkSmartPointer cleaner = vtkSmartPointer::New(); cleaner->SetInputData(m_FiberPolyData); cleaner->PointMergingOff(); cleaner->Update(); m_FiberPolyData = cleaner->GetOutput(); m_FiberLengths.clear(); m_MeanFiberLength = 0; m_MedianFiberLength = 0; m_LengthStDev = 0; m_NumFibers = m_FiberPolyData->GetNumberOfCells(); if (m_FiberColors==nullptr || m_FiberColors->GetNumberOfTuples()!=m_FiberPolyData->GetNumberOfPoints()) this->ColorFibersByOrientation(); if (m_FiberWeights->GetSize()!=m_NumFibers) { m_FiberWeights = vtkSmartPointer::New(); m_FiberWeights->SetName("FIBER_WEIGHTS"); m_FiberWeights->SetNumberOfValues(m_NumFibers); this->SetFiberWeights(1); } if (m_NumFibers<=0) // no fibers present; apply default geometry { m_MinFiberLength = 0; m_MaxFiberLength = 0; mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); geometry->SetImageGeometry(false); float b[] = {0, 1, 0, 1, 0, 1}; geometry->SetFloatBounds(b); SetGeometry(geometry); return; } double b[6]; m_FiberPolyData->GetBounds(b); // calculate statistics for (int i=0; iGetNumberOfCells(); i++) { vtkCell* cell = m_FiberPolyData->GetCell(i); int p = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); float length = 0; for (int j=0; jGetPoint(j, p1); double p2[3]; points->GetPoint(j+1, p2); float dist = std::sqrt((p1[0]-p2[0])*(p1[0]-p2[0])+(p1[1]-p2[1])*(p1[1]-p2[1])+(p1[2]-p2[2])*(p1[2]-p2[2])); length += dist; } m_FiberLengths.push_back(length); m_MeanFiberLength += length; if (i==0) { m_MinFiberLength = length; m_MaxFiberLength = length; } else { if (lengthm_MaxFiberLength) m_MaxFiberLength = length; } } m_MeanFiberLength /= m_NumFibers; std::vector< float > sortedLengths = m_FiberLengths; std::sort(sortedLengths.begin(), sortedLengths.end()); for (int i=0; i1) m_LengthStDev /= (m_NumFibers-1); else m_LengthStDev = 0; m_LengthStDev = std::sqrt(m_LengthStDev); m_MedianFiberLength = sortedLengths.at(m_NumFibers/2); mitk::Geometry3D::Pointer geometry = mitk::Geometry3D::New(); geometry->SetFloatBounds(b); this->SetGeometry(geometry); m_UpdateTime3D.Modified(); m_UpdateTime2D.Modified(); } float mitk::FiberBundle::GetFiberWeight(unsigned int fiber) const { return m_FiberWeights->GetValue(fiber); } void mitk::FiberBundle::SetFiberWeights(float newWeight) { for (int i=0; iGetSize(); i++) m_FiberWeights->SetValue(i, newWeight); } void mitk::FiberBundle::SetFiberWeights(vtkSmartPointer weights) { if (m_NumFibers!=weights->GetSize()) { MITK_INFO << "Weights array not equal to number of fibers!"; return; } for (int i=0; iGetSize(); i++) m_FiberWeights->SetValue(i, weights->GetValue(i)); m_FiberWeights->SetName("FIBER_WEIGHTS"); } void mitk::FiberBundle::SetFiberWeight(unsigned int fiber, float weight) { m_FiberWeights->SetValue(fiber, weight); } void mitk::FiberBundle::SetFiberColors(vtkSmartPointer fiberColors) { for(long i=0; iGetNumberOfPoints(); ++i) { unsigned char source[4] = {0,0,0,0}; - fiberColors->GetTupleValue(i, source); + fiberColors->GetTypedTuple(i, source); unsigned char target[4] = {0,0,0,0}; target[0] = source[0]; target[1] = source[1]; target[2] = source[2]; target[3] = source[3]; - m_FiberColors->InsertTupleValue(i, target); + m_FiberColors->InsertTypedTuple(i, target); } m_UpdateTime3D.Modified(); m_UpdateTime2D.Modified(); } itk::Matrix< double, 3, 3 > mitk::FiberBundle::TransformMatrix(itk::Matrix< double, 3, 3 > m, double rx, double ry, double rz) { rx = rx*M_PI/180; ry = ry*M_PI/180; rz = rz*M_PI/180; itk::Matrix< double, 3, 3 > rotX; rotX.SetIdentity(); rotX[1][1] = cos(rx); rotX[2][2] = rotX[1][1]; rotX[1][2] = -sin(rx); rotX[2][1] = -rotX[1][2]; itk::Matrix< double, 3, 3 > rotY; rotY.SetIdentity(); rotY[0][0] = cos(ry); rotY[2][2] = rotY[0][0]; rotY[0][2] = sin(ry); rotY[2][0] = -rotY[0][2]; itk::Matrix< double, 3, 3 > rotZ; rotZ.SetIdentity(); rotZ[0][0] = cos(rz); rotZ[1][1] = rotZ[0][0]; rotZ[0][1] = -sin(rz); rotZ[1][0] = -rotZ[0][1]; itk::Matrix< double, 3, 3 > rot = rotZ*rotY*rotX; m = rot*m; return m; } itk::Point mitk::FiberBundle::TransformPoint(vnl_vector_fixed< double, 3 > point, double rx, double ry, double rz, double tx, double ty, double tz) { rx = rx*M_PI/180; ry = ry*M_PI/180; rz = rz*M_PI/180; vnl_matrix_fixed< double, 3, 3 > rotX; rotX.set_identity(); rotX[1][1] = cos(rx); rotX[2][2] = rotX[1][1]; rotX[1][2] = -sin(rx); rotX[2][1] = -rotX[1][2]; vnl_matrix_fixed< double, 3, 3 > rotY; rotY.set_identity(); rotY[0][0] = cos(ry); rotY[2][2] = rotY[0][0]; rotY[0][2] = sin(ry); rotY[2][0] = -rotY[0][2]; vnl_matrix_fixed< double, 3, 3 > rotZ; rotZ.set_identity(); rotZ[0][0] = cos(rz); rotZ[1][1] = rotZ[0][0]; rotZ[0][1] = -sin(rz); rotZ[1][0] = -rotZ[0][1]; vnl_matrix_fixed< double, 3, 3 > rot = rotZ*rotY*rotX; mitk::BaseGeometry::Pointer geom = this->GetGeometry(); mitk::Point3D center = geom->GetCenter(); point[0] -= center[0]; point[1] -= center[1]; point[2] -= center[2]; point = rot*point; point[0] += center[0]+tx; point[1] += center[1]+ty; point[2] += center[2]+tz; itk::Point out; out[0] = point[0]; out[1] = point[1]; out[2] = point[2]; return out; } void mitk::FiberBundle::TransformFibers(double rx, double ry, double rz, double tx, double ty, double tz) { rx = rx*M_PI/180; ry = ry*M_PI/180; rz = rz*M_PI/180; vnl_matrix_fixed< double, 3, 3 > rotX; rotX.set_identity(); rotX[1][1] = cos(rx); rotX[2][2] = rotX[1][1]; rotX[1][2] = -sin(rx); rotX[2][1] = -rotX[1][2]; vnl_matrix_fixed< double, 3, 3 > rotY; rotY.set_identity(); rotY[0][0] = cos(ry); rotY[2][2] = rotY[0][0]; rotY[0][2] = sin(ry); rotY[2][0] = -rotY[0][2]; vnl_matrix_fixed< double, 3, 3 > rotZ; rotZ.set_identity(); rotZ[0][0] = cos(rz); rotZ[1][1] = rotZ[0][0]; rotZ[0][1] = -sin(rz); rotZ[1][0] = -rotZ[0][1]; vnl_matrix_fixed< double, 3, 3 > rot = rotZ*rotY*rotX; mitk::BaseGeometry::Pointer geom = this->GetGeometry(); mitk::Point3D center = geom->GetCenter(); vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); vtkSmartPointer container = vtkSmartPointer::New(); for (int j=0; jGetPoint(j); vnl_vector_fixed< double, 3 > dir; dir[0] = p[0]-center[0]; dir[1] = p[1]-center[1]; dir[2] = p[2]-center[2]; dir = rot*dir; dir[0] += center[0]+tx; dir[1] += center[1]+ty; dir[2] += center[2]+tz; vtkIdType id = vtkNewPoints->InsertNextPoint(dir.data_block()); container->GetPointIds()->InsertNextId(id); } vtkNewCells->InsertNextCell(container); } m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); } void mitk::FiberBundle::RotateAroundAxis(double x, double y, double z) { x = x*M_PI/180; y = y*M_PI/180; z = z*M_PI/180; vnl_matrix_fixed< double, 3, 3 > rotX; rotX.set_identity(); rotX[1][1] = cos(x); rotX[2][2] = rotX[1][1]; rotX[1][2] = -sin(x); rotX[2][1] = -rotX[1][2]; vnl_matrix_fixed< double, 3, 3 > rotY; rotY.set_identity(); rotY[0][0] = cos(y); rotY[2][2] = rotY[0][0]; rotY[0][2] = sin(y); rotY[2][0] = -rotY[0][2]; vnl_matrix_fixed< double, 3, 3 > rotZ; rotZ.set_identity(); rotZ[0][0] = cos(z); rotZ[1][1] = rotZ[0][0]; rotZ[0][1] = -sin(z); rotZ[1][0] = -rotZ[0][1]; mitk::BaseGeometry::Pointer geom = this->GetGeometry(); mitk::Point3D center = geom->GetCenter(); vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); vtkSmartPointer container = vtkSmartPointer::New(); for (int j=0; jGetPoint(j); vnl_vector_fixed< double, 3 > dir; dir[0] = p[0]-center[0]; dir[1] = p[1]-center[1]; dir[2] = p[2]-center[2]; dir = rotZ*rotY*rotX*dir; dir[0] += center[0]; dir[1] += center[1]; dir[2] += center[2]; vtkIdType id = vtkNewPoints->InsertNextPoint(dir.data_block()); container->GetPointIds()->InsertNextId(id); } vtkNewCells->InsertNextCell(container); } m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); } void mitk::FiberBundle::ScaleFibers(double x, double y, double z, bool subtractCenter) { MITK_INFO << "Scaling fibers"; boost::progress_display disp(m_NumFibers); mitk::BaseGeometry* geom = this->GetGeometry(); mitk::Point3D c = geom->GetCenter(); vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); vtkSmartPointer container = vtkSmartPointer::New(); for (int j=0; jGetPoint(j); if (subtractCenter) { p[0] -= c[0]; p[1] -= c[1]; p[2] -= c[2]; } p[0] *= x; p[1] *= y; p[2] *= z; if (subtractCenter) { p[0] += c[0]; p[1] += c[1]; p[2] += c[2]; } vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } vtkNewCells->InsertNextCell(container); } m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); } void mitk::FiberBundle::TranslateFibers(double x, double y, double z) { vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); vtkSmartPointer container = vtkSmartPointer::New(); for (int j=0; jGetPoint(j); p[0] += x; p[1] += y; p[2] += z; vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } vtkNewCells->InsertNextCell(container); } m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); } void mitk::FiberBundle::MirrorFibers(unsigned int axis) { if (axis>2) return; MITK_INFO << "Mirroring fibers"; boost::progress_display disp(m_NumFibers); vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); vtkSmartPointer container = vtkSmartPointer::New(); for (int j=0; jGetPoint(j); p[axis] = -p[axis]; vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } vtkNewCells->InsertNextCell(container); } m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); } void mitk::FiberBundle::RemoveDir(vnl_vector_fixed dir, double threshold) { dir.normalize(); vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); boost::progress_display disp(m_FiberPolyData->GetNumberOfCells()); for (int i=0; iGetNumberOfCells(); i++) { ++disp ; vtkCell* cell = m_FiberPolyData->GetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); // calculate curvatures vtkSmartPointer container = vtkSmartPointer::New(); bool discard = false; for (int j=0; jGetPoint(j, p1); double p2[3]; points->GetPoint(j+1, p2); vnl_vector_fixed< double, 3 > v1; v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; if (v1.magnitude()>0.001) { v1.normalize(); if (fabs(dot_product(v1,dir))>threshold) { discard = true; break; } } } if (!discard) { for (int j=0; jGetPoint(j, p1); vtkIdType id = vtkNewPoints->InsertNextPoint(p1); container->GetPointIds()->InsertNextId(id); } vtkNewCells->InsertNextCell(container); } } m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); // UpdateColorCoding(); // UpdateFiberGeometry(); } bool mitk::FiberBundle::ApplyCurvatureThreshold(float minRadius, bool deleteFibers) { if (minRadius<0) return true; vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); MITK_INFO << "Applying curvature threshold"; boost::progress_display disp(m_FiberPolyData->GetNumberOfCells()); for (int i=0; iGetNumberOfCells(); i++) { ++disp ; vtkCell* cell = m_FiberPolyData->GetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); // calculate curvatures vtkSmartPointer container = vtkSmartPointer::New(); for (int j=0; jGetPoint(j, p1); double p2[3]; points->GetPoint(j+1, p2); double p3[3]; points->GetPoint(j+2, p3); vnl_vector_fixed< float, 3 > v1, v2, v3; v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; v2[0] = p3[0]-p2[0]; v2[1] = p3[1]-p2[1]; v2[2] = p3[2]-p2[2]; v3[0] = p1[0]-p3[0]; v3[1] = p1[1]-p3[1]; v3[2] = p1[2]-p3[2]; float a = v1.magnitude(); float b = v2.magnitude(); float c = v3.magnitude(); float r = a*b*c/std::sqrt((a+b+c)*(a+b-c)*(b+c-a)*(a-b+c)); // radius of triangle via Heron's formula (area of triangle) vtkIdType id = vtkNewPoints->InsertNextPoint(p1); container->GetPointIds()->InsertNextId(id); if (deleteFibers && rInsertNextCell(container); container = vtkSmartPointer::New(); } else if (j==numPoints-3) { id = vtkNewPoints->InsertNextPoint(p2); container->GetPointIds()->InsertNextId(id); id = vtkNewPoints->InsertNextPoint(p3); container->GetPointIds()->InsertNextId(id); vtkNewCells->InsertNextCell(container); } } } if (vtkNewCells->GetNumberOfCells()<=0) return false; m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); return true; } bool mitk::FiberBundle::RemoveShortFibers(float lengthInMM) { MITK_INFO << "Removing short fibers"; if (lengthInMM<=0 || lengthInMMm_MaxFiberLength) // can't remove all fibers { MITK_WARN << "Process aborted. No fibers would be left!"; return false; } vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); float min = m_MaxFiberLength; boost::progress_display disp(m_NumFibers); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); if (m_FiberLengths.at(i)>=lengthInMM) { vtkSmartPointer container = vtkSmartPointer::New(); for (int j=0; jGetPoint(j); vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } vtkNewCells->InsertNextCell(container); if (m_FiberLengths.at(i)GetNumberOfCells()<=0) return false; m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); return true; } bool mitk::FiberBundle::RemoveLongFibers(float lengthInMM) { if (lengthInMM<=0 || lengthInMM>m_MaxFiberLength) return true; if (lengthInMM vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); MITK_INFO << "Removing long fibers"; boost::progress_display disp(m_NumFibers); for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); if (m_FiberLengths.at(i)<=lengthInMM) { vtkSmartPointer container = vtkSmartPointer::New(); for (int j=0; jGetPoint(j); vtkIdType id = vtkNewPoints->InsertNextPoint(p); container->GetPointIds()->InsertNextId(id); } vtkNewCells->InsertNextCell(container); } } if (vtkNewCells->GetNumberOfCells()<=0) return false; m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); return true; } void mitk::FiberBundle::ResampleSpline(float pointDistance, double tension, double continuity, double bias ) { if (pointDistance<=0) return; vtkSmartPointer vtkSmoothPoints = vtkSmartPointer::New(); //in smoothpoints the interpolated points representing a fiber are stored. //in vtkcells all polylines are stored, actually all id's of them are stored vtkSmartPointer vtkSmoothCells = vtkSmartPointer::New(); //cellcontainer for smoothed lines vtkIdType pointHelperCnt = 0; MITK_INFO << "Smoothing fibers"; vtkSmartPointer newFiberWeights = vtkSmartPointer::New(); newFiberWeights->SetName("FIBER_WEIGHTS"); newFiberWeights->SetNumberOfValues(m_NumFibers); boost::progress_display disp(m_NumFibers); #pragma omp parallel for for (int i=0; i newPoints = vtkSmartPointer::New(); float length = 0; float weight = 1; #pragma omp critical { length = m_FiberLengths.at(i); weight = m_FiberWeights->GetValue(i); ++disp; vtkCell* cell = m_FiberPolyData->GetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); for (int j=0; jInsertNextPoint(points->GetPoint(j)); } int sampling = std::ceil(length/pointDistance); vtkSmartPointer xSpline = vtkSmartPointer::New(); vtkSmartPointer ySpline = vtkSmartPointer::New(); vtkSmartPointer zSpline = vtkSmartPointer::New(); xSpline->SetDefaultBias(bias); xSpline->SetDefaultTension(tension); xSpline->SetDefaultContinuity(continuity); ySpline->SetDefaultBias(bias); ySpline->SetDefaultTension(tension); ySpline->SetDefaultContinuity(continuity); zSpline->SetDefaultBias(bias); zSpline->SetDefaultTension(tension); zSpline->SetDefaultContinuity(continuity); vtkSmartPointer spline = vtkSmartPointer::New(); spline->SetXSpline(xSpline); spline->SetYSpline(ySpline); spline->SetZSpline(zSpline); spline->SetPoints(newPoints); vtkSmartPointer functionSource = vtkSmartPointer::New(); functionSource->SetParametricFunction(spline); functionSource->SetUResolution(sampling); functionSource->SetVResolution(sampling); functionSource->SetWResolution(sampling); functionSource->Update(); vtkPolyData* outputFunction = functionSource->GetOutput(); vtkPoints* tmpSmoothPnts = outputFunction->GetPoints(); //smoothPoints of current fiber vtkSmartPointer smoothLine = vtkSmartPointer::New(); smoothLine->GetPointIds()->SetNumberOfIds(tmpSmoothPnts->GetNumberOfPoints()); #pragma omp critical { for (int j=0; jGetNumberOfPoints(); j++) { smoothLine->GetPointIds()->SetId(j, j+pointHelperCnt); vtkSmoothPoints->InsertNextPoint(tmpSmoothPnts->GetPoint(j)); } newFiberWeights->SetValue(vtkSmoothCells->GetNumberOfCells(), weight); vtkSmoothCells->InsertNextCell(smoothLine); pointHelperCnt += tmpSmoothPnts->GetNumberOfPoints(); } } SetFiberWeights(newFiberWeights); m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkSmoothPoints); m_FiberPolyData->SetLines(vtkSmoothCells); this->SetFiberPolyData(m_FiberPolyData, true); } void mitk::FiberBundle::ResampleSpline(float pointDistance) { ResampleSpline(pointDistance, 0, 0, 0 ); } unsigned long mitk::FiberBundle::GetNumberOfPoints() const { unsigned long points = 0; for (int i=0; iGetNumberOfCells(); i++) { vtkCell* cell = m_FiberPolyData->GetCell(i); points += cell->GetNumberOfPoints(); } return points; } void mitk::FiberBundle::Compress(float error) { vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); MITK_INFO << "Compressing fibers"; unsigned long numRemovedPoints = 0; boost::progress_display disp(m_FiberPolyData->GetNumberOfCells()); vtkSmartPointer newFiberWeights = vtkSmartPointer::New(); newFiberWeights->SetName("FIBER_WEIGHTS"); newFiberWeights->SetNumberOfValues(m_NumFibers); #pragma omp parallel for for (int i=0; iGetNumberOfCells(); i++) { std::vector< vnl_vector_fixed< double, 3 > > vertices; float weight = 1; #pragma omp critical { ++disp; weight = m_FiberWeights->GetValue(i); vtkCell* cell = m_FiberPolyData->GetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); for (int j=0; jGetPoint(j, cand); vnl_vector_fixed< double, 3 > candV; candV[0]=cand[0]; candV[1]=cand[1]; candV[2]=cand[2]; vertices.push_back(candV); } } // calculate curvatures int numPoints = vertices.size(); std::vector< int > removedPoints; removedPoints.resize(numPoints, 0); removedPoints[0]=-1; removedPoints[numPoints-1]=-1; vtkSmartPointer container = vtkSmartPointer::New(); int remCounter = 0; bool pointFound = true; while (pointFound) { pointFound = false; double minError = error; int removeIndex = -1; for (unsigned int j=0; j candV = vertices.at(j); int validP = -1; vnl_vector_fixed< double, 3 > pred; for (int k=j-1; k>=0; k--) if (removedPoints[k]<=0) { pred = vertices.at(k); validP = k; break; } int validS = -1; vnl_vector_fixed< double, 3 > succ; for (int k=j+1; k=0 && validS>=0) { double a = (candV-pred).magnitude(); double b = (candV-succ).magnitude(); double c = (pred-succ).magnitude(); double s=0.5*(a+b+c); double hc=(2.0/c)*sqrt(fabs(s*(s-a)*(s-b)*(s-c))); if (hcInsertNextPoint(vertices.at(j).data_block()); container->GetPointIds()->InsertNextId(id); } } } #pragma omp critical { newFiberWeights->SetValue(vtkNewCells->GetNumberOfCells(), weight); numRemovedPoints += remCounter; vtkNewCells->InsertNextCell(container); } } if (vtkNewCells->GetNumberOfCells()>0) { MITK_INFO << "Removed points: " << numRemovedPoints; SetFiberWeights(newFiberWeights); m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); } } void mitk::FiberBundle::ResampleLinear(double pointDistance) { vtkSmartPointer vtkNewPoints = vtkSmartPointer::New(); vtkSmartPointer vtkNewCells = vtkSmartPointer::New(); MITK_INFO << "Resampling fibers (linear)"; boost::progress_display disp(m_FiberPolyData->GetNumberOfCells()); vtkSmartPointer newFiberWeights = vtkSmartPointer::New(); newFiberWeights->SetName("FIBER_WEIGHTS"); newFiberWeights->SetNumberOfValues(m_NumFibers); #pragma omp parallel for for (int i=0; iGetNumberOfCells(); i++) { std::vector< vnl_vector_fixed< double, 3 > > vertices; float weight = 1; #pragma omp critical { ++disp; weight = m_FiberWeights->GetValue(i); vtkCell* cell = m_FiberPolyData->GetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); for (int j=0; jGetPoint(j, cand); vnl_vector_fixed< double, 3 > candV; candV[0]=cand[0]; candV[1]=cand[1]; candV[2]=cand[2]; vertices.push_back(candV); } } vtkSmartPointer container = vtkSmartPointer::New(); vnl_vector_fixed< double, 3 > lastV = vertices.at(0); #pragma omp critical { vtkIdType id = vtkNewPoints->InsertNextPoint(lastV.data_block()); container->GetPointIds()->InsertNextId(id); } for (unsigned int j=1; j vec = vertices.at(j) - lastV; double new_dist = vec.magnitude(); if (new_dist >= pointDistance) { vnl_vector_fixed< double, 3 > newV = lastV; if ( new_dist-pointDistance <= mitk::eps ) { vec.normalize(); newV += vec * pointDistance; } else { // intersection between sphere (radius 'pointDistance', center 'lastV') and line (direction 'd' and point 'p') vnl_vector_fixed< double, 3 > p = vertices.at(j-1); vnl_vector_fixed< double, 3 > d = vertices.at(j) - p; double a = d[0]*d[0] + d[1]*d[1] + d[2]*d[2]; double b = 2 * (d[0] * (p[0] - lastV[0]) + d[1] * (p[1] - lastV[1]) + d[2] * (p[2] - lastV[2])); double c = (p[0] - lastV[0])*(p[0] - lastV[0]) + (p[1] - lastV[1])*(p[1] - lastV[1]) + (p[2] - lastV[2])*(p[2] - lastV[2]) - pointDistance*pointDistance; double v1 =(-b + std::sqrt(b*b-4*a*c))/(2*a); double v2 =(-b - std::sqrt(b*b-4*a*c))/(2*a); if (v1>0) newV = p + d * v1; else if (v2>0) newV = p + d * v2; else MITK_INFO << "ERROR1 - linear resampling"; j--; } #pragma omp critical { vtkIdType id = vtkNewPoints->InsertNextPoint(newV.data_block()); container->GetPointIds()->InsertNextId(id); } lastV = newV; } else if (j==vertices.size()-1 && new_dist>0.0001) { #pragma omp critical { vtkIdType id = vtkNewPoints->InsertNextPoint(vertices.at(j).data_block()); container->GetPointIds()->InsertNextId(id); } } } #pragma omp critical { newFiberWeights->SetValue(vtkNewCells->GetNumberOfCells(), weight); vtkNewCells->InsertNextCell(container); } } if (vtkNewCells->GetNumberOfCells()>0) { SetFiberWeights(newFiberWeights); m_FiberPolyData = vtkSmartPointer::New(); m_FiberPolyData->SetPoints(vtkNewPoints); m_FiberPolyData->SetLines(vtkNewCells); this->SetFiberPolyData(m_FiberPolyData, true); } } // reapply selected colorcoding in case PolyData structure has changed bool mitk::FiberBundle::Equals(mitk::FiberBundle* fib, double eps) { if (fib==nullptr) { MITK_INFO << "Reference bundle is nullptr!"; return false; } if (m_NumFibers!=fib->GetNumFibers()) { MITK_INFO << "Unequal number of fibers!"; MITK_INFO << m_NumFibers << " vs. " << fib->GetNumFibers(); return false; } for (int i=0; iGetCell(i); int numPoints = cell->GetNumberOfPoints(); vtkPoints* points = cell->GetPoints(); vtkCell* cell2 = fib->GetFiberPolyData()->GetCell(i); int numPoints2 = cell2->GetNumberOfPoints(); vtkPoints* points2 = cell2->GetPoints(); if (numPoints2!=numPoints) { MITK_INFO << "Unequal number of points in fiber " << i << "!"; MITK_INFO << numPoints2 << " vs. " << numPoints; return false; } for (int j=0; jGetPoint(j); double* p2 = points2->GetPoint(j); if (fabs(p1[0]-p2[0])>eps || fabs(p1[1]-p2[1])>eps || fabs(p1[2]-p2[2])>eps) { MITK_INFO << "Unequal points in fiber " << i << " at position " << j << "!"; MITK_INFO << "p1: " << p1[0] << ", " << p1[1] << ", " << p1[2]; MITK_INFO << "p2: " << p2[0] << ", " << p2[1] << ", " << p2[2]; return false; } } } return true; } void mitk::FiberBundle::PrintSelf(std::ostream &os, itk::Indent indent) const { os << indent << this->GetNameOfClass() << ":\n"; os << indent << "Number of fibers: " << this->GetNumFibers() << std::endl; os << indent << "Min. fiber length: " << this->GetMinFiberLength() << std::endl; os << indent << "Max. fiber length: " << this->GetMaxFiberLength() << std::endl; os << indent << "Mean fiber length: " << this->GetMeanFiberLength() << std::endl; os << indent << "Median fiber length: " << this->GetMedianFiberLength() << std::endl; os << indent << "STDEV fiber length: " << this->GetLengthStDev() << std::endl; os << indent << "Number of points: " << this->GetNumberOfPoints() << std::endl; Superclass::PrintSelf(os, indent); } /* ESSENTIAL IMPLEMENTATION OF SUPERCLASS METHODS */ void mitk::FiberBundle::UpdateOutputInformation() { } void mitk::FiberBundle::SetRequestedRegionToLargestPossibleRegion() { } bool mitk::FiberBundle::RequestedRegionIsOutsideOfTheBufferedRegion() { return false; } bool mitk::FiberBundle::VerifyRequestedRegion() { return true; } void mitk::FiberBundle::SetRequestedRegion(const itk::DataObject* ) { } diff --git a/Modules/DiffusionImaging/FiberTracking/Resources/Shaders/mitkShaderFiberClipping.xml b/Modules/DiffusionImaging/FiberTracking/Resources/Shaders/mitkShaderFiberClipping.xml deleted file mode 100644 index da3da5b910..0000000000 --- a/Modules/DiffusionImaging/FiberTracking/Resources/Shaders/mitkShaderFiberClipping.xml +++ /dev/null @@ -1,56 +0,0 @@ - - - - - varying vec3 positionWorld; - varying vec3 color; - - void main(void) - { - color = gl_Color.rgb; - positionWorld = vec3(gl_Vertex); - gl_Position = ftransform(); - } - - - - uniform vec4 slicingPlane; - uniform float fiberThickness; - uniform int fiberFadingON; - uniform float fiberOpacity; - - varying vec3 positionWorld; - varying vec3 color; - - void main(void) - { - float r1 = dot(positionWorld, slicingPlane.xyz) - slicingPlane.w; - - if ( abs(r1) > fiberThickness ) - discard; - - if (fiberFadingON != 0) - { - float x = (r1+fiberThickness)/(fiberThickness*2.0); - x = 1.0 - x; - gl_FragColor = vec4(color*x, fiberOpacity); - }else{ - gl_FragColor = vec4(color, fiberOpacity); - } - - } - - - - - - - - - diff --git a/Modules/DiffusionImaging/FiberTracking/Resources/empty b/Modules/DiffusionImaging/FiberTracking/Resources/empty new file mode 100644 index 0000000000..e69de29bb2 diff --git a/Modules/DiffusionImaging/FiberTracking/files.cmake b/Modules/DiffusionImaging/FiberTracking/files.cmake index 92512547a1..4649890eb3 100644 --- a/Modules/DiffusionImaging/FiberTracking/files.cmake +++ b/Modules/DiffusionImaging/FiberTracking/files.cmake @@ -1,94 +1,91 @@ set(CPP_FILES mitkFiberTrackingModuleActivator.cpp ## IO datastructures IODataStructures/FiberBundle/mitkFiberBundle.cpp IODataStructures/FiberBundle/mitkTrackvis.cpp IODataStructures/PlanarFigureComposite/mitkPlanarFigureComposite.cpp IODataStructures/mitkTractographyForest.cpp # Interactions # Tractography Algorithms/GibbsTracking/mitkParticleGrid.cpp Algorithms/GibbsTracking/mitkMetropolisHastingsSampler.cpp Algorithms/GibbsTracking/mitkEnergyComputer.cpp Algorithms/GibbsTracking/mitkGibbsEnergyComputer.cpp Algorithms/GibbsTracking/mitkFiberBuilder.cpp Algorithms/GibbsTracking/mitkSphereInterpolator.cpp Algorithms/itkStreamlineTrackingFilter.cpp Algorithms/TrackingHandlers/mitkTrackingDataHandler.cpp Algorithms/TrackingHandlers/mitkTrackingHandlerTensor.cpp Algorithms/TrackingHandlers/mitkTrackingHandlerPeaks.cpp Algorithms/TrackingHandlers/mitkTrackingHandlerOdf.cpp ) set(H_FILES # DataStructures -> FiberBundle IODataStructures/FiberBundle/mitkFiberBundle.h IODataStructures/FiberBundle/mitkTrackvis.h IODataStructures/mitkFiberfoxParameters.h IODataStructures/mitkTractographyForest.h # Algorithms Algorithms/itkTractDensityImageFilter.h Algorithms/itkTractsToFiberEndingsImageFilter.h Algorithms/itkTractsToRgbaImageFilter.h Algorithms/itkTractsToVectorImageFilter.h Algorithms/itkEvaluateDirectionImagesFilter.h Algorithms/itkEvaluateTractogramDirectionsFilter.h Algorithms/itkFiberCurvatureFilter.h # Tractography Algorithms/TrackingHandlers/mitkTrackingDataHandler.h Algorithms/TrackingHandlers/mitkTrackingHandlerRandomForest.h Algorithms/TrackingHandlers/mitkTrackingHandlerTensor.h Algorithms/TrackingHandlers/mitkTrackingHandlerPeaks.h Algorithms/TrackingHandlers/mitkTrackingHandlerOdf.h Algorithms/itkGibbsTrackingFilter.h Algorithms/itkStochasticTractographyFilter.h Algorithms/GibbsTracking/mitkParticle.h Algorithms/GibbsTracking/mitkParticleGrid.h Algorithms/GibbsTracking/mitkMetropolisHastingsSampler.h Algorithms/GibbsTracking/mitkSimpSamp.h Algorithms/GibbsTracking/mitkEnergyComputer.h Algorithms/GibbsTracking/mitkGibbsEnergyComputer.h Algorithms/GibbsTracking/mitkSphereInterpolator.h Algorithms/GibbsTracking/mitkFiberBuilder.h Algorithms/itkStreamlineTrackingFilter.h # Fiberfox Fiberfox/itkFibersFromPlanarFiguresFilter.h Fiberfox/itkTractsToDWIImageFilter.h Fiberfox/itkKspaceImageFilter.h Fiberfox/itkDftImageFilter.h Fiberfox/itkFieldmapGeneratorFilter.h Fiberfox/SignalModels/mitkDiffusionSignalModel.h Fiberfox/SignalModels/mitkTensorModel.h Fiberfox/SignalModels/mitkBallModel.h Fiberfox/SignalModels/mitkDotModel.h Fiberfox/SignalModels/mitkAstroStickModel.h Fiberfox/SignalModels/mitkStickModel.h Fiberfox/SignalModels/mitkRawShModel.h Fiberfox/SignalModels/mitkDiffusionNoiseModel.h Fiberfox/SignalModels/mitkRicianNoiseModel.h Fiberfox/SignalModels/mitkChiSquareNoiseModel.h Fiberfox/Sequences/mitkAcquisitionType.h Fiberfox/Sequences/mitkSingleShotEpi.h Fiberfox/Sequences/mitkCartesianReadout.h ) set(RESOURCE_FILES # Binary directory resources FiberTrackingLUTBaryCoords.bin FiberTrackingLUTIndices.bin - - # Shaders - Shaders/mitkShaderFiberClipping.xml ) diff --git a/Modules/GPGPU/CMakeLists.txt b/Modules/GPGPU/CMakeLists.txt index 694b7ba6c6..bcdfc0fa98 100644 --- a/Modules/GPGPU/CMakeLists.txt +++ b/Modules/GPGPU/CMakeLists.txt @@ -1,17 +1,17 @@ if(APPLE) message(STATUS "Module GPGPU is not ported to MacOS yet") else(APPLE) set(package_deps) if(UNIX) list(APPEND package_deps X11) endif() MITK_CREATE_MODULE( # INCLUDE_DIRS . DEPENDS MitkCore - PACKAGE_DEPENDS ${package_deps} GLEW Qt5|Widgets + PACKAGE_DEPENDS ${package_deps} OpenGL Qt5|Widgets ) endif(APPLE) diff --git a/Modules/GPGPU/mitkGPGPU.h b/Modules/GPGPU/mitkGPGPU.h index 6b6850f9e8..82e8f3ecfb 100644 --- a/Modules/GPGPU/mitkGPGPU.h +++ b/Modules/GPGPU/mitkGPGPU.h @@ -1,176 +1,176 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKGPGPU_H #define MITKGPGPU_H -#include +#include #include #ifdef _WIN32 #include #else #include #include #endif #include #include "mitkCommon.h" namespace mitk { //##Documentation //## @brief GPGPU class MITKGPGPU_EXPORT GPGPU { public: enum TextureFormat { FLOAT32_LUMINANCE, FLOAT32_LUMINANCE_ALPHA, FLOAT32_RGBA, UINT8_RGBA, }; class MITKGPGPU_EXPORT Texture { public: Texture(mitk::GPGPU::TextureFormat format, int width, int height, int depth = 0); ~Texture(); void ActivateAsSource(int unit); void ActivateAsDestination(); void Upload(mitk::GPGPU::TextureFormat inputformat, const void *src); void Download(mitk::GPGPU::TextureFormat inputformat, void *dst); int GetWidth(); int GetHeigth(); int GetDepth(); private: mitk::GPGPU::TextureFormat myFormat; int myWidth, myHeight, myDepth; int glTarget; int glTextureHandle; int glFBOHandle; }; class MITKGPGPU_EXPORT Shader { public: Shader(char *source); ~Shader(); void Activate(); void SetUniform(char *name, int i0); void SetUniform(char *name, int i0, int i1); void SetUniform(char *name, int i0, int i1, int i2); void SetUniform(char *name, int i0, int i1, int i2, int i3); void SetUniform(char *name, float i0); void SetUniform(char *name, float i0, float i1); void SetUniform(char *name, float i0, float i1, float i2); void SetUniform(char *name, float i0, float i1, float i2, float i3); private: int GetUniformLocation(char *name); int glHandleVertex; int glHandleFragment; int glHandleProgram; }; GPGPU(); ~GPGPU(); void Activate(); void Deactivate(); void Run(); void Run(float start, float end); private: #ifdef _WIN32 HWND windowHandle; HDC windowsContext; HGLRC openGLContext; #else GLXContext openGLContext; GLXDrawable GLX_drawable; Display *X_display; #endif }; } // namespace mitk /*{ mitk::GPGPU *gpu=new mitk::GPGPU(); gpu->Activate(); mitk::GPGPU::Texture *input=new mitk::GPGPU::Texture( GLSL_FLOAT32_LUMINANCE , 128,128 ); mitk::GPGPU::Texture *output=new mitk::GPGPU::Texture( GLSL_FLOAT32_LUMINANCE , 128,128 ); mitk::GPGPU::Shader *shader = new mitk::GPGPU::Shader( "uniform float invsize;\n" "uniform sampler2D input;\n" "uniform sampler2D input2;\n" "uniform sampler2D input3;\n" "void main()\n" "{\n" " vec2 pos=gl_FragCoord.xy*invsize; \n" " int x; \n" " float y; \n" " vec2 z; \n" " vec4 ddd; \n" " vec4 gl_FragColor; \n" " float x = texture2D(input,vec2(x,y) ); " gl_FragColor.r = x; \n" "}\n" ); input->Upload( GLSL_FLOAT32_LUMINANCE, eurerArray); shader->Activate(); shader->SetUniform("input",0); gpu->ActivateAsSource(input,0); gpu->ActivateAsDestination(output); gpu->Run(); input2->ActivateAsSource(0); output2->ActivateAsDestination(); gpu->Run(); output->Download( GLSL_FLOAT32_LUMINANCE, zielArray); input2->Upload( GLSL_FLOAT32_LUMINANCE, eurerArray); input2->ActivateAsSource(0); output2->ActivateAsDestination(); shader->SetUniform("input",0); gpu->Deactivate(); delete gpu; }*/ #endif diff --git a/Modules/Gizmo/src/mitkGizmoMapper2D.cpp b/Modules/Gizmo/src/mitkGizmoMapper2D.cpp index 39fe9bb696..d0703db556 100644 --- a/Modules/Gizmo/src/mitkGizmoMapper2D.cpp +++ b/Modules/Gizmo/src/mitkGizmoMapper2D.cpp @@ -1,341 +1,341 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkGizmoMapper2D.h" #include "mitkGizmo.h" // MITK includes #include #include #include #include #include // VTK includes #include #include #include #include #include #include #include #include #include mitk::GizmoMapper2D::LocalStorage::LocalStorage() { - m_VtkPolyDataMapper = vtkSmartPointer::New(); + m_VtkPolyDataMapper = vtkSmartPointer::New(); m_Actor = vtkSmartPointer::New(); m_Actor->SetMapper(m_VtkPolyDataMapper); } const mitk::Gizmo *mitk::GizmoMapper2D::GetInput() { return static_cast(GetDataNode()->GetData()); } void mitk::GizmoMapper2D::ResetMapper(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); ls->m_Actor->VisibilityOff(); } namespace { //! Helper method: will assign given value to all points in given polydata object. void AssignScalarValueTo(vtkPolyData *polydata, char value) { vtkSmartPointer pointData = vtkSmartPointer::New(); int numberOfPoints = polydata->GetNumberOfPoints(); pointData->SetNumberOfComponents(1); pointData->SetNumberOfTuples(numberOfPoints); pointData->FillComponent(0, value); polydata->GetPointData()->SetScalars(pointData); } //! Helper method: will create a vtkPolyData representing a disk //! around center, inside the plane defined by viewRight and viewUp, //! and with the given radius. vtkSmartPointer Create2DDisk(mitk::Vector3D viewRight, mitk::Vector3D viewUp, mitk::Point3D center, double radius) { // build the axis itself (as a tube around the line defining the axis) vtkSmartPointer disk = vtkSmartPointer::New(); mitk::Vector3D ringPointer; unsigned int numberOfRingPoints = 36; vtkSmartPointer ringPoints = vtkSmartPointer::New(); vtkSmartPointer ringPoly = vtkSmartPointer::New(); ringPoly->InsertNextCell(numberOfRingPoints + 1); for (unsigned int segment = 0; segment < numberOfRingPoints; ++segment) { double x = std::cos((double)(segment) / (double)numberOfRingPoints * 2.0 * vtkMath::Pi()); double y = std::sin((double)(segment) / (double)numberOfRingPoints * 2.0 * vtkMath::Pi()); ringPointer = viewRight * x + viewUp * y; ringPoints->InsertPoint(segment, (center + ringPointer * radius).GetDataPointer()); ringPoly->InsertCellPoint(segment); } ringPoly->InsertCellPoint(0); disk->SetPoints(ringPoints); disk->SetPolys(ringPoly); return disk; } //! Helper method: will create a vtkPolyData representing a 2D arrow //! that is oriented from arrowStart to arrowTip, orthogonal //! to camera direction. The arrow tip will contain scalar values //! of vertexValueScale, the arrow shaft will contain scalar values //! of vertexValueMove. Those values are used for picking during interaction. vtkSmartPointer Create2DArrow(mitk::Vector3D cameraDirection, mitk::Point3D arrowStart, mitk::Point3D arrowTip, int vertexValueMove, int vertexValueScale) { mitk::Vector3D arrowDirection = arrowTip - arrowStart; mitk::Vector3D arrowOrthogonal = itk::CrossProduct(cameraDirection, arrowDirection); arrowOrthogonal.Normalize(); double triangleFraction = 0.2; vtkSmartPointer arrow = vtkSmartPointer::New(); vtkSmartPointer points = vtkSmartPointer::New(); // shaft : points 0, 1 points->InsertPoint(0, arrowStart.GetDataPointer()); points->InsertPoint(1, (arrowStart + arrowDirection * (1.0 - triangleFraction)).GetDataPointer()); // tip : points 2, 3, 4 points->InsertPoint(2, arrowTip.GetDataPointer()); points->InsertPoint(3, (arrowStart + (1.0 - triangleFraction) * arrowDirection + arrowOrthogonal * (0.5 * triangleFraction * arrowDirection.GetNorm())) .GetDataPointer()); points->InsertPoint(4, (arrowStart + (1.0 - triangleFraction) * arrowDirection - arrowOrthogonal * (0.5 * triangleFraction * arrowDirection.GetNorm())) .GetDataPointer()); arrow->SetPoints(points); // define line connection for shaft vtkSmartPointer lines = vtkSmartPointer::New(); vtkIdType shaftLinePoints[] = {0, 1}; lines->InsertNextCell(2, shaftLinePoints); arrow->SetLines(lines); // define polygon for triangle vtkSmartPointer polys = vtkSmartPointer::New(); vtkIdType tipLinePoints[] = {2, 3, 4}; polys->InsertNextCell(3, tipLinePoints); arrow->SetPolys(polys); // assign scalar values vtkSmartPointer pointData = vtkSmartPointer::New(); pointData->SetNumberOfComponents(1); pointData->SetNumberOfTuples(5); pointData->FillComponent(0, vertexValueScale); pointData->SetTuple1(0, vertexValueMove); pointData->SetTuple1(1, vertexValueMove); arrow->GetPointData()->SetScalars(pointData); return arrow; } } vtkPolyData *mitk::GizmoMapper2D::GetVtkPolyData(mitk::BaseRenderer *renderer) { return m_LSH.GetLocalStorage(renderer)->m_VtkPolyDataMapper->GetInput(); } void mitk::GizmoMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { auto gizmo = GetInput(); auto node = GetDataNode(); LocalStorage *ls = m_LSH.GetLocalStorage(renderer); // check if something important has changed and we need to re-render if ((ls->m_LastUpdateTime >= node->GetMTime()) && (ls->m_LastUpdateTime >= gizmo->GetPipelineMTime()) && (ls->m_LastUpdateTime >= renderer->GetCurrentWorldPlaneGeometryUpdateTime()) && (ls->m_LastUpdateTime >= renderer->GetCurrentWorldPlaneGeometry()->GetMTime()) && (ls->m_LastUpdateTime >= node->GetPropertyList()->GetMTime()) && (ls->m_LastUpdateTime >= node->GetPropertyList(renderer)->GetMTime())) { return; } ls->m_LastUpdateTime.Modified(); // some special handling around visibility: let two properties steer // visibility in 2D instead of many renderer specific "visible" properties bool visible2D = true; this->GetDataNode()->GetBoolProperty("show in 2D", visible2D); if (!visible2D && renderer->GetMapperID() == BaseRenderer::Standard2D) { ls->m_Actor->VisibilityOff(); return; } else { ls->m_Actor->VisibilityOn(); } auto camera = renderer->GetVtkRenderer()->GetActiveCamera(); auto plane = renderer->GetCurrentWorldPlaneGeometry(); Point3D gizmoCenterView = plane->ProjectPointOntoPlane(gizmo->GetCenter()); Vector3D viewUp; camera->GetViewUp(viewUp.GetDataPointer()); Vector3D cameraDirection; camera->GetDirectionOfProjection(cameraDirection.GetDataPointer()); Vector3D viewRight = itk::CrossProduct(viewUp, cameraDirection); auto appender = vtkSmartPointer::New(); double diagonal = std::min(renderer->GetSizeX(), renderer->GetSizeY()); double arrowLength = 0.1 * diagonal; // fixed in relation to window size auto disk = Create2DDisk(viewRight, viewUp, gizmoCenterView - cameraDirection, 0.1 * arrowLength); AssignScalarValueTo(disk, Gizmo::MoveFreely); appender->AddInputData(disk); // loop over directions -1 and +1 for arrows for (double direction = -1.0; direction < 2.0; direction += 2.0) { auto axisX = Create2DArrow(cameraDirection, gizmoCenterView, plane->ProjectPointOntoPlane(gizmo->GetCenter() + (gizmo->GetAxisX() * arrowLength) * direction), Gizmo::MoveAlongAxisX, Gizmo::ScaleX); appender->AddInputData(axisX); auto axisY = Create2DArrow(cameraDirection, gizmoCenterView, plane->ProjectPointOntoPlane(gizmo->GetCenter() + (gizmo->GetAxisY() * arrowLength) * direction), Gizmo::MoveAlongAxisY, Gizmo::ScaleY); appender->AddInputData(axisY); auto axisZ = Create2DArrow(cameraDirection, gizmoCenterView, plane->ProjectPointOntoPlane(gizmo->GetCenter() + (gizmo->GetAxisZ() * arrowLength) * direction), Gizmo::MoveAlongAxisZ, Gizmo::ScaleZ); appender->AddInputData(axisZ); } ls->m_VtkPolyDataMapper->SetInputConnection(appender->GetOutputPort()); ApplyVisualProperties(renderer); } void mitk::GizmoMapper2D::ApplyVisualProperties(BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); float lineWidth = 3.0f; ls->m_Actor->GetProperty()->SetLineWidth(lineWidth); mitk::LookupTableProperty::Pointer lookupTableProp; this->GetDataNode()->GetProperty(lookupTableProp, "LookupTable", renderer); if (lookupTableProp.IsNotNull()) { ls->m_VtkPolyDataMapper->SetLookupTable(lookupTableProp->GetLookupTable()->GetVtkLookupTable()); } bool scalarVisibility = false; this->GetDataNode()->GetBoolProperty("scalar visibility", scalarVisibility); ls->m_VtkPolyDataMapper->SetScalarVisibility((scalarVisibility ? 1 : 0)); if (scalarVisibility) { mitk::VtkScalarModeProperty *scalarMode; if (this->GetDataNode()->GetProperty(scalarMode, "scalar mode", renderer)) ls->m_VtkPolyDataMapper->SetScalarMode(scalarMode->GetVtkScalarMode()); else ls->m_VtkPolyDataMapper->SetScalarModeToDefault(); bool colorMode = false; this->GetDataNode()->GetBoolProperty("color mode", colorMode); ls->m_VtkPolyDataMapper->SetColorMode((colorMode ? 1 : 0)); double scalarsMin = 0; this->GetDataNode()->GetDoubleProperty("ScalarsRangeMinimum", scalarsMin, renderer); double scalarsMax = 1.0; this->GetDataNode()->GetDoubleProperty("ScalarsRangeMaximum", scalarsMax, renderer); ls->m_VtkPolyDataMapper->SetScalarRange(scalarsMin, scalarsMax); } } void mitk::GizmoMapper2D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer /*= nullptr*/, bool /*= false*/) { node->SetProperty("color", ColorProperty::New(0.3, 0.3, 0.3)); // a little lighter than the // "plane widgets" of // QmitkStdMultiWidget node->SetProperty("scalar visibility", BoolProperty::New(true), renderer); node->SetProperty("ScalarsRangeMinimum", DoubleProperty::New(0), renderer); node->SetProperty("ScalarsRangeMaximum", DoubleProperty::New((int)Gizmo::NoHandle), renderer); double colorMoveFreely[] = {1, 0, 0, 1}; // RGBA double colorAxisX[] = {0.753, 0, 0, 1}; // colors copied from QmitkStdMultiWidget to double colorAxisY[] = {0, 0.69, 0, 1}; // look alike double colorAxisZ[] = {0, 0.502, 1, 1}; double colorInactive[] = {0.7, 0.7, 0.7, 1}; // build a nice color table vtkSmartPointer lut = vtkSmartPointer::New(); lut->SetNumberOfTableValues((int)Gizmo::NoHandle + 1); lut->SetTableRange(0, (int)Gizmo::NoHandle); lut->SetTableValue(Gizmo::MoveFreely, colorMoveFreely); lut->SetTableValue(Gizmo::MoveAlongAxisX, colorAxisX); lut->SetTableValue(Gizmo::MoveAlongAxisY, colorAxisY); lut->SetTableValue(Gizmo::MoveAlongAxisZ, colorAxisZ); lut->SetTableValue(Gizmo::RotateAroundAxisX, colorAxisX); lut->SetTableValue(Gizmo::RotateAroundAxisY, colorAxisY); lut->SetTableValue(Gizmo::RotateAroundAxisZ, colorAxisZ); lut->SetTableValue(Gizmo::ScaleX, colorAxisX); lut->SetTableValue(Gizmo::ScaleY, colorAxisY); lut->SetTableValue(Gizmo::ScaleZ, colorAxisZ); lut->SetTableValue(Gizmo::NoHandle, colorInactive); mitk::LookupTable::Pointer mlut = mitk::LookupTable::New(); mlut->SetVtkLookupTable(lut); mitk::LookupTableProperty::Pointer lutProp = mitk::LookupTableProperty::New(); lutProp->SetLookupTable(mlut); node->SetProperty("LookupTable", lutProp, renderer); node->SetProperty("helper object", BoolProperty::New(true), renderer); node->SetProperty("visible", BoolProperty::New(true), renderer); node->SetProperty("show in 2D", BoolProperty::New(true), renderer); // no "show in 3D" because this would require a specialized mapper for gizmos in 3D } diff --git a/Modules/Gizmo/src/mitkGizmoMapper2D.h b/Modules/Gizmo/src/mitkGizmoMapper2D.h index 14b4f2834e..83b5e6b59a 100644 --- a/Modules/Gizmo/src/mitkGizmoMapper2D.h +++ b/Modules/Gizmo/src/mitkGizmoMapper2D.h @@ -1,97 +1,97 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkGizmoMapper2D_h #define mitkGizmoMapper2D_h #include -#include +#include namespace mitk { // forward declaration class Gizmo; //! 2D Mapper for mitk::Gimzo. //! //! Paints a similar representation as for 2D (see mitk::Gizmo itself). //! The three axes of the manipulated object are visualized. They are //! pickable and will report "move along axis" or "scale" when clicked //! at the arrow shafts or the arrow tips. //! //! For usability, we removed the circles for rotation because they //! would most often coincide with the arrows, thus distinction is //! complicated. class GizmoMapper2D : public mitk::VtkMapper { public: mitkClassMacro(GizmoMapper2D, VtkMapper); itkFactorylessNewMacro(Self); itkCloneMacro(Self); //! Provides given node with a set of default properties. //! //! \param node The DataNode to decorate with properties. //! \param renderer When not nullptr, generate specific properties for given renderer //! \param overwrite Whether already existing properties shall be overwritten. static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); //! Return the vtkProp that represents the "rendering result". vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override { return m_LSH.GetLocalStorage(renderer)->m_Actor; } //! "Resets" the mapper, setting its result to invisible. void ResetMapper(mitk::BaseRenderer *renderer) override; //! Return the internal vtkPolyData for given renderer. //! This serves for picking by the associated interactor class. vtkPolyData *GetVtkPolyData(mitk::BaseRenderer *renderer); private: //! Provide the mapping input as a specific RawMesh_C const Gizmo *GetInput(); //! Update the vtkProp, i.e. the contours of a slice through our RawMesh_C. virtual void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; //! Apply visual properties void ApplyVisualProperties(BaseRenderer *renderer); //! (RenderWindow) Instance specific data. class LocalStorage : public Mapper::BaseLocalStorage { public: //! The overall rendering result. vtkSmartPointer m_Actor; //! The mapper of the resulting vtkPolyData //! (3D polygons for 3D mapper, 2D contours for 2D mapper) - vtkSmartPointer m_VtkPolyDataMapper; + vtkSmartPointer m_VtkPolyDataMapper; //! Last time this storage has been updated. itk::TimeStamp m_LastUpdateTime; LocalStorage(); }; //! (RenderWindow) Instance specific data. LocalStorageHandler m_LSH; }; } // namespace #endif diff --git a/Modules/IOExt/Internal/mitkIOExtObjectFactory.cpp b/Modules/IOExt/Internal/mitkIOExtObjectFactory.cpp index 1913da91dc..c5871d1a1a 100644 --- a/Modules/IOExt/Internal/mitkIOExtObjectFactory.cpp +++ b/Modules/IOExt/Internal/mitkIOExtObjectFactory.cpp @@ -1,184 +1,184 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkIOExtObjectFactory.h" #include "mitkCoreObjectFactory.h" #include "mitkParRecFileIOFactory.h" //#include "mitkObjFileIOFactory.h" #include "mitkStlVolumeTimeSeriesIOFactory.h" #include "mitkVtkVolumeTimeSeriesIOFactory.h" #include "mitkUnstructuredGridVtkWriter.h" #include "mitkUnstructuredGridVtkWriterFactory.h" -#include "mitkGPUVolumeMapper3D.h" +#include "mitkVolumeMapperVtkSmart3D.h" #include "mitkMesh.h" #include "mitkMeshMapper2D.h" #include "mitkMeshVtkMapper3D.h" #include "mitkUnstructuredGridMapper2D.h" #include "mitkUnstructuredGridVtkMapper3D.h" #include "mitkVtkGLMapperWrapper.h" #include #include #include mitk::IOExtObjectFactory::IOExtObjectFactory() : CoreObjectFactoryBase(), m_ParRecFileIOFactory(ParRecFileIOFactory::New().GetPointer()) //, m_ObjFileIOFactory(ObjFileIOFactory::New().GetPointer()) , m_StlVolumeTimeSeriesIOFactory(StlVolumeTimeSeriesIOFactory::New().GetPointer()), m_VtkVolumeTimeSeriesIOFactory(VtkVolumeTimeSeriesIOFactory::New().GetPointer()), m_UnstructuredGridVtkWriterFactory(UnstructuredGridVtkWriterFactory::New().GetPointer()) { static bool alreadyDone = false; if (!alreadyDone) { MITK_DEBUG << "IOExtObjectFactory c'tor" << std::endl; itk::ObjectFactoryBase::RegisterFactory(m_ParRecFileIOFactory); itk::ObjectFactoryBase::RegisterFactory(m_StlVolumeTimeSeriesIOFactory); itk::ObjectFactoryBase::RegisterFactory(m_VtkVolumeTimeSeriesIOFactory); itk::ObjectFactoryBase::RegisterFactory(m_UnstructuredGridVtkWriterFactory); m_FileWriters.push_back(mitk::UnstructuredGridVtkWriter::New().GetPointer()); m_FileWriters.push_back(mitk::UnstructuredGridVtkWriter::New().GetPointer()); m_FileWriters.push_back(mitk::UnstructuredGridVtkWriter::New().GetPointer()); CreateFileExtensionsMap(); alreadyDone = true; } } mitk::IOExtObjectFactory::~IOExtObjectFactory() { itk::ObjectFactoryBase::UnRegisterFactory(m_ParRecFileIOFactory); itk::ObjectFactoryBase::UnRegisterFactory(m_StlVolumeTimeSeriesIOFactory); itk::ObjectFactoryBase::UnRegisterFactory(m_VtkVolumeTimeSeriesIOFactory); itk::ObjectFactoryBase::UnRegisterFactory(m_UnstructuredGridVtkWriterFactory); } mitk::Mapper::Pointer mitk::IOExtObjectFactory::CreateMapper(mitk::DataNode *node, MapperSlotId id) { mitk::Mapper::Pointer newMapper = nullptr; mitk::BaseData *data = node->GetData(); if (id == mitk::BaseRenderer::Standard2D) { if ((dynamic_cast(data) != nullptr)) { newMapper = mitk::MeshMapper2D::New(); newMapper->SetDataNode(node); } else if ((dynamic_cast(data) != nullptr)) { newMapper = mitk::VtkGLMapperWrapper::New(mitk::UnstructuredGridMapper2D::New().GetPointer()); newMapper->SetDataNode(node); } } else if (id == mitk::BaseRenderer::Standard3D) { if ((dynamic_cast(data) != nullptr)) { - newMapper = mitk::GPUVolumeMapper3D::New(); + newMapper = mitk::VolumeMapperVtkSmart3D::New(); newMapper->SetDataNode(node); } else if ((dynamic_cast(data) != nullptr)) { newMapper = mitk::MeshVtkMapper3D::New(); newMapper->SetDataNode(node); } else if ((dynamic_cast(data) != nullptr)) { newMapper = mitk::UnstructuredGridVtkMapper3D::New(); newMapper->SetDataNode(node); } } return newMapper; } void mitk::IOExtObjectFactory::SetDefaultProperties(mitk::DataNode *node) { if (node == nullptr) return; mitk::DataNode::Pointer nodePointer = node; mitk::Image::Pointer image = dynamic_cast(node->GetData()); if (image.IsNotNull() && image->IsInitialized()) { - mitk::GPUVolumeMapper3D::SetDefaultProperties(node); + mitk::VolumeMapperVtkSmart3D::SetDefaultProperties(node); } if (dynamic_cast(node->GetData())) { mitk::UnstructuredGridVtkMapper3D::SetDefaultProperties(node); } } const char *mitk::IOExtObjectFactory::GetFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_FileExtensionsMap, fileExtension); return fileExtension.c_str(); } mitk::CoreObjectFactoryBase::MultimapType mitk::IOExtObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } mitk::CoreObjectFactoryBase::MultimapType mitk::IOExtObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } void mitk::IOExtObjectFactory::CreateFileExtensionsMap() { m_FileExtensionsMap.insert(std::pair("*.vtu", "VTK Unstructured Grid")); m_FileExtensionsMap.insert(std::pair("*.vtk", "VTK Unstructured Grid")); m_FileExtensionsMap.insert(std::pair("*.pvtu", "VTK Unstructured Grid")); m_SaveFileExtensionsMap.insert(std::pair("*.pvtu", "VTK Parallel XML Unstructured Grid")); m_SaveFileExtensionsMap.insert(std::pair("*.vtu", "VTK XML Unstructured Grid")); m_SaveFileExtensionsMap.insert(std::pair("*.vtk", "VTK Legacy Unstructured Grid")); } const char *mitk::IOExtObjectFactory::GetSaveFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); return fileExtension.c_str(); } struct RegisterIOExtObjectFactory { RegisterIOExtObjectFactory() : m_Factory(mitk::IOExtObjectFactory::New()) { mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(m_Factory); } ~RegisterIOExtObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory(m_Factory); } mitk::IOExtObjectFactory::Pointer m_Factory; }; static RegisterIOExtObjectFactory registerIOExtObjectFactory; diff --git a/Modules/LegacyGL/mitkGL.h b/Modules/LegacyGL/mitkGL.h index db372315ee..fc1398efc9 100644 --- a/Modules/LegacyGL/mitkGL.h +++ b/Modules/LegacyGL/mitkGL.h @@ -1,30 +1,31 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKGL_H_HEADER_INCLUDED_C1C53722 #define MITKGL_H_HEADER_INCLUDED_C1C53722 #ifdef WIN32 #include #endif #ifndef __APPLE__ -#include "GL/gl.h" +//#include "GL/gl.h" +#include "vtk_glew.h" #else #include "OpenGL/gl.h" #endif #endif /* MITKGL_H_HEADER_INCLUDED_C1C53722 */ diff --git a/Modules/MapperExt/files.cmake b/Modules/MapperExt/files.cmake index 6a072e68b7..3ec5ef80f6 100644 --- a/Modules/MapperExt/files.cmake +++ b/Modules/MapperExt/files.cmake @@ -1,21 +1,20 @@ file(GLOB_RECURSE H_FILES RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_SOURCE_DIR}/include/*") set(CPP_FILES mitkEnhancedPointSetVtkMapper3D.cpp mitkGPUVolumeMapper3D.cpp mitkMeshMapper2D.cpp mitkMeshVtkMapper3D.cpp mitkSplineVtkMapper3D.cpp mitkUnstructuredGridMapper2D.cpp mitkUnstructuredGridVtkMapper3D.cpp mitkVectorImageMapper2D.cpp + mitkVolumeMapperVtkSmart3D.cpp vtkMaskedGlyph2D.cpp vtkMaskedGlyph3D.cpp vtkMitkGPUVolumeRayCastMapper.cpp - vtkMitkOpenGLVolumeTextureMapper3D.cpp - vtkMitkVolumeTextureMapper3D.cpp vtkUnstructuredGridMapper.cpp vtkPointSetSlicer.cxx ) diff --git a/Modules/MapperExt/include/mitkGPUVolumeMapper3D.h b/Modules/MapperExt/include/mitkGPUVolumeMapper3D.h index 69067f71a8..07845fc4fa 100644 --- a/Modules/MapperExt/include/mitkGPUVolumeMapper3D.h +++ b/Modules/MapperExt/include/mitkGPUVolumeMapper3D.h @@ -1,190 +1,164 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITKGPUVOLUMEMAPPER3D_H_HEADER_INCLUDED #define MITKGPUVOLUMEMAPPER3D_H_HEADER_INCLUDED // MITK #include "MitkMapperExtExports.h" #include "mitkBaseRenderer.h" #include "mitkCommon.h" #include "mitkImage.h" #include "mitkVtkMapper.h" -#include "vtkMitkVolumeTextureMapper3D.h" // VTK #include #include #include #include #include #include -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) - #include "vtkMitkGPUVolumeRayCastMapper.h" -#endif - namespace mitk { /************************************************************************/ /* Properties that influence the mapper are: * * - \b "level window": for the level window of the volume data * - \b "LookupTable" : for the lookup table of the volume data * - \b "TransferFunction" (mitk::TransferFunctionProperty): for the used transfer function of the volume data ************************************************************************/ //##Documentation //## @brief Vtk-based mapper for VolumeData //## //## @ingroup Mapper class MITKMAPPEREXT_EXPORT GPUVolumeMapper3D : public VtkMapper { public: mitkClassMacro(GPUVolumeMapper3D, VtkMapper); itkFactorylessNewMacro(Self) itkCloneMacro(Self) virtual const mitk::Image *GetInput(); virtual vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; virtual void ApplyProperties(vtkActor *actor, mitk::BaseRenderer *renderer) override; static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); /** Returns true if this Mapper currently allows for Level-of-Detail rendering. * This reflects whether this Mapper currently invokes StartEvent, EndEvent, and * ProgressEvent on BaseRenderer. */ virtual bool IsLODEnabled(BaseRenderer *renderer = nullptr) const override; bool IsMIPEnabled(BaseRenderer *renderer = nullptr); bool IsGPUEnabled(BaseRenderer *renderer = nullptr); bool IsRAYEnabled(BaseRenderer *renderer = nullptr); virtual void MitkRenderVolumetricGeometry(mitk::BaseRenderer *renderer) override; protected: GPUVolumeMapper3D(); virtual ~GPUVolumeMapper3D(); bool IsRenderable(mitk::BaseRenderer *renderer); void InitCommon(); void DeinitCommon(); void InitCPU(mitk::BaseRenderer *renderer); void DeinitCPU(mitk::BaseRenderer *renderer); void GenerateDataCPU(mitk::BaseRenderer *renderer); bool InitGPU(mitk::BaseRenderer *renderer); - void DeinitGPU(mitk::BaseRenderer *renderer); - void GenerateDataGPU(mitk::BaseRenderer *renderer); - -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) + void DeinitGPU(mitk::BaseRenderer *); + void GenerateDataGPU(mitk::BaseRenderer *); bool InitRAY(mitk::BaseRenderer *renderer); void DeinitRAY(mitk::BaseRenderer *renderer); void GenerateDataRAY(mitk::BaseRenderer *renderer); -#endif - void InitVtkMapper(mitk::BaseRenderer *renderer); virtual void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; void CreateDefaultTransferFunctions(); void UpdateTransferFunctions(mitk::BaseRenderer *renderer); vtkSmartPointer m_Volumenullptr; bool m_commonInitialized; vtkSmartPointer m_UnitSpacingImageFilter; vtkSmartPointer m_DefaultOpacityTransferFunction; vtkSmartPointer m_DefaultGradientTransferFunction; vtkSmartPointer m_DefaultColorTransferFunction; vtkSmartPointer m_BinaryOpacityTransferFunction; vtkSmartPointer m_BinaryGradientTransferFunction; vtkSmartPointer m_BinaryColorTransferFunction; class LocalStorage : public mitk::Mapper::BaseLocalStorage { public: // NO SMARTPOINTER HERE vtkRenderWindow *m_VtkRenderWindow; bool m_cpuInitialized; vtkSmartPointer m_VolumeCPU; vtkSmartPointer m_MapperCPU; vtkSmartPointer m_VolumePropertyCPU; bool m_gpuSupported; bool m_gpuInitialized; vtkSmartPointer m_VolumeGPU; - vtkSmartPointer m_MapperGPU; vtkSmartPointer m_VolumePropertyGPU; -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) - bool m_raySupported; bool m_rayInitialized; vtkSmartPointer m_VolumeRAY; vtkSmartPointer m_MapperRAY; vtkSmartPointer m_VolumePropertyRAY; -#endif - LocalStorage() { m_VtkRenderWindow = 0; m_cpuInitialized = false; m_gpuInitialized = false; m_gpuSupported = true; // assume initially gpu slicing is supported -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) m_rayInitialized = false; m_raySupported = true; // assume initially gpu raycasting is supported -#endif } ~LocalStorage() { if (m_cpuInitialized && m_MapperCPU && m_VtkRenderWindow) m_MapperCPU->ReleaseGraphicsResources(m_VtkRenderWindow); - if (m_gpuInitialized && m_MapperGPU && m_VtkRenderWindow) - m_MapperGPU->ReleaseGraphicsResources(m_VtkRenderWindow); - -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) if (m_rayInitialized && m_MapperRAY && m_VtkRenderWindow) m_MapperRAY->ReleaseGraphicsResources(m_VtkRenderWindow); -#endif } }; mitk::LocalStorageHandler m_LSH; }; } // namespace mitk #endif /* MITKVOLUMEDATAVTKMAPPER3D_H_HEADER_INCLUDED */ diff --git a/Modules/MapperExt/include/mitkVolumeMapperVtkSmart3D.h b/Modules/MapperExt/include/mitkVolumeMapperVtkSmart3D.h new file mode 100644 index 0000000000..46af198c5b --- /dev/null +++ b/Modules/MapperExt/include/mitkVolumeMapperVtkSmart3D.h @@ -0,0 +1,75 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#ifndef MITKVTKSMARTVOLUMEMAPPER_H_HEADER_INCLUDED +#define MITKVTKSMARTVOLUMEMAPPER_H_HEADER_INCLUDED + +// MITK +#include "MitkMapperExtExports.h" +#include "mitkBaseRenderer.h" +#include "mitkCommon.h" +#include "mitkImage.h" +#include "mitkVtkMapper.h" + +// VTK +#include +#include +#include +#include +#include +#include + +namespace mitk +{ + + //##Documentation + //## @brief Vtk-based mapper for VolumeData + //## + //## @ingroup Mapper + class MITKMAPPEREXT_EXPORT VolumeMapperVtkSmart3D : public VtkMapper + { + public: + mitkClassMacro(VolumeMapperVtkSmart3D, VtkMapper); + + itkFactorylessNewMacro(Self) itkCloneMacro(Self) + + virtual vtkProp *GetVtkProp(mitk::BaseRenderer *renderer) override; + + virtual void ApplyProperties(vtkActor *actor, mitk::BaseRenderer *renderer) override; + static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); + + protected: + VolumeMapperVtkSmart3D(); + virtual ~VolumeMapperVtkSmart3D(); + + virtual void GenerateDataForRenderer(mitk::BaseRenderer *renderer) override; + + void createMapper(vtkImageData*); + void createVolume(); + void createVolumeProperty(); + vtkImageData* GetInputImage(); + + vtkSmartPointer m_Volume; + vtkSmartPointer m_SmartVolumeMapper; + vtkSmartPointer m_VolumeProperty; + + void UpdateTransferFunctions(mitk::BaseRenderer *renderer); + void UpdateRenderMode(mitk::BaseRenderer *renderer); + }; + +} // namespace mitk + +#endif /* MITKVTKSMARTVOLUMEMAPPER_H_HEADER_INCLUDED */ diff --git a/Modules/MapperExt/include/vtkMitkGPUVolumeRayCastMapper.h b/Modules/MapperExt/include/vtkMitkGPUVolumeRayCastMapper.h index cf37c3bb21..a7a6031c65 100644 --- a/Modules/MapperExt/include/vtkMitkGPUVolumeRayCastMapper.h +++ b/Modules/MapperExt/include/vtkMitkGPUVolumeRayCastMapper.h @@ -1,299 +1,294 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper.h,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .NAME vtkMitkGPUVolumeRayCastMapper - Ray casting performed on the GPU. // .SECTION Description // vtkMitkGPUVolumeRayCastMapper is a volume mapper that performs ray casting on // the GPU using fragment programs. // #ifndef __vtkMitkGPUVolumeRayCastMapper_h #define __vtkMitkGPUVolumeRayCastMapper_h #include "MitkMapperExtExports.h" #include "mitkCommon.h" #include "vtkVersionMacros.h" #include "vtkVolumeMapper.h" -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) - class vtkVolumeProperty; class vtkRenderWindow; // class vtkKWAMRVolumeMapper; // friend class. class MITKMAPPEREXT_EXPORT vtkMitkGPUVolumeRayCastMapper : public vtkVolumeMapper { public: vtkTypeMacro(vtkMitkGPUVolumeRayCastMapper, vtkVolumeMapper); void PrintSelf(ostream &os, vtkIndent indent) override; // Description: // If AutoAdjustSampleDistances is on, the the ImageSampleDistance // will be varied to achieve the allocated render time of this // prop (controlled by the desired update rate and any culling in // use). vtkSetClampMacro(AutoAdjustSampleDistances, int, 0, 1); vtkGetMacro(AutoAdjustSampleDistances, int); vtkBooleanMacro(AutoAdjustSampleDistances, int); // Description: // Set/Get the distance between samples used for rendering // when AutoAdjustSampleDistances is off, or when this mapper // has more than 1 second allocated to it for rendering. // Initial value is 1.0. vtkSetMacro(SampleDistance, float); vtkGetMacro(SampleDistance, float); // Description: // Sampling distance in the XY image dimensions. Default value of 1 meaning // 1 ray cast per pixel. If set to 0.5, 4 rays will be cast per pixel. If // set to 2.0, 1 ray will be cast for every 4 (2 by 2) pixels. This value // will be adjusted to meet a desired frame rate when AutoAdjustSampleDistances // is on. vtkSetClampMacro(ImageSampleDistance, float, 0.1f, 100.0f); vtkGetMacro(ImageSampleDistance, float); // Description: // This is the minimum image sample distance allow when the image // sample distance is being automatically adjusted. vtkSetClampMacro(MinimumImageSampleDistance, float, 0.1f, 100.0f); vtkGetMacro(MinimumImageSampleDistance, float); // Description: // This is the maximum image sample distance allow when the image // sample distance is being automatically adjusted. vtkSetClampMacro(MaximumImageSampleDistance, float, 0.1f, 100.0f); vtkGetMacro(MaximumImageSampleDistance, float); // Description: // Set/Get the window / level applied to the final color. // This allows brightness / contrast adjustments on the // final image. // window is the width of the window. // level is the center of the window. // Initial window value is 1.0 // Initial level value is 0.5 // window cannot be null but can be negative, this way // values will be reversed. // |window| can be larger than 1.0 // level can be any real value. vtkSetMacro(FinalColorWindow, float); vtkGetMacro(FinalColorWindow, float); vtkSetMacro(FinalColorLevel, float); vtkGetMacro(FinalColorLevel, float); // Description: // Maximum size of the 3D texture in GPU memory. // Will default to the size computed from the graphics // card. Can be adjusted by the user. vtkSetMacro(MaxMemoryInBytes, vtkIdType); vtkGetMacro(MaxMemoryInBytes, vtkIdType); // Description: // Maximum fraction of the MaxMemoryInBytes that should // be used to hold the texture. Valid values are 0.1 to // 1.0. vtkSetClampMacro(MaxMemoryFraction, float, 0.1f, 1.0f); vtkGetMacro(MaxMemoryFraction, float); // Description: // Tells if the mapper will report intermediate progress. // Initial value is true. As the progress works with a GL blocking // call (glFinish()), this can be useful for huge dataset but can // slow down rendering of small dataset. It should be set to true // for big dataset or complex shading and streaming but to false for // small datasets. vtkSetMacro(ReportProgress, bool); vtkGetMacro(ReportProgress, bool); // Description: // Based on hardware and properties, we may or may not be able to // render using 3D texture mapping. This indicates if 3D texture // mapping is supported by the hardware, and if the other extensions // necessary to support the specific properties are available. virtual int IsRenderSupported(vtkRenderWindow *vtkNotUsed(window), vtkVolumeProperty *vtkNotUsed(property)) { return 0; } void CreateCanonicalView(vtkRenderer *ren, vtkVolume *volume, vtkImageData *image, int blend_mode, double viewDirection[3], double viewUp[3]); void SetMaskInput(vtkImageData *mask); vtkGetObjectMacro(MaskInput, vtkImageData); // Description: // Tells how much mask color transfer function is used compared to the // standard color transfer function when the mask is true. // 0.0 means only standard color transfer function. // 1.0 means only mask color tranfer function. // Initial value is 1.0. vtkSetClampMacro(MaskBlendFactor, float, 0.0f, 1.0f); vtkGetMacro(MaskBlendFactor, float); // BTX // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // Initialize rendering for this volume. void Render(vtkRenderer *, vtkVolume *) override; // Description: // Handled in the subclass - the actual render method // \pre input is up-to-date. virtual void GPURender(vtkRenderer *, vtkVolume *) {} // Description: // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE // Release any graphics resources that are being consumed by this mapper. // The parameter window could be used to determine which graphic // resources to release. // \deprecatedSince{2013_12} DEPRECATED(void ReleaseGraphicsResources(vtkWindow *) override){}; // Description: // Return how much the dataset has to be reduced in each dimension to // fit on the GPU. If the value is 1.0, there is no need to reduce the // dataset. // \pre the calling thread has a current OpenGL context. // \pre mapper_supported: IsRenderSupported(renderer->GetRenderWindow(),0) // The computation is based on hardware limits (3D texture indexable size) // and MaxMemoryInBytes. // \post valid_i_ratio: ratio[0]>0 && ratio[0]<=1.0 // \post valid_j_ratio: ratio[1]>0 && ratio[1]<=1.0 // \post valid_k_ratio: ratio[2]>0 && ratio[2]<=1.0 virtual void GetReductionRatio(double ratio[3]) = 0; // ETX protected: vtkMitkGPUVolumeRayCastMapper(); ~vtkMitkGPUVolumeRayCastMapper(); // Check to see that the render will be OK int ValidateRender(vtkRenderer *, vtkVolume *); // Special version of render called during the creation // of a canonical view. void CanonicalViewRender(vtkRenderer *, vtkVolume *); // Methods called by the AMR Volume Mapper. virtual void PreRender(vtkRenderer *ren, vtkVolume *vol, double datasetBounds[6], double scalarRange[2], int numberOfScalarComponents, unsigned int numberOfLevels) = 0; // \pre input is up-to-date virtual void RenderBlock(vtkRenderer *ren, vtkVolume *vol, unsigned int level) = 0; virtual void PostRender(vtkRenderer *ren, int numberOfScalarComponents) = 0; // Description: // Called by the AMR Volume Mapper. // Set the flag that tells if the scalars are on point data (0) or // cell data (1). void SetCellFlag(int cellFlag); // The distance between sample points along the ray float SampleDistance; float ImageSampleDistance; float MinimumImageSampleDistance; float MaximumImageSampleDistance; int AutoAdjustSampleDistances; int SmallVolumeRender; double BigTimeToDraw; double SmallTimeToDraw; float FinalColorWindow; float FinalColorLevel; vtkIdType MaxMemoryInBytes; float MaxMemoryFraction; // 1 if we are generating the canonical image, 0 otherwise int GeneratingCanonicalView; vtkImageData *CanonicalViewImageData; // Description: // Set the mapper in AMR Mode or not. Initial value is false. // Called only by the vtkKWAMRVolumeMapper vtkSetClampMacro(AMRMode, int, 0, 1); vtkGetMacro(AMRMode, int); vtkBooleanMacro(AMRMode, int); int AMRMode; int CellFlag; // point data or cell data (or field data, not handled) ? // Description: // Compute the cropping planes clipped by the bounds of the volume. // The result is put into this->ClippedCroppingRegionPlanes. // NOTE: IT WILL BE MOVED UP TO vtkVolumeMapper after bullet proof usage // in this mapper. Other subclasses will use the ClippedCroppingRegionsPlanes // members instead of CroppingRegionPlanes. // \pre volume_exists: this->GetInput()!=0 // \pre valid_cropping: this->Cropping && // this->CroppingRegionPlanes[0]CroppingRegionPlanes[1] && // this->CroppingRegionPlanes[2]CroppingRegionPlanes[3] && // this->CroppingRegionPlanes[4]CroppingRegionPlanes[5]) virtual void ClipCroppingRegionPlanes(); double ClippedCroppingRegionPlanes[6]; bool ReportProgress; vtkImageData *MaskInput; float MaskBlendFactor; vtkGetObjectMacro(TransformedInput, vtkImageData); void SetTransformedInput(vtkImageData *); vtkImageData *TransformedInput; // Description: // This is needed only to check if the input data has been changed since the last // Render() call. vtkImageData *LastInput; private: vtkMitkGPUVolumeRayCastMapper(const vtkMitkGPUVolumeRayCastMapper &); // Not implemented. void operator=(const vtkMitkGPUVolumeRayCastMapper &); // Not implemented. }; #endif - -#endif diff --git a/Modules/MapperExt/include/vtkMitkOpenGLVolumeTextureMapper3D.h b/Modules/MapperExt/include/vtkMitkOpenGLVolumeTextureMapper3D.h deleted file mode 100644 index e06844a66f..0000000000 --- a/Modules/MapperExt/include/vtkMitkOpenGLVolumeTextureMapper3D.h +++ /dev/null @@ -1,148 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -// .NAME vtkMitkOpenGLVolumeTextureMapper3D - concrete implementation of 3D volume texture mapping - -// .SECTION Description -// vtkMitkOpenGLVolumeTextureMapper3D renders a volume using 3D texture mapping. -// See vtkMitkVolumeTextureMapper3D for full description. - -// .SECTION see also -// vtkMitkVolumeTextureMapper3D vtkVolumeMapper - -#ifndef __vtkMitkOpenGLVolumeTextureMapper3D_h -#define __vtkMitkOpenGLVolumeTextureMapper3D_h - -#include "MitkMapperExtExports.h" -#include "mitkBaseRenderer.h" -#include "vtkMitkVolumeTextureMapper3D.h" - -#ifndef VTK_IMPLEMENT_MESA_CXX -#include "vtkOpenGL.h" // GLfloat type is used in some method signatures. -#endif - -class vtkRenderWindow; -class vtkVolumeProperty; - -#include "mitkCommon.h" - -class MITKMAPPEREXT_EXPORT vtkMitkOpenGLVolumeTextureMapper3D : public vtkMitkVolumeTextureMapper3D -{ -public: - vtkTypeMacro(vtkMitkOpenGLVolumeTextureMapper3D, vtkMitkVolumeTextureMapper3D); - void PrintSelf(ostream &os, vtkIndent indent) override; - - static vtkMitkOpenGLVolumeTextureMapper3D *New(); - - // Description: - // Is hardware rendering supported? No if the input data is - // more than one independent component, or if the hardware does - // not support the required extensions - // int IsRenderSupported(vtkVolumeProperty *); - int IsRenderSupported(vtkRenderer *ren, vtkVolumeProperty *) override; - - // BTX - - // Description: - // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE - // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS - // Render the volume - virtual void Render(vtkRenderer *ren, vtkVolume *vol) override; - - // ETX - - // Desciption: - // Initialize when we go to render, or go to answer the - // IsRenderSupported question. Don't call unless we have - // a valid OpenGL context! - vtkGetMacro(Initialized, int); - - // Description: - // Release any graphics resources that are being consumed by this texture. - // The parameter window could be used to determine which graphic - // resources to release. - // deprecatedSince{2013_12} Use ReleaseGraphicsResources(mitk::BaseRenderer* renderer) instead - DEPRECATED(void ReleaseGraphicsResources(vtkWindow *) override); - - // Description: - // Release any graphics resources that are being consumed by this texture. - // The parameter renderer could be used to determine which graphic - // resources to release. - void ReleaseGraphicsResources(mitk::BaseRenderer *renderer); - -protected: - vtkMitkOpenGLVolumeTextureMapper3D(); - ~vtkMitkOpenGLVolumeTextureMapper3D(); - - bool RenderPossible; - - // BTX - - void GetLightInformation(vtkRenderer *ren, - vtkVolume *vol, - GLfloat lightDirection[2][4], - GLfloat lightDiffuseColor[2][4], - GLfloat lightSpecularColor[2][4], - GLfloat halfwayVector[2][4], - GLfloat *ambient); - // ETX - - int Initialized; - GLuint Volume1Index; - GLuint Volume2Index; - GLuint Volume3Index; - GLuint ColorLookupIndex; - GLuint AlphaLookupIndex; - - GLuint prgOneComponentShade; - GLuint prgRGBAShade; - - vtkRenderWindow *RenderWindow; - - bool SupportsCompressedTexture; - - // void Initialize(); - void Initialize(vtkRenderer *r); - - virtual void RenderFP(vtkRenderer *ren, vtkVolume *vol); - - void SetupOneIndependentTextures(vtkRenderer *ren, vtkVolume *vol); - void RenderOneIndependentShadeFP(vtkRenderer *ren, vtkVolume *vol); - - void SetupRGBATextures(vtkRenderer *ren, vtkVolume *vol); - void RenderRGBAShadeFP(vtkRenderer *ren, vtkVolume *vol); - - void DeleteTextureIndex(GLuint *index); - void CreateTextureIndex(GLuint *index); - - void RenderPolygons(vtkRenderer *ren, vtkVolume *vol, int stages[4]); - - void SetupProgramLocalsForShadingFP(vtkRenderer *ren, vtkVolume *vol); - - void Setup3DTextureParameters(bool linear); - - void ComputeVolumeDimensions(); - - bool UpdateVolumes(vtkVolume *); - - bool UpdateVolumesRGBA(vtkVolume *); - -private: - vtkMitkOpenGLVolumeTextureMapper3D(const vtkMitkOpenGLVolumeTextureMapper3D &); // Not implemented. - void operator=(const vtkMitkOpenGLVolumeTextureMapper3D &); // Not implemented. -}; - -#endif diff --git a/Modules/MapperExt/include/vtkMitkVolumeTextureMapper3D.h b/Modules/MapperExt/include/vtkMitkVolumeTextureMapper3D.h deleted file mode 100644 index 7fe2ded61a..0000000000 --- a/Modules/MapperExt/include/vtkMitkVolumeTextureMapper3D.h +++ /dev/null @@ -1,223 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -// .NAME vtkMitkVolumeTextureMapper3D - volume render with 3D texture mapping - -// .SECTION Description -// vtkMitkVolumeTextureMapper3D renders a volume using 3D texture mapping. -// This class is actually an abstract superclass - with all the actual -// work done by vtkMitkOpenGLVolumeTextureMapper3D. -// -// This mappers currently supports: -// -// - any data type as input -// - one component, or two or four non-independent components -// - composite blending -// - intermixed opaque geometry -// - multiple volumes can be rendered if they can -// be sorted into back-to-front order (use the vtkFrustumCoverageCuller) -// -// This mapper does not support: -// - more than one independent component -// - maximum intensity projection -// -// Internally, this mapper will potentially change the resolution of the -// input data. The data will be resampled to be a power of two in each -// direction, and also no greater than 128*256*256 voxels (any aspect) -// for one or two component data, or 128*128*256 voxels (any aspect) -// for four component data. The limits are currently hardcoded after -// a check using the GL_PROXY_TEXTURE3D because some graphics drivers -// were always responding "yes" to the proxy call despite not being -// able to allocate that much texture memory. -// -// Currently, calculations are computed using 8 bits per RGBA channel. -// In the future this should be expanded to handle newer boards that -// can support 15 bit float compositing. -// -// This mapper supports two main families of graphics hardware: -// nvidia and ATI. There are two different implementations of -// 3D texture mapping used - one based on nvidia's GL_NV_texture_shader2 -// and GL_NV_register_combiners2 extension, and one based on -// ATI's GL_ATI_fragment_shader (supported also by some nvidia boards) -// To use this class in an application that will run on various -// hardware configurations, you should have a back-up volume rendering -// method. You should create a vtkMitkVolumeTextureMapper3D, assign its -// input, make sure you have a current OpenGL context (you've rendered -// at least once), then call IsRenderSupported with a vtkVolumeProperty -// as an argument. This method will return 0 if the input has more than -// one independent component, or if the graphics hardware does not -// support the set of required extensions for using at least one of -// the two implemented methods (nvidia or ati) -// -// .SECTION Thanks -// Thanks to Alexandre Gouaillard at the Megason Lab, Department of Systems -// Biology, Harvard Medical School -// https://wiki.med.harvard.edu/SysBio/Megason/ -// for the idea and initial patch to speed-up rendering with compressed -// textures. -// -// .SECTION see also -// vtkVolumeMapper - -#ifndef __vtkMitkVolumeTextureMapper3D_h -#define __vtkMitkVolumeTextureMapper3D_h - -#include "MitkMapperExtExports.h" -#include "vtkVolumeMapper.h" - -class vtkImageData; -class vtkColorTransferFunction; -class vtkPiecewiseFunction; -class vtkVolumeProperty; - -#include "mitkCommon.h" - -class MITKMAPPEREXT_EXPORT vtkMitkVolumeTextureMapper3D : public vtkVolumeMapper -{ -public: - vtkTypeMacro(vtkMitkVolumeTextureMapper3D, vtkVolumeMapper); - void PrintSelf(ostream &os, vtkIndent indent) override; - - // static vtkMitkVolumeTextureMapper3D *New(); //VTK6_TODO - - // Description: - // The distance at which to space sampling planes. This - // may not be honored for interactive renders. An interactive - // render is defined as one that has less than 1 second of - // allocated render time. - vtkSetMacro(SampleDistance, float); - vtkGetMacro(SampleDistance, float); - - // Description: - // These are the dimensions of the 3D texture - vtkGetVectorMacro(VolumeDimensions, int, 3); - - // Description: - // This is the spacing of the 3D texture - vtkGetVectorMacro(VolumeSpacing, float, 3); - - // Description: - // Based on hardware and properties, we may or may not be able to - // render using 3D texture mapping. This indicates if 3D texture - // mapping is supported by the hardware, and if the other extensions - // necessary to support the specific properties are available. - virtual int IsRenderSupported(vtkRenderer *, vtkVolumeProperty *) = 0; - - // Description: - // Allow access to the number of polygons used for the - // rendering. - vtkGetMacro(NumberOfPolygons, int); - - // Description: - // Allow access to the actual sample distance used to render - // the image. - vtkGetMacro(ActualSampleDistance, float); - - // BTX - - // Description: - // WARNING: INTERNAL METHOD - NOT INTENDED FOR GENERAL USE - // DO NOT USE THIS METHOD OUTSIDE OF THE RENDERING PROCESS - // Render the volume - virtual void Render(vtkRenderer *, vtkVolume *) override{}; - - // Description: - // Set/Get if the mapper use compressed textures (if supported by the - // hardware). Initial value is false. - // There are two reasons to use compressed textures: 1. rendering can be 4 - // times faster. 2. It saves some VRAM. - // There is one reason to not use compressed textures: quality may be lower - // than with uncompressed textures. - vtkSetMacro(UseCompressedTexture, bool); - vtkGetMacro(UseCompressedTexture, bool); - - void UpdateMTime(); - -protected: - vtkMitkVolumeTextureMapper3D(); - ~vtkMitkVolumeTextureMapper3D(); - - float *PolygonBuffer; - float *IntersectionBuffer; - int NumberOfPolygons; - int BufferSize; - - /* - unsigned char *Volume1; - unsigned char *Volume2; - unsigned char *Volume3; - */ - /* - int VolumeSize; - int VolumeComponents; - */ - - int VolumeDimensions[3]; - float VolumeSpacing[3]; - - float SampleDistance; - float ActualSampleDistance; - - vtkImageData *SavedTextureInput; - vtkImageData *SavedParametersInput; - - vtkColorTransferFunction *SavedRGBFunction; - vtkPiecewiseFunction *SavedGrayFunction; - vtkPiecewiseFunction *SavedScalarOpacityFunction; - vtkPiecewiseFunction *SavedGradientOpacityFunction; - int SavedColorChannels; - float SavedSampleDistance; - float SavedScalarOpacityDistance; - - unsigned char ColorLookup[65536 * 4]; - unsigned char AlphaLookup[65536]; - float TempArray1[3 * 4096]; - float TempArray2[4096]; - int ColorTableSize; - float ColorTableScale; - float ColorTableOffset; - - unsigned char DiffuseLookup[65536 * 4]; - unsigned char SpecularLookup[65536 * 4]; - - vtkTimeStamp SavedTextureMTime; - vtkTimeStamp SavedParametersMTime; - - bool UseCompressedTexture; - - bool SupportsNonPowerOfTwoTextures; - - // Description: - // For the given viewing direction, compute the set of polygons. - void ComputePolygons(vtkRenderer *ren, vtkVolume *vol, double bounds[6]); - - // Description: - // Update the internal RGBA representation of the volume. Return 1 if - // anything change, 0 if nothing changed. - int UpdateColorLookup(vtkVolume *); - - // Description: - // Impemented in subclass - check is texture size is OK. - // BTX - virtual int IsTextureSizeSupported(int vtkNotUsed(size)[3], int vtkNotUsed(components)) { return 0; } - // ETX - -private: - vtkMitkVolumeTextureMapper3D(const vtkMitkVolumeTextureMapper3D &); // Not implemented. - void operator=(const vtkMitkVolumeTextureMapper3D &); // Not implemented. -}; - -#endif diff --git a/Modules/MapperExt/include/vtkUnstructuredGridMapper.h b/Modules/MapperExt/include/vtkUnstructuredGridMapper.h index adf3eff216..12344b922b 100644 --- a/Modules/MapperExt/include/vtkUnstructuredGridMapper.h +++ b/Modules/MapperExt/include/vtkUnstructuredGridMapper.h @@ -1,87 +1,87 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef __vtkUnstructuredGridMapper_h #define __vtkUnstructuredGridMapper_h #include "MitkMapperExtExports.h" #include "mitkBaseRenderer.h" #include "mitkBoundingObject.h" #include "mitkCommon.h" #include "vtkMapper.h" class vtkPolyDataMapper; class vtkGeometryFilter; class vtkUnstructuredGrid; class MITKMAPPEREXT_EXPORT vtkUnstructuredGridMapper : public vtkMapper { public: static vtkUnstructuredGridMapper *New(); vtkTypeMacro(vtkUnstructuredGridMapper, vtkMapper); void PrintSelf(ostream &os, vtkIndent indent) override; void Render(vtkRenderer *ren, vtkActor *act) override; // Description: // Get the internal poly data mapper used to map data set to graphics system. vtkGetObjectMacro(PolyDataMapper, vtkPolyDataMapper); // Description: // Release any graphics resources that are being consumed by this mapper. // The parameter window could be used to determine which graphic // resources to release. // deprecatedSince{2013_12} Use ReleaseGraphicsResources(mitk::BaseRenderer* renderer) instead DEPRECATED(void ReleaseGraphicsResources(vtkWindow *) override); // Description: // Release any graphics resources that are being consumed by this mapper. // The parameter renderer could be used to determine which graphic // resources to release. // deprecatedSince{2013_12} Use ReleaseGraphicsResources(mitk::BaseRenderer* renderer) instead void ReleaseGraphicsResources(mitk::BaseRenderer *renderer); // Description: // Get the mtime also considering the lookup table. - unsigned long GetMTime() override; + vtkMTimeType GetMTime() override; // Description: // Set the Input of this mapper. void SetInput(vtkUnstructuredGrid *input); vtkUnstructuredGrid *GetInput(); void SetBoundingObject(mitk::BoundingObject *bo); protected: vtkUnstructuredGridMapper(); ~vtkUnstructuredGridMapper(); vtkGeometryFilter *GeometryExtractor; vtkPolyDataMapper *PolyDataMapper; mitk::BoundingObject::Pointer m_BoundingObject; virtual void ReportReferences(vtkGarbageCollector *) override; // see algorithm for more info virtual int FillInputPortInformation(int port, vtkInformation *info) override; private: vtkUnstructuredGridMapper(const vtkUnstructuredGridMapper &); // Not implemented. void operator=(const vtkUnstructuredGridMapper &); // Not implemented. }; #endif // __vtkUnstructuredGridMapper_h diff --git a/Modules/MapperExt/src/mitkGPUVolumeMapper3D.cpp b/Modules/MapperExt/src/mitkGPUVolumeMapper3D.cpp index 4db7aa4cf1..07983f107b 100644 --- a/Modules/MapperExt/src/mitkGPUVolumeMapper3D.cpp +++ b/Modules/MapperExt/src/mitkGPUVolumeMapper3D.cpp @@ -1,708 +1,592 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #define GPU_INFO MITK_INFO("mapper.vr") #define GPU_WARN MITK_WARN("mapper.vr") #define GPU_ERROR MITK_ERROR("mapper.vr") -#include -VTK_MODULE_INIT(vtkRenderingVolumeOpenGL); - #include "mitkGPUVolumeMapper3D.h" #include "mitkDataNode.h" #include "mitkColorProperty.h" #include "mitkColorProperty.h" #include "mitkLevelWindow.h" #include "mitkLevelWindowProperty.h" #include "mitkLookupTableProperty.h" #include "mitkProperties.h" #include "mitkRenderingManager.h" #include "mitkTransferFunctionInitializer.h" #include "mitkTransferFunctionProperty.h" #include "mitkVtkPropRenderer.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include -#include #include #include -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) - #include "vtkMitkGPUVolumeRayCastMapper.h" -#endif - -#include "vtkMitkOpenGLVolumeTextureMapper3D.h" #include "vtkOpenGLGPUVolumeRayCastMapper.h" const mitk::Image *mitk::GPUVolumeMapper3D::GetInput() { return static_cast(GetDataNode()->GetData()); } void mitk::GPUVolumeMapper3D::MitkRenderVolumetricGeometry(mitk::BaseRenderer *renderer) { - LocalStorage *ls = m_LSH.GetLocalStorage(renderer); - VtkMapper::MitkRenderVolumetricGeometry(renderer); - if (ls->m_gpuInitialized) - ls->m_MapperGPU->UpdateMTime(); + // if(ls->m_gpuInitialized) + // ls->m_MapperGPU->UpdateMTime(); } -bool mitk::GPUVolumeMapper3D::InitGPU(mitk::BaseRenderer *renderer) +bool mitk::GPUVolumeMapper3D::InitGPU(mitk::BaseRenderer * /*renderer*/) { - LocalStorage *ls = m_LSH.GetLocalStorage(renderer); - - if (ls->m_gpuInitialized) - return ls->m_gpuSupported; - - ls->m_VtkRenderWindow = renderer->GetVtkRenderer()->GetRenderWindow(); - - GPU_INFO << "initializing gpu-slicing-vr (vtkMitkOpenGLVolumeTextureMapper3D)"; - - ls->m_MapperGPU = vtkSmartPointer::New(); - ls->m_MapperGPU->SetUseCompressedTexture(false); - ls->m_MapperGPU->SetSampleDistance(1.0); - - ls->m_VolumePropertyGPU = vtkSmartPointer::New(); - ls->m_VolumePropertyGPU->ShadeOn(); - ls->m_VolumePropertyGPU->SetAmbient(0.25f); // 0.05f - ls->m_VolumePropertyGPU->SetDiffuse(0.50f); // 0.45f - ls->m_VolumePropertyGPU->SetSpecular(0.40f); // 0.50f - ls->m_VolumePropertyGPU->SetSpecularPower(16.0f); - ls->m_VolumePropertyGPU->SetInterpolationTypeToLinear(); - - ls->m_VolumeGPU = vtkSmartPointer::New(); - ls->m_VolumeGPU->SetMapper(ls->m_MapperGPU); - ls->m_VolumeGPU->SetProperty(ls->m_VolumePropertyGPU); - ls->m_VolumeGPU->VisibilityOn(); - - ls->m_MapperGPU->SetInputConnection(this->m_UnitSpacingImageFilter->GetOutputPort()); - - ls->m_gpuSupported = ls->m_MapperGPU->IsRenderSupported(renderer->GetVtkRenderer(), ls->m_VolumePropertyGPU); - - ls->m_gpuInitialized = true; - - return ls->m_gpuSupported; + return false; } void mitk::GPUVolumeMapper3D::InitCPU(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); if (ls->m_cpuInitialized) return; ls->m_VtkRenderWindow = renderer->GetVtkRenderer()->GetRenderWindow(); ls->m_MapperCPU = vtkSmartPointer::New(); int numThreads = ls->m_MapperCPU->GetNumberOfThreads(); GPU_INFO << "initializing cpu-raycast-vr (vtkFixedPointVolumeRayCastMapper) (" << numThreads << " threads)"; ls->m_MapperCPU->SetSampleDistance(1.0); // ls->m_MapperCPU->LockSampleDistanceToInputSpacingOn(); ls->m_MapperCPU->SetImageSampleDistance(1.0); ls->m_MapperCPU->IntermixIntersectingGeometryOn(); ls->m_MapperCPU->SetAutoAdjustSampleDistances(0); ls->m_VolumePropertyCPU = vtkSmartPointer::New(); ls->m_VolumePropertyCPU->ShadeOn(); ls->m_VolumePropertyCPU->SetAmbient(0.10f); // 0.05f ls->m_VolumePropertyCPU->SetDiffuse(0.50f); // 0.45f ls->m_VolumePropertyCPU->SetSpecular(0.40f); // 0.50f ls->m_VolumePropertyCPU->SetSpecularPower(16.0f); ls->m_VolumePropertyCPU->SetInterpolationTypeToLinear(); ls->m_VolumeCPU = vtkSmartPointer::New(); ls->m_VolumeCPU->SetMapper(ls->m_MapperCPU); ls->m_VolumeCPU->SetProperty(ls->m_VolumePropertyCPU); ls->m_VolumeCPU->VisibilityOn(); ls->m_MapperCPU->SetInputConnection(m_UnitSpacingImageFilter->GetOutputPort()); // m_Resampler->GetOutput()); ls->m_cpuInitialized = true; } -void mitk::GPUVolumeMapper3D::DeinitGPU(mitk::BaseRenderer *renderer) -{ - LocalStorage *ls = m_LSH.GetLocalStorage(renderer); - - if (ls->m_gpuInitialized) - { - GPU_INFO << "deinitializing gpu-slicing-vr"; - // deinit renderwindow, this is needed to release the memory allocated on the gpu - // to prevent leaking memory on the gpu - ls->m_MapperGPU->ReleaseGraphicsResources(renderer->GetVtkRenderer()->GetVTKWindow()); - ls->m_VolumePropertyGPU = nullptr; - ls->m_MapperGPU = nullptr; - ls->m_VolumeGPU = nullptr; - ls->m_gpuInitialized = false; - } -} - void mitk::GPUVolumeMapper3D::DeinitCPU(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); if (!ls->m_cpuInitialized) return; GPU_INFO << "deinitializing cpu-raycast-vr"; ls->m_VolumePropertyCPU = nullptr; ls->m_MapperCPU = nullptr; ls->m_VolumeCPU = nullptr; ls->m_cpuInitialized = false; } mitk::GPUVolumeMapper3D::GPUVolumeMapper3D() { m_Volumenullptr = 0; m_commonInitialized = false; } mitk::GPUVolumeMapper3D::~GPUVolumeMapper3D() { DeinitCommon(); } void mitk::GPUVolumeMapper3D::InitCommon() { if (m_commonInitialized) return; m_UnitSpacingImageFilter = vtkSmartPointer::New(); m_UnitSpacingImageFilter->SetOutputSpacing(1.0, 1.0, 1.0); CreateDefaultTransferFunctions(); m_commonInitialized = true; } void mitk::GPUVolumeMapper3D::DeinitCommon() { if (!m_commonInitialized) return; m_commonInitialized = false; } bool mitk::GPUVolumeMapper3D::IsRenderable(mitk::BaseRenderer *renderer) { if (!GetDataNode()) return false; DataNode *node = GetDataNode(); bool visible = true; node->GetVisibility(visible, renderer, "visible"); if (!visible) return false; bool value = false; if (!node->GetBoolProperty("volumerendering", value, renderer)) return false; if (!value) return false; mitk::Image *input = const_cast(this->GetInput()); if (!input || !input->IsInitialized()) return false; vtkImageData *inputData = input->GetVtkImageData(this->GetTimestep()); if (inputData == nullptr) return false; return true; } void mitk::GPUVolumeMapper3D::InitVtkMapper(mitk::BaseRenderer *renderer) { -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) if (IsRAYEnabled(renderer)) { DeinitCPU(renderer); - DeinitGPU(renderer); if (!InitRAY(renderer)) { GPU_WARN << "hardware renderer can't initialize ... falling back to software renderer"; goto fallback; } } - else -#endif - if (IsGPUEnabled(renderer)) + else if (IsGPUEnabled(renderer)) { DeinitCPU(renderer); -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) DeinitRAY(renderer); -#endif if (!InitGPU(renderer)) { GPU_WARN << "hardware renderer can't initialize ... falling back to software renderer"; goto fallback; } } else { fallback: - DeinitGPU(renderer); -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) DeinitRAY(renderer); -#endif InitCPU(renderer); } } vtkProp *mitk::GPUVolumeMapper3D::GetVtkProp(mitk::BaseRenderer *renderer) { if (!IsRenderable(renderer)) { if (!m_Volumenullptr) { m_Volumenullptr = vtkSmartPointer::New(); m_Volumenullptr->VisibilityOff(); } return m_Volumenullptr; } InitCommon(); InitVtkMapper(renderer); LocalStorage *ls = m_LSH.GetLocalStorage(renderer); -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) if (ls->m_rayInitialized) return ls->m_VolumeRAY; -#endif if (ls->m_gpuInitialized) return ls->m_VolumeGPU; return ls->m_VolumeCPU; } void mitk::GPUVolumeMapper3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) { if (!IsRenderable(renderer)) return; InitCommon(); InitVtkMapper(renderer); mitk::Image *input = const_cast(this->GetInput()); vtkImageData *inputData = input->GetVtkImageData(this->GetTimestep()); m_UnitSpacingImageFilter->SetInputData(inputData); LocalStorage *ls = m_LSH.GetLocalStorage(renderer); -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) if (ls->m_rayInitialized) { GenerateDataRAY(renderer); } else -#endif if (ls->m_gpuInitialized) { GenerateDataGPU(renderer); } else { GenerateDataCPU(renderer); } // UpdateTransferFunctions UpdateTransferFunctions(renderer); } -void mitk::GPUVolumeMapper3D::GenerateDataGPU(mitk::BaseRenderer *renderer) +void mitk::GPUVolumeMapper3D::GenerateDataGPU(mitk::BaseRenderer * /*renderer*/) { - LocalStorage *ls = m_LSH.GetLocalStorage(renderer); - - bool useCompression = false; - GetDataNode()->GetBoolProperty("volumerendering.gpu.usetexturecompression", useCompression, renderer); - ls->m_MapperGPU->SetUseCompressedTexture(useCompression); - - if (IsLODEnabled(renderer) && mitk::RenderingManager::GetInstance()->GetNextLOD(renderer) == 0) - ls->m_MapperGPU->SetSampleDistance(2.0); - else - ls->m_MapperGPU->SetSampleDistance(1.0); - - // Updating shadings - { - float value = 0; - if (GetDataNode()->GetFloatProperty("volumerendering.gpu.ambient", value, renderer)) - ls->m_VolumePropertyGPU->SetAmbient(value); - if (GetDataNode()->GetFloatProperty("volumerendering.gpu.diffuse", value, renderer)) - ls->m_VolumePropertyGPU->SetDiffuse(value); - if (GetDataNode()->GetFloatProperty("volumerendering.gpu.specular", value, renderer)) - ls->m_VolumePropertyGPU->SetSpecular(value); - if (GetDataNode()->GetFloatProperty("volumerendering.gpu.specular.power", value, renderer)) - ls->m_VolumePropertyGPU->SetSpecularPower(value); - } } void mitk::GPUVolumeMapper3D::GenerateDataCPU(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); int nextLod = mitk::RenderingManager::GetInstance()->GetNextLOD(renderer); if (IsLODEnabled(renderer) && nextLod == 0) { ls->m_MapperCPU->SetImageSampleDistance(3.5); ls->m_MapperCPU->SetSampleDistance(1.25); ls->m_VolumePropertyCPU->SetInterpolationTypeToNearest(); } else { ls->m_MapperCPU->SetImageSampleDistance(1.0); ls->m_MapperCPU->SetSampleDistance(1.0); ls->m_VolumePropertyCPU->SetInterpolationTypeToLinear(); } // Check raycasting mode if (IsMIPEnabled(renderer)) ls->m_MapperCPU->SetBlendModeToMaximumIntensity(); else ls->m_MapperCPU->SetBlendModeToComposite(); // Updating shadings { float value = 0; if (GetDataNode()->GetFloatProperty("volumerendering.cpu.ambient", value, renderer)) ls->m_VolumePropertyCPU->SetAmbient(value); if (GetDataNode()->GetFloatProperty("volumerendering.cpu.diffuse", value, renderer)) ls->m_VolumePropertyCPU->SetDiffuse(value); if (GetDataNode()->GetFloatProperty("volumerendering.cpu.specular", value, renderer)) ls->m_VolumePropertyCPU->SetSpecular(value); if (GetDataNode()->GetFloatProperty("volumerendering.cpu.specular.power", value, renderer)) ls->m_VolumePropertyCPU->SetSpecularPower(value); } } void mitk::GPUVolumeMapper3D::CreateDefaultTransferFunctions() { m_DefaultOpacityTransferFunction = vtkSmartPointer::New(); m_DefaultOpacityTransferFunction->AddPoint(0.0, 0.0); m_DefaultOpacityTransferFunction->AddPoint(255.0, 0.8); m_DefaultOpacityTransferFunction->ClampingOn(); m_DefaultGradientTransferFunction = vtkSmartPointer::New(); m_DefaultGradientTransferFunction->AddPoint(0.0, 0.0); m_DefaultGradientTransferFunction->AddPoint(255.0, 0.8); m_DefaultGradientTransferFunction->ClampingOn(); m_DefaultColorTransferFunction = vtkSmartPointer::New(); m_DefaultColorTransferFunction->AddRGBPoint(0.0, 0.0, 0.0, 0.0); m_DefaultColorTransferFunction->AddRGBPoint(127.5, 1, 1, 0.0); m_DefaultColorTransferFunction->AddRGBPoint(255.0, 0.8, 0.2, 0); m_DefaultColorTransferFunction->ClampingOn(); m_BinaryOpacityTransferFunction = vtkSmartPointer::New(); m_BinaryOpacityTransferFunction->AddPoint(0, 0.0); m_BinaryOpacityTransferFunction->AddPoint(1, 1.0); m_BinaryGradientTransferFunction = vtkSmartPointer::New(); m_BinaryGradientTransferFunction->AddPoint(0.0, 1.0); m_BinaryColorTransferFunction = vtkSmartPointer::New(); } void mitk::GPUVolumeMapper3D::UpdateTransferFunctions(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); vtkPiecewiseFunction *opacityTransferFunction = m_DefaultOpacityTransferFunction; vtkPiecewiseFunction *gradientTransferFunction = m_DefaultGradientTransferFunction; vtkColorTransferFunction *colorTransferFunction = m_DefaultColorTransferFunction; bool isBinary = false; GetDataNode()->GetBoolProperty("binary", isBinary, renderer); if (isBinary) { opacityTransferFunction = m_BinaryOpacityTransferFunction; gradientTransferFunction = m_BinaryGradientTransferFunction; colorTransferFunction = m_BinaryColorTransferFunction; colorTransferFunction->RemoveAllPoints(); float rgb[3]; if (!GetDataNode()->GetColor(rgb, renderer)) rgb[0] = rgb[1] = rgb[2] = 1; colorTransferFunction->AddRGBPoint(0, rgb[0], rgb[1], rgb[2]); colorTransferFunction->Modified(); } else { mitk::TransferFunctionProperty *transferFunctionProp = dynamic_cast(this->GetDataNode()->GetProperty("TransferFunction", renderer)); if (transferFunctionProp) { opacityTransferFunction = transferFunctionProp->GetValue()->GetScalarOpacityFunction(); gradientTransferFunction = transferFunctionProp->GetValue()->GetGradientOpacityFunction(); colorTransferFunction = transferFunctionProp->GetValue()->GetColorTransferFunction(); } } if (ls->m_gpuInitialized) { ls->m_VolumePropertyGPU->SetColor(colorTransferFunction); ls->m_VolumePropertyGPU->SetScalarOpacity(opacityTransferFunction); ls->m_VolumePropertyGPU->SetGradientOpacity(gradientTransferFunction); } -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) - if (ls->m_rayInitialized) { ls->m_VolumePropertyRAY->SetColor(colorTransferFunction); ls->m_VolumePropertyRAY->SetScalarOpacity(opacityTransferFunction); ls->m_VolumePropertyRAY->SetGradientOpacity(gradientTransferFunction); } -#endif - if (ls->m_cpuInitialized) { ls->m_VolumePropertyCPU->SetColor(colorTransferFunction); ls->m_VolumePropertyCPU->SetScalarOpacity(opacityTransferFunction); ls->m_VolumePropertyCPU->SetGradientOpacity(gradientTransferFunction); } } void mitk::GPUVolumeMapper3D::ApplyProperties(vtkActor * /*actor*/, mitk::BaseRenderer * /*renderer*/) { // GPU_INFO << "ApplyProperties"; } void mitk::GPUVolumeMapper3D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { // GPU_INFO << "SetDefaultProperties"; node->AddProperty("volumerendering", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.usemip", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.uselod", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.cpu.ambient", mitk::FloatProperty::New(0.10f), renderer, overwrite); node->AddProperty("volumerendering.cpu.diffuse", mitk::FloatProperty::New(0.50f), renderer, overwrite); node->AddProperty("volumerendering.cpu.specular", mitk::FloatProperty::New(0.40f), renderer, overwrite); node->AddProperty("volumerendering.cpu.specular.power", mitk::FloatProperty::New(16.0f), renderer, overwrite); bool usegpu = true; #ifdef __APPLE__ usegpu = false; node->AddProperty("volumerendering.uselod", mitk::BoolProperty::New(true), renderer, overwrite); #endif node->AddProperty("volumerendering.usegpu", mitk::BoolProperty::New(usegpu), renderer, overwrite); -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) - node->AddProperty("volumerendering.useray", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.ray.ambient", mitk::FloatProperty::New(0.25f), renderer, overwrite); node->AddProperty("volumerendering.ray.diffuse", mitk::FloatProperty::New(0.50f), renderer, overwrite); node->AddProperty("volumerendering.ray.specular", mitk::FloatProperty::New(0.40f), renderer, overwrite); node->AddProperty("volumerendering.ray.specular.power", mitk::FloatProperty::New(16.0f), renderer, overwrite); -#endif node->AddProperty("volumerendering.gpu.ambient", mitk::FloatProperty::New(0.25f), renderer, overwrite); node->AddProperty("volumerendering.gpu.diffuse", mitk::FloatProperty::New(0.50f), renderer, overwrite); node->AddProperty("volumerendering.gpu.specular", mitk::FloatProperty::New(0.40f), renderer, overwrite); node->AddProperty("volumerendering.gpu.specular.power", mitk::FloatProperty::New(16.0f), renderer, overwrite); node->AddProperty("volumerendering.gpu.usetexturecompression", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("volumerendering.gpu.reducesliceartifacts", mitk::BoolProperty::New(false), renderer, overwrite); node->AddProperty("binary", mitk::BoolProperty::New(false), renderer, overwrite); mitk::Image::Pointer image = dynamic_cast(node->GetData()); if (image.IsNotNull() && image->IsInitialized()) { if ((overwrite) || (node->GetProperty("levelwindow", renderer) == nullptr)) { mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); mitk::LevelWindow levelwindow; levelwindow.SetAuto(image); levWinProp->SetLevelWindow(levelwindow); node->SetProperty("levelwindow", levWinProp, renderer); } if ((overwrite) || (node->GetProperty("TransferFunction", renderer) == nullptr)) { // add a default transfer function mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(tf); tfInit->SetTransferFunctionMode(0); node->SetProperty("TransferFunction", mitk::TransferFunctionProperty::New(tf.GetPointer())); } } Superclass::SetDefaultProperties(node, renderer, overwrite); } bool mitk::GPUVolumeMapper3D::IsLODEnabled(mitk::BaseRenderer *renderer) const { bool value = false; return GetDataNode()->GetBoolProperty("volumerendering.uselod", value, renderer) && value; } bool mitk::GPUVolumeMapper3D::IsMIPEnabled(mitk::BaseRenderer *renderer) { bool value = false; return GetDataNode()->GetBoolProperty("volumerendering.usemip", value, renderer) && value; } bool mitk::GPUVolumeMapper3D::IsGPUEnabled(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); bool value = false; return ls->m_gpuSupported && GetDataNode()->GetBoolProperty("volumerendering.usegpu", value, renderer) && value; } -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) - bool mitk::GPUVolumeMapper3D::InitRAY(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); if (ls->m_rayInitialized) return ls->m_raySupported; ls->m_VtkRenderWindow = renderer->GetVtkRenderer()->GetRenderWindow(); GPU_INFO << "initializing gpu-raycast-vr (vtkOpenGLGPUVolumeRayCastMapper)"; ls->m_MapperRAY = vtkSmartPointer::New(); ls->m_MapperRAY->SetAutoAdjustSampleDistances(0); ls->m_MapperRAY->SetSampleDistance(1.0); ls->m_VolumePropertyRAY = vtkSmartPointer::New(); ls->m_VolumePropertyRAY->ShadeOn(); ls->m_VolumePropertyRAY->SetAmbient(0.25f); // 0.05f ls->m_VolumePropertyRAY->SetDiffuse(0.50f); // 0.45f ls->m_VolumePropertyRAY->SetSpecular(0.40f); // 0.50f ls->m_VolumePropertyRAY->SetSpecularPower(16.0f); ls->m_VolumePropertyRAY->SetInterpolationTypeToLinear(); ls->m_VolumeRAY = vtkSmartPointer::New(); ls->m_VolumeRAY->SetMapper(ls->m_MapperRAY); ls->m_VolumeRAY->SetProperty(ls->m_VolumePropertyRAY); ls->m_VolumeRAY->VisibilityOn(); ls->m_MapperRAY->SetInputConnection(this->m_UnitSpacingImageFilter->GetOutputPort()); ls->m_raySupported = ls->m_MapperRAY->IsRenderSupported(renderer->GetRenderWindow(), ls->m_VolumePropertyRAY); ls->m_rayInitialized = true; return ls->m_raySupported; } void mitk::GPUVolumeMapper3D::DeinitRAY(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); if (ls->m_rayInitialized) { GPU_INFO << "deinitializing gpu-raycast-vr"; ls->m_MapperRAY = nullptr; ls->m_VolumePropertyRAY = nullptr; // Here ReleaseGraphicsResources has to be called to avoid VTK error messages. // This seems like a VTK bug, because ReleaseGraphicsResources() is ment for internal use, // but you cannot just delete the object (last smartpointer reference) without getting the // VTK error. ls->m_VolumeRAY->ReleaseGraphicsResources(renderer->GetVtkRenderer()->GetRenderWindow()); ls->m_VolumeRAY = nullptr; ls->m_rayInitialized = false; } } void mitk::GPUVolumeMapper3D::GenerateDataRAY(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); if (IsLODEnabled(renderer) && mitk::RenderingManager::GetInstance()->GetNextLOD(renderer) == 0) ls->m_MapperRAY->SetImageSampleDistance(4.0); else ls->m_MapperRAY->SetImageSampleDistance(1.0); // Check raycasting mode if (IsMIPEnabled(renderer)) ls->m_MapperRAY->SetBlendModeToMaximumIntensity(); else ls->m_MapperRAY->SetBlendModeToComposite(); // Updating shadings { float value = 0; if (GetDataNode()->GetFloatProperty("volumerendering.ray.ambient", value, renderer)) ls->m_VolumePropertyRAY->SetAmbient(value); if (GetDataNode()->GetFloatProperty("volumerendering.ray.diffuse", value, renderer)) ls->m_VolumePropertyRAY->SetDiffuse(value); if (GetDataNode()->GetFloatProperty("volumerendering.ray.specular", value, renderer)) ls->m_VolumePropertyRAY->SetSpecular(value); if (GetDataNode()->GetFloatProperty("volumerendering.ray.specular.power", value, renderer)) ls->m_VolumePropertyRAY->SetSpecularPower(value); } } bool mitk::GPUVolumeMapper3D::IsRAYEnabled(mitk::BaseRenderer *renderer) { LocalStorage *ls = m_LSH.GetLocalStorage(renderer); bool value = false; return ls->m_raySupported && GetDataNode()->GetBoolProperty("volumerendering.useray", value, renderer) && value; } - -#endif diff --git a/Modules/MapperExt/src/mitkVolumeMapperVtkSmart3D.cpp b/Modules/MapperExt/src/mitkVolumeMapperVtkSmart3D.cpp new file mode 100644 index 0000000000..f80a1fb416 --- /dev/null +++ b/Modules/MapperExt/src/mitkVolumeMapperVtkSmart3D.cpp @@ -0,0 +1,255 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include "mitkVolumeMapperVtkSmart3D.h" +#include "mitkTransferFunctionProperty.h" +#include "mitkTransferFunctionInitializer.h" +#include "mitkLevelWindowProperty.h" +#include +#include +#include +#include +#include + +void mitk::VolumeMapperVtkSmart3D::GenerateDataForRenderer(mitk::BaseRenderer *renderer) +{ + if (this->GetDataNode()->GetMTime() < this->GetMTime()) + { + return; + } + + bool value; + this->GetDataNode()->GetBoolProperty("volumerendering", value, renderer); + if (!value) + { + m_Volume->VisibilityOff(); + return; + } + else + { + m_Volume->VisibilityOn(); + } + + UpdateTransferFunctions(renderer); + UpdateRenderMode(renderer); + this->Modified(); +} + +vtkProp* mitk::VolumeMapperVtkSmart3D::GetVtkProp(mitk::BaseRenderer *) +{ + if (!m_Volume->GetMapper()) + { + createMapper(GetInputImage()); + createVolume(); + createVolumeProperty(); + } + + return m_Volume; +} + +void mitk::VolumeMapperVtkSmart3D::ApplyProperties(vtkActor *, mitk::BaseRenderer *) +{ + +} + +void mitk::VolumeMapperVtkSmart3D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) +{ + // GPU_INFO << "SetDefaultProperties"; + + node->AddProperty("volumerendering", mitk::BoolProperty::New(false), renderer, overwrite); + node->AddProperty("volumerendering.usemip", mitk::BoolProperty::New(false), renderer, overwrite); + + node->AddProperty("volumerendering.cpu.ambient", mitk::FloatProperty::New(0.10f), renderer, overwrite); + node->AddProperty("volumerendering.cpu.diffuse", mitk::FloatProperty::New(0.50f), renderer, overwrite); + node->AddProperty("volumerendering.cpu.specular", mitk::FloatProperty::New(0.40f), renderer, overwrite); + node->AddProperty("volumerendering.cpu.specular.power", mitk::FloatProperty::New(16.0f), renderer, overwrite); + node->AddProperty("volumerendering.usegpu", mitk::BoolProperty::New(false), renderer, overwrite); + node->AddProperty("volumerendering.useray", mitk::BoolProperty::New(false), renderer, overwrite); + + node->AddProperty("volumerendering.gpu.ambient", mitk::FloatProperty::New(0.25f), renderer, overwrite); + node->AddProperty("volumerendering.gpu.diffuse", mitk::FloatProperty::New(0.50f), renderer, overwrite); + node->AddProperty("volumerendering.gpu.specular", mitk::FloatProperty::New(0.40f), renderer, overwrite); + node->AddProperty("volumerendering.gpu.specular.power", mitk::FloatProperty::New(16.0f), renderer, overwrite); + + node->AddProperty("binary", mitk::BoolProperty::New(false), renderer, overwrite); + + mitk::Image::Pointer image = dynamic_cast(node->GetData()); + if (image.IsNotNull() && image->IsInitialized()) + { + if ((overwrite) || (node->GetProperty("levelwindow", renderer) == nullptr)) + { + mitk::LevelWindowProperty::Pointer levWinProp = mitk::LevelWindowProperty::New(); + mitk::LevelWindow levelwindow; + levelwindow.SetAuto(image); + levWinProp->SetLevelWindow(levelwindow); + node->SetProperty("levelwindow", levWinProp, renderer); + } + + if ((overwrite) || (node->GetProperty("TransferFunction", renderer) == nullptr)) + { + // add a default transfer function + mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); + mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(tf); + tfInit->SetTransferFunctionMode(0); + node->SetProperty("TransferFunction", mitk::TransferFunctionProperty::New(tf.GetPointer())); + } + } + + Superclass::SetDefaultProperties(node, renderer, overwrite); +} + +vtkImageData* mitk::VolumeMapperVtkSmart3D::GetInputImage() +{ + mitk::Image *input = const_cast(static_cast(this->GetDataNode()->GetData())); + vtkImageData* img = input->GetVtkImageData(this->GetTimestep()); + img->SetSpacing(1,1,1); + + return img; +} + +void mitk::VolumeMapperVtkSmart3D::createMapper(vtkImageData* imageData) +{ + m_SmartVolumeMapper->SetBlendModeToComposite(); + m_SmartVolumeMapper->SetInputData(imageData); +} + +void mitk::VolumeMapperVtkSmart3D::createVolume() +{ + m_Volume->VisibilityOff(); + m_Volume->SetMapper(m_SmartVolumeMapper); + m_Volume->SetProperty(m_VolumeProperty); +} + +void mitk::VolumeMapperVtkSmart3D::createVolumeProperty() +{ + m_VolumeProperty->ShadeOn(); + m_VolumeProperty->SetInterpolationType(VTK_LINEAR_INTERPOLATION); +} + +void mitk::VolumeMapperVtkSmart3D::UpdateTransferFunctions(mitk::BaseRenderer *renderer) +{ + vtkSmartPointer opacityTransferFunction; + vtkSmartPointer gradientTransferFunction; + vtkSmartPointer colorTransferFunction; + + bool isBinary = false; + + this->GetDataNode()->GetBoolProperty("binary", isBinary, renderer); + + if (isBinary) + { + colorTransferFunction = vtkSmartPointer::New(); + + float rgb[3]; + if (!GetDataNode()->GetColor(rgb, renderer)) + rgb[0] = rgb[1] = rgb[2] = 1; + colorTransferFunction->AddRGBPoint(0, rgb[0], rgb[1], rgb[2]); + colorTransferFunction->Modified(); + + opacityTransferFunction = vtkSmartPointer::New(); + gradientTransferFunction = vtkSmartPointer::New(); + } + else + { + mitk::TransferFunctionProperty *transferFunctionProp = + dynamic_cast(this->GetDataNode()->GetProperty("TransferFunction", renderer)); + + if (transferFunctionProp) + { + opacityTransferFunction = transferFunctionProp->GetValue()->GetScalarOpacityFunction(); + gradientTransferFunction = transferFunctionProp->GetValue()->GetGradientOpacityFunction(); + colorTransferFunction = transferFunctionProp->GetValue()->GetColorTransferFunction(); + } + else + { + opacityTransferFunction = vtkSmartPointer::New(); + gradientTransferFunction = vtkSmartPointer::New(); + colorTransferFunction = vtkSmartPointer::New(); + } + } + + m_VolumeProperty->SetColor(colorTransferFunction); + m_VolumeProperty->SetScalarOpacity(opacityTransferFunction); + m_VolumeProperty->SetGradientOpacity(gradientTransferFunction); +} + + +void mitk::VolumeMapperVtkSmart3D::UpdateRenderMode(mitk::BaseRenderer *renderer) +{ + bool usegpu = false; + bool useray = false; + bool usemip = false; + this->GetDataNode()->GetBoolProperty("volumerendering.usegpu", usegpu); + this->GetDataNode()->GetBoolProperty("volumerendering.useray", useray); + this->GetDataNode()->GetBoolProperty("volumerendering.usemip", usemip); + + if (usegpu) + m_SmartVolumeMapper->SetRequestedRenderModeToGPU(); + else if (useray) + m_SmartVolumeMapper->SetRequestedRenderModeToRayCast(); + else + m_SmartVolumeMapper->SetRequestedRenderModeToDefault(); + + int blendMode; + if (this->GetDataNode()->GetIntProperty("volumerendering.blendmode", blendMode)) + m_SmartVolumeMapper->SetBlendMode(blendMode); + else if (usemip) + m_SmartVolumeMapper->SetBlendMode(vtkSmartVolumeMapper::MAXIMUM_INTENSITY_BLEND); + + // shading parameter + if (m_SmartVolumeMapper->GetRequestedRenderMode() == vtkSmartVolumeMapper::GPURenderMode) + { + float value = 0; + if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.ambient", value, renderer)) + m_VolumeProperty->SetAmbient(value); + if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.diffuse", value, renderer)) + m_VolumeProperty->SetDiffuse(value); + if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.specular", value, renderer)) + m_VolumeProperty->SetSpecular(value); + if (this->GetDataNode()->GetFloatProperty("volumerendering.gpu.specular.power", value, renderer)) + m_VolumeProperty->SetSpecularPower(value); + } + else + { + float value = 0; + if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.ambient", value, renderer)) + m_VolumeProperty->SetAmbient(value); + if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.diffuse", value, renderer)) + m_VolumeProperty->SetDiffuse(value); + if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.specular", value, renderer)) + m_VolumeProperty->SetSpecular(value); + if (this->GetDataNode()->GetFloatProperty("volumerendering.cpu.specular.power", value, renderer)) + m_VolumeProperty->SetSpecularPower(value); + } +} + +mitk::VolumeMapperVtkSmart3D::VolumeMapperVtkSmart3D() +{ + vtkObjectFactory::RegisterFactory(vtkRenderingOpenGL2ObjectFactory::New()); + vtkObjectFactory::RegisterFactory(vtkRenderingVolumeOpenGL2ObjectFactory::New()); + + m_SmartVolumeMapper = vtkSmartPointer::New(); + m_SmartVolumeMapper->SetBlendModeToComposite(); + m_VolumeProperty = vtkSmartPointer::New(); + m_Volume = vtkSmartPointer::New(); +} + +mitk::VolumeMapperVtkSmart3D::~VolumeMapperVtkSmart3D() +{ + +} + + diff --git a/Modules/MapperExt/src/vtkMitkGPUVolumeRayCastMapper.cpp b/Modules/MapperExt/src/vtkMitkGPUVolumeRayCastMapper.cpp index 9f483a152f..e3c0a47f72 100644 --- a/Modules/MapperExt/src/vtkMitkGPUVolumeRayCastMapper.cpp +++ b/Modules/MapperExt/src/vtkMitkGPUVolumeRayCastMapper.cpp @@ -1,629 +1,624 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ /*========================================================================= Program: Visualization Toolkit Module: $RCSfile: vtkMitkGPUVolumeRayCastMapper.cxx,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMitkGPUVolumeRayCastMapper.h" - -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION == 5) && (VTK_MINOR_VERSION >= 6))) - #include "vtkCamera.h" #include "vtkCellData.h" #include "vtkCommand.h" // for VolumeMapperRender{Start|End|Progress}Event #include "vtkDataArray.h" #include "vtkGPUInfo.h" #include "vtkGPUInfoList.h" #include "vtkImageData.h" #include "vtkImageResample.h" #include "vtkMultiThreader.h" #include "vtkPointData.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkRendererCollection.h" #include "vtkTimerLog.h" #include "vtkVolume.h" #include "vtkVolumeProperty.h" #include vtkInstantiatorNewMacro(vtkMitkGPUVolumeRayCastMapper); vtkCxxSetObjectMacro(vtkMitkGPUVolumeRayCastMapper, MaskInput, vtkImageData); vtkCxxSetObjectMacro(vtkMitkGPUVolumeRayCastMapper, TransformedInput, vtkImageData); vtkMitkGPUVolumeRayCastMapper::vtkMitkGPUVolumeRayCastMapper() { this->AutoAdjustSampleDistances = 1; this->ImageSampleDistance = 1.0; this->MinimumImageSampleDistance = 1.0; this->MaximumImageSampleDistance = 10.0; this->SampleDistance = 1.0; this->SmallVolumeRender = 0; this->BigTimeToDraw = 0.0; this->SmallTimeToDraw = 0.0; this->FinalColorWindow = 1.0; this->FinalColorLevel = 0.5; this->GeneratingCanonicalView = 0; this->CanonicalViewImageData = nullptr; this->MaskInput = nullptr; this->MaskBlendFactor = 1.0f; this->AMRMode = 0; this->ClippedCroppingRegionPlanes[0] = VTK_DOUBLE_MAX; this->ClippedCroppingRegionPlanes[1] = VTK_DOUBLE_MIN; this->ClippedCroppingRegionPlanes[2] = VTK_DOUBLE_MAX; this->ClippedCroppingRegionPlanes[3] = VTK_DOUBLE_MIN; this->ClippedCroppingRegionPlanes[4] = VTK_DOUBLE_MAX; this->ClippedCroppingRegionPlanes[5] = VTK_DOUBLE_MIN; this->MaxMemoryInBytes = 0; vtkGPUInfoList *l = vtkGPUInfoList::New(); l->Probe(); if (l->GetNumberOfGPUs() > 0) { vtkGPUInfo *info = l->GetGPUInfo(0); this->MaxMemoryInBytes = info->GetDedicatedVideoMemory(); if (this->MaxMemoryInBytes == 0) { this->MaxMemoryInBytes = info->GetDedicatedSystemMemory(); } // we ignore info->GetSharedSystemMemory(); as this is very slow. } l->Delete(); if (this->MaxMemoryInBytes == 0) // use some default value: 128MB. { this->MaxMemoryInBytes = 128 * 1024 * 1024; } this->MaxMemoryFraction = 0.75; this->ReportProgress = true; this->TransformedInput = nullptr; this->LastInput = nullptr; } // ---------------------------------------------------------------------------- vtkMitkGPUVolumeRayCastMapper::~vtkMitkGPUVolumeRayCastMapper() { this->SetMaskInput(nullptr); this->SetTransformedInput(nullptr); this->LastInput = nullptr; } // ---------------------------------------------------------------------------- // The render method that is called from the volume. If this is a canonical // view render, a specialized version of this method will be called instead. // Otherwise we will // - Invoke a start event // - Start timing // - Check that everything is OK for rendering // - Render // - Stop the timer and record results // - Invoke an end event // ---------------------------------------------------------------------------- void vtkMitkGPUVolumeRayCastMapper::Render(vtkRenderer *ren, vtkVolume *vol) { // Catch renders that are happening due to a canonical view render and // handle them separately. if (this->GeneratingCanonicalView) { this->CanonicalViewRender(ren, vol); return; } // Invoke a VolumeMapperRenderStartEvent this->InvokeEvent(vtkCommand::VolumeMapperRenderStartEvent, nullptr); // Start the timer to time the length of this render vtkTimerLog *timer = vtkTimerLog::New(); timer->StartTimer(); // Make sure everything about this render is OK. // This is where the input is updated. if (this->ValidateRender(ren, vol)) { // Everything is OK - so go ahead and really do the render this->GPURender(ren, vol); } // Stop the timer timer->StopTimer(); double t = timer->GetElapsedTime(); // cout << "Render Timer " << t << " seconds, " << 1.0/t << " frames per second" << endl; this->TimeToDraw = t; timer->Delete(); if (vol->GetAllocatedRenderTime() < 1.0) { this->SmallTimeToDraw = t; } else { this->BigTimeToDraw = t; } // Invoke a VolumeMapperRenderEndEvent this->InvokeEvent(vtkCommand::VolumeMapperRenderEndEvent, nullptr); } // ---------------------------------------------------------------------------- // Special version for rendering a canonical view - we don't do things like // invoke start or end events, and we don't capture the render time. // ---------------------------------------------------------------------------- void vtkMitkGPUVolumeRayCastMapper::CanonicalViewRender(vtkRenderer *ren, vtkVolume *vol) { // Make sure everything about this render is OK if (this->ValidateRender(ren, vol)) { // Everything is OK - so go ahead and really do the render this->GPURender(ren, vol); } } // ---------------------------------------------------------------------------- // This method us used by the render method to validate everything before // attempting to render. This method returns 0 if something is not right - // such as missing input, a null renderer or a null volume, no scalars, etc. // In some cases it will produce a vtkErrorMacro message, and in others // (for example, in the case of cropping planes that define a region with // a volume or 0 or less) it will fail silently. If everything is OK, it will // return with a value of 1. // ---------------------------------------------------------------------------- int vtkMitkGPUVolumeRayCastMapper::ValidateRender(vtkRenderer *ren, vtkVolume *vol) { // Check that we have everything we need to render. int goodSoFar = 1; // Check for a renderer - we MUST have one if (!ren) { goodSoFar = 0; vtkErrorMacro("Renderer cannot be null."); } // Check for the volume - we MUST have one if (goodSoFar && !vol) { goodSoFar = 0; vtkErrorMacro("Volume cannot be null."); } // Don't need to check if we have a volume property // since the volume will create one if we don't. Also // don't need to check for the scalar opacity function // or the RGB transfer function since the property will // create them if they do not yet exist. // However we must currently check that the number of // color channels is 3 // TODO: lift this restriction - should work with // gray functions as well. Right now turning off test // because otherwise 4 component rendering isn't working. // Will revisit. if (goodSoFar && vol->GetProperty()->GetColorChannels() != 3) { // goodSoFar = 0; // vtkErrorMacro("Must have a color transfer function."); } // Check the cropping planes. If they are invalid, just silently // fail. This will happen when an interactive widget is dragged // such that it defines 0 or negative volume - this can happen // and should just not render the volume. // Check the cropping planes if (goodSoFar && this->Cropping && (this->CroppingRegionPlanes[0] >= this->CroppingRegionPlanes[1] || this->CroppingRegionPlanes[2] >= this->CroppingRegionPlanes[3] || this->CroppingRegionPlanes[4] >= this->CroppingRegionPlanes[5])) { // No error message here - we want to be silent goodSoFar = 0; } // Check that we have input data vtkImageData *input = this->GetInput(); // If we have a timestamp change or data change then create a new clone. if (input != this->LastInput || input->GetMTime() > this->TransformedInput->GetMTime()) { this->LastInput = input; vtkImageData *clone; if (!this->TransformedInput) { clone = vtkImageData::New(); this->SetTransformedInput(clone); clone->Delete(); } else { clone = this->TransformedInput; } clone->ShallowCopy(input); // @TODO: This is the workaround to deal with GPUVolumeRayCastMapper // not able to handle extents starting from non zero values. // There is not a easy fix in the GPU volume ray cast mapper hence // this fix has been introduced. // Get the current extents. int extents[6], real_extents[6]; clone->GetExtent(extents); clone->GetExtent(real_extents); // Get the current origin and spacing. double origin[3], spacing[3]; clone->GetOrigin(origin); clone->GetSpacing(spacing); for (int cc = 0; cc < 3; cc++) { // Transform the origin and the extents. origin[cc] = origin[cc] + extents[2 * cc] * spacing[cc]; extents[2 * cc + 1] -= extents[2 * cc]; extents[2 * cc] -= extents[2 * cc]; } clone->SetOrigin(origin); clone->SetExtent(extents); } if (goodSoFar && !this->TransformedInput) { vtkErrorMacro("Input is nullptr but is required"); goodSoFar = 0; } // Update the date then make sure we have scalars. Note // that we must have point or cell scalars because field // scalars are not supported. vtkDataArray *scalars = nullptr; if (goodSoFar) { // Here is where we update the input // this->TransformedInput->UpdateInformation(); //VTK6_TODO // this->TransformedInput->SetUpdateExtentToWholeExtent(); // this->TransformedInput->Update(); // Now make sure we can find scalars scalars = this->GetScalars( this->TransformedInput, this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, this->CellFlag); // We couldn't find scalars if (!scalars) { vtkErrorMacro("No scalars found on input."); goodSoFar = 0; } // Even if we found scalars, if they are field data scalars that isn't good else if (this->CellFlag == 2) { vtkErrorMacro("Only point or cell scalar support - found field scalars instead."); goodSoFar = 0; } } // Make sure the scalar type is actually supported. This mappers supports // almost all standard scalar types. if (goodSoFar) { switch (scalars->GetDataType()) { case VTK_CHAR: vtkErrorMacro(<< "scalar of type VTK_CHAR is not supported " << "because this type is platform dependent. " << "Use VTK_SIGNED_CHAR or VTK_UNSIGNED_CHAR instead."); goodSoFar = 0; break; case VTK_BIT: vtkErrorMacro("scalar of type VTK_BIT is not supported by this mapper."); goodSoFar = 0; break; case VTK_ID_TYPE: vtkErrorMacro("scalar of type VTK_ID_TYPE is not supported by this mapper."); goodSoFar = 0; break; case VTK_STRING: vtkErrorMacro("scalar of type VTK_STRING is not supported by this mapper."); goodSoFar = 0; break; default: // Don't need to do anything here break; } } // Check on the blending type - we support composite and min / max intensity if (goodSoFar) { if (this->BlendMode != vtkVolumeMapper::COMPOSITE_BLEND && this->BlendMode != vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND && this->BlendMode != vtkVolumeMapper::MINIMUM_INTENSITY_BLEND) { goodSoFar = 0; vtkErrorMacro(<< "Selected blend mode not supported. " << "Only Composite and MIP and MinIP modes " << "are supported by the current implementation."); } } // This mapper supports 1 component data, or 4 component if it is not independent // component (i.e. the four components define RGBA) int numberOfComponents = 0; if (goodSoFar) { numberOfComponents = scalars->GetNumberOfComponents(); if (!(numberOfComponents == 1 || (numberOfComponents == 4 && vol->GetProperty()->GetIndependentComponents() == 0))) { goodSoFar = 0; vtkErrorMacro(<< "Only one component scalars, or four " << "component with non-independent components, " << "are supported by this mapper."); } } // If this is four component data, then it better be unsigned char (RGBA). if (goodSoFar && numberOfComponents == 4 && scalars->GetDataType() != VTK_UNSIGNED_CHAR) { goodSoFar = 0; vtkErrorMacro("Only unsigned char is supported for 4-component scalars!"); } // return our status return goodSoFar; } // ---------------------------------------------------------------------------- // Description: // Called by the AMR Volume Mapper. // Set the flag that tells if the scalars are on point data (0) or // cell data (1). void vtkMitkGPUVolumeRayCastMapper::SetCellFlag(int cellFlag) { this->CellFlag = cellFlag; } // ---------------------------------------------------------------------------- void vtkMitkGPUVolumeRayCastMapper::CreateCanonicalView(vtkRenderer *ren, vtkVolume *volume, vtkImageData *image, int vtkNotUsed(blend_mode), double viewDirection[3], double viewUp[3]) { this->GeneratingCanonicalView = 1; int oldSwap = ren->GetRenderWindow()->GetSwapBuffers(); ren->GetRenderWindow()->SwapBuffersOff(); int dim[3]; image->GetDimensions(dim); int *size = ren->GetRenderWindow()->GetSize(); vtkImageData *bigImage = vtkImageData::New(); bigImage->SetDimensions(size[0], size[1], 1); bigImage->AllocateScalars(VTK_UNSIGNED_CHAR, 3); this->CanonicalViewImageData = bigImage; double scale[2]; scale[0] = dim[0] / static_cast(size[0]); scale[1] = dim[1] / static_cast(size[1]); // Save the visibility flags of the renderers and set all to false except // for the ren. vtkRendererCollection *renderers = ren->GetRenderWindow()->GetRenderers(); int numberOfRenderers = renderers->GetNumberOfItems(); auto rendererVisibilities = new bool[numberOfRenderers]; renderers->InitTraversal(); int i = 0; while (i < numberOfRenderers) { vtkRenderer *r = renderers->GetNextItem(); rendererVisibilities[i] = r->GetDraw() == 1; if (r != ren) { r->SetDraw(false); } ++i; } // Save the visibility flags of the props and set all to false except // for the volume. vtkPropCollection *props = ren->GetViewProps(); int numberOfProps = props->GetNumberOfItems(); auto propVisibilities = new bool[numberOfProps]; props->InitTraversal(); i = 0; while (i < numberOfProps) { vtkProp *p = props->GetNextProp(); propVisibilities[i] = p->GetVisibility() == 1; if (p != volume) { p->SetVisibility(false); } ++i; } vtkCamera *savedCamera = ren->GetActiveCamera(); savedCamera->Modified(); vtkCamera *canonicalViewCamera = vtkCamera::New(); // Code from vtkFixedPointVolumeRayCastMapper: double *center = volume->GetCenter(); double bounds[6]; volume->GetBounds(bounds); double d = sqrt((bounds[1] - bounds[0]) * (bounds[1] - bounds[0]) + (bounds[3] - bounds[2]) * (bounds[3] - bounds[2]) + (bounds[5] - bounds[4]) * (bounds[5] - bounds[4])); // For now use x distance - need to change this d = bounds[1] - bounds[0]; // Set up the camera in parallel canonicalViewCamera->SetFocalPoint(center); canonicalViewCamera->ParallelProjectionOn(); canonicalViewCamera->SetPosition( center[0] - d * viewDirection[0], center[1] - d * viewDirection[1], center[2] - d * viewDirection[2]); canonicalViewCamera->SetViewUp(viewUp); canonicalViewCamera->SetParallelScale(d / 2); ren->SetActiveCamera(canonicalViewCamera); ren->GetRenderWindow()->Render(); ren->SetActiveCamera(savedCamera); canonicalViewCamera->Delete(); // Shrink to image to the desired size vtkImageResample *resample = vtkImageResample::New(); resample->SetInputData(bigImage); resample->SetAxisMagnificationFactor(0, scale[0]); resample->SetAxisMagnificationFactor(1, scale[1]); resample->SetAxisMagnificationFactor(2, 1); resample->UpdateWholeExtent(); // Copy the pixels over image->DeepCopy(resample->GetOutput()); bigImage->Delete(); resample->Delete(); // Restore the visibility flags of the props props->InitTraversal(); i = 0; while (i < numberOfProps) { vtkProp *p = props->GetNextProp(); p->SetVisibility(propVisibilities[i]); ++i; } delete[] propVisibilities; // Restore the visibility flags of the renderers renderers->InitTraversal(); i = 0; while (i < numberOfRenderers) { vtkRenderer *r = renderers->GetNextItem(); r->SetDraw(rendererVisibilities[i]); ++i; } delete[] rendererVisibilities; ren->GetRenderWindow()->SetSwapBuffers(oldSwap); this->CanonicalViewImageData = nullptr; this->GeneratingCanonicalView = 0; } // ---------------------------------------------------------------------------- // Print method for vtkMitkGPUVolumeRayCastMapper void vtkMitkGPUVolumeRayCastMapper::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "AutoAdjustSampleDistances: " << this->AutoAdjustSampleDistances << endl; os << indent << "MinimumImageSampleDistance: " << this->MinimumImageSampleDistance << endl; os << indent << "MaximumImageSampleDistance: " << this->MaximumImageSampleDistance << endl; os << indent << "ImageSampleDistance: " << this->ImageSampleDistance << endl; os << indent << "SampleDistance: " << this->SampleDistance << endl; os << indent << "FinalColorWindow: " << this->FinalColorWindow << endl; os << indent << "FinalColorLevel: " << this->FinalColorLevel << endl; os << indent << "MaskInput: " << this->MaskInput << endl; os << indent << "MaskBlendFactor: " << this->MaskBlendFactor << endl; os << indent << "MaxMemoryInBytes: " << this->MaxMemoryInBytes << endl; os << indent << "MaxMemoryFraction: " << this->MaxMemoryFraction << endl; os << indent << "ReportProgress: " << this->ReportProgress << endl; } // ---------------------------------------------------------------------------- // Description: // Compute the cropping planes clipped by the bounds of the volume. // The result is put into this->ClippedCroppingRegionPlanes. // NOTE: IT WILL BE MOVED UP TO vtkVolumeMapper after bullet proof usage // in this mapper. Other subclasses will use the ClippedCroppingRegionsPlanes // members instead of CroppingRegionPlanes. // \pre volume_exists: this->GetInput()!=0 // \pre valid_cropping: this->Cropping && // this->CroppingRegionPlanes[0]CroppingRegionPlanes[1] && // this->CroppingRegionPlanes[2]CroppingRegionPlanes[3] && // this->CroppingRegionPlanes[4]CroppingRegionPlanes[5]) void vtkMitkGPUVolumeRayCastMapper::ClipCroppingRegionPlanes() { assert("pre: volume_exists" && this->GetInput() != nullptr); assert("pre: valid_cropping" && this->Cropping && this->CroppingRegionPlanes[0] < this->CroppingRegionPlanes[1] && this->CroppingRegionPlanes[2] < this->CroppingRegionPlanes[3] && this->CroppingRegionPlanes[4] < this->CroppingRegionPlanes[5]); // vtkVolumeMapper::Render() will have something like: // if(this->Cropping && (this->CroppingRegionPlanes[0]>=this->CroppingRegionPlanes[1] || // this->CroppingRegionPlanes[2]>=this->CroppingRegionPlanes[3] || // this->CroppingRegionPlanes[4]>=this->CroppingRegionPlanes[5])) // { // // silentely stop because the cropping is not valid. // return; // } double volBounds[6]; this->GetInput()->GetBounds(volBounds); int i = 0; while (i < 6) { // max of the mins if (this->CroppingRegionPlanes[i] < volBounds[i]) { this->ClippedCroppingRegionPlanes[i] = volBounds[i]; } else { this->ClippedCroppingRegionPlanes[i] = this->CroppingRegionPlanes[i]; } ++i; // min of the maxs if (this->CroppingRegionPlanes[i] > volBounds[i]) { this->ClippedCroppingRegionPlanes[i] = volBounds[i]; } + else { this->ClippedCroppingRegionPlanes[i] = this->CroppingRegionPlanes[i]; } ++i; } } - -#endif diff --git a/Modules/MapperExt/src/vtkPointSetSlicer.cxx b/Modules/MapperExt/src/vtkPointSetSlicer.cxx index 8d433c392f..8c6930f5be 100644 --- a/Modules/MapperExt/src/vtkPointSetSlicer.cxx +++ b/Modules/MapperExt/src/vtkPointSetSlicer.cxx @@ -1,638 +1,638 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include #include #include "vtkPointSetSlicer.h" #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkCutter.h" #include "vtkDataSet.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkGenericCell.h" #include "vtkMergePoints.h" #include "vtkObjectFactory.h" #include "vtkPlane.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkUnstructuredGrid.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkStreamingDemandDrivenPipeline.h" vtkStandardNewMacro(vtkPointSetSlicer); // Construct with user-specified implicit function; initial value of 0.0; and // generating cut scalars turned off. vtkPointSetSlicer::vtkPointSetSlicer(vtkPlane *cf) { this->SlicePlane = cf; this->GenerateCutScalars = 0; this->Locator = 0; this->Cutter = vtkCutter::New(); this->Cutter->GenerateValues(1, 0, 1); } vtkPointSetSlicer::~vtkPointSetSlicer() { this->SetSlicePlane(0); if (this->Locator) { this->Locator->UnRegister(this); this->Locator = NULL; } this->Cutter->Delete(); } void vtkPointSetSlicer::SetSlicePlane(vtkPlane *plane) { if (this->SlicePlane == plane) { return; } if (this->SlicePlane) { this->SlicePlane->UnRegister(this); this->SlicePlane = 0; } if (plane) { plane->Register(this); this->Cutter->SetCutFunction(plane); } this->SlicePlane = plane; this->Modified(); } // Overload standard modified time function. If cut functions is modified, // or contour values modified, then this object is modified as well. -unsigned long vtkPointSetSlicer::GetMTime() +vtkMTimeType vtkPointSetSlicer::GetMTime() { - unsigned long mTime = this->Superclass::GetMTime(); - unsigned long time; + vtkMTimeType mTime = this->Superclass::GetMTime(); + vtkMTimeType time; if (this->SlicePlane != 0) { time = this->SlicePlane->GetMTime(); mTime = (time > mTime ? time : mTime); } if (this->Locator != 0) { time = this->Locator->GetMTime(); mTime = (time > mTime ? time : mTime); } return mTime; } int vtkPointSetSlicer::RequestData(vtkInformation * /*request*/, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { // get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); // get the input and ouptut vtkDataSet *input = vtkDataSet::SafeDownCast(inInfo->Get(vtkDataObject::DATA_OBJECT())); vtkPolyData *output = vtkPolyData::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); vtkDebugMacro(<< "Executing cutter"); if (!this->SlicePlane) { vtkErrorMacro("No slice plane specified"); return 0; } if (input->GetNumberOfPoints() < 1) { return 1; } if (input->GetDataObjectType() == VTK_STRUCTURED_POINTS || input->GetDataObjectType() == VTK_IMAGE_DATA) { if (input->GetCell(0) && input->GetCell(0)->GetCellDimension() >= 3) { // this->StructuredPointsCutter(input, output, request, inputVector, outputVector); return 1; } } if (input->GetDataObjectType() == VTK_STRUCTURED_GRID) { if (input->GetCell(0)) { int dim = input->GetCell(0)->GetCellDimension(); // only do 3D structured grids (to be extended in the future) if (dim >= 3) { // this->StructuredGridCutter(input, output); return 1; } } } if (input->GetDataObjectType() == VTK_RECTILINEAR_GRID) { // this->RectilinearGridCutter(input, output); return 1; } if (input->GetDataObjectType() == VTK_UNSTRUCTURED_GRID) { vtkDebugMacro(<< "Executing Unstructured Grid Cutter"); this->UnstructuredGridCutter(input, output); } else { vtkDebugMacro(<< "Executing DataSet Cutter"); // this->DataSetCutter(input, output); } return 1; } int vtkPointSetSlicer::RequestUpdateExtent(vtkInformation *, vtkInformationVector **inputVector, vtkInformationVector *) { vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); inInfo->Set(vtkStreamingDemandDrivenPipeline::EXACT_EXTENT(), 1); return 1; } int vtkPointSetSlicer::FillInputPortInformation(int, vtkInformation *info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkDataSet"); return 1; } void vtkPointSetSlicer::UnstructuredGridCutter(vtkDataSet *input, vtkPolyData *output) { vtkIdType cellId, i; vtkDoubleArray *cellScalars; vtkCellArray *newVerts, *newLines, *newPolys; vtkPoints *newPoints; vtkDoubleArray *cutScalars; double s; vtkIdType estimatedSize, numCells = input->GetNumberOfCells(); vtkIdType numPts = input->GetNumberOfPoints(); vtkIdType cellArrayIt = 0; int numCellPts; vtkPointData *inPD, *outPD; vtkCellData *inCD = input->GetCellData(), *outCD = output->GetCellData(); vtkIdList *cellIds; int abortExecute = 0; double range[2]; // Create objects to hold output of contour operation // estimatedSize = (vtkIdType)pow((double)numCells, .75); estimatedSize = estimatedSize / 1024 * 1024; // multiple of 1024 if (estimatedSize < 1024) { estimatedSize = 1024; } newPoints = vtkPoints::New(); newPoints->Allocate(estimatedSize, estimatedSize / 2); newVerts = vtkCellArray::New(); newVerts->Allocate(estimatedSize, estimatedSize / 2); newLines = vtkCellArray::New(); newLines->Allocate(estimatedSize, estimatedSize / 2); newPolys = vtkCellArray::New(); newPolys->Allocate(estimatedSize, estimatedSize / 2); cutScalars = vtkDoubleArray::New(); cutScalars->SetNumberOfTuples(numPts); // Interpolate data along edge. If generating cut scalars, do necessary setup if (this->GenerateCutScalars) { inPD = vtkPointData::New(); inPD->ShallowCopy(input->GetPointData()); // copies original attributes inPD->SetScalars(cutScalars); } else { inPD = input->GetPointData(); } outPD = output->GetPointData(); outPD->InterpolateAllocate(inPD, estimatedSize, estimatedSize / 2); outCD->CopyAllocate(inCD, estimatedSize, estimatedSize / 2); // locator used to merge potentially duplicate points if (this->Locator == NULL) { this->CreateDefaultLocator(); } this->Locator->InitPointInsertion(newPoints, input->GetBounds()); // Loop over all points evaluating scalar function at each point // for (i = 0; i < numPts; i++) { s = this->SlicePlane->FunctionValue(input->GetPoint(i)); cutScalars->SetComponent(i, 0, s); } // Compute some information for progress methods // vtkIdType numCuts = numCells; vtkIdType progressInterval = numCuts / 20 + 1; int cut = 0; vtkUnstructuredGrid *grid = (vtkUnstructuredGrid *)input; vtkIdType *cellArrayPtr = grid->GetCells()->GetPointer(); double *scalarArrayPtr = cutScalars->GetPointer(0); double tempScalar; cellScalars = cutScalars->NewInstance(); cellScalars->SetNumberOfComponents(cutScalars->GetNumberOfComponents()); cellScalars->Allocate(VTK_CELL_SIZE * cutScalars->GetNumberOfComponents()); // Three passes over the cells to process lower dimensional cells first. // For poly data output cells need to be added in the order: // verts, lines and then polys, or cell data gets mixed up. // A better solution is to have an unstructured grid output. // I create a table that maps cell type to cell dimensionality, // because I need a fast way to get cell dimensionality. // This assumes GetCell is slow and GetCellType is fast. // I do not like hard coding a list of cell types here, // but I do not want to add GetCellDimension(vtkIdType cellId) // to the vtkDataSet API. Since I anticipate that the output // will change to vtkUnstructuredGrid. This temporary solution // is acceptable. // int cellType; unsigned char cellTypeDimensions[VTK_NUMBER_OF_CELL_TYPES]; vtkCutter::GetCellTypeDimensions(cellTypeDimensions); int dimensionality; // We skip 0d cells (points), because they cannot be cut (generate no data). for (dimensionality = 1; dimensionality <= 3; ++dimensionality) { // Loop over all cells; get scalar values for all cell points // and process each cell. // cellArrayIt = 0; for (cellId = 0; cellId < numCells && !abortExecute; cellId++) { numCellPts = cellArrayPtr[cellArrayIt]; // I assume that "GetCellType" is fast. cellType = input->GetCellType(cellId); if (cellType >= VTK_NUMBER_OF_CELL_TYPES) { // Protect against new cell types added. vtkErrorMacro("Unknown cell type " << cellType); cellArrayIt += 1 + numCellPts; continue; } if (cellTypeDimensions[cellType] != dimensionality) { cellArrayIt += 1 + numCellPts; continue; } cellArrayIt++; // find min and max values in scalar data range[0] = scalarArrayPtr[cellArrayPtr[cellArrayIt]]; range[1] = scalarArrayPtr[cellArrayPtr[cellArrayIt]]; cellArrayIt++; for (i = 1; i < numCellPts; i++) { tempScalar = scalarArrayPtr[cellArrayPtr[cellArrayIt]]; cellArrayIt++; if (tempScalar <= range[0]) { range[0] = tempScalar; } // if tempScalar <= min range value if (tempScalar >= range[1]) { range[1] = tempScalar; } // if tempScalar >= max range value } // for all points in this cell int needCell = 0; if (0.0 >= range[0] && 0.0 <= range[1]) { needCell = 1; } if (needCell) { vtkCell *cell = input->GetCell(cellId); cellIds = cell->GetPointIds(); cutScalars->GetTuples(cellIds, cellScalars); // Loop over all contour values. if (dimensionality == 3 && !(++cut % progressInterval)) { vtkDebugMacro(<< "Cutting #" << cut); this->UpdateProgress(static_cast(cut) / numCuts); abortExecute = this->GetAbortExecute(); } this->ContourUnstructuredGridCell( cell, cellScalars, this->Locator, newVerts, newLines, newPolys, inPD, outPD, inCD, cellId, outCD); } // if need cell } // for all cells } // for all dimensions (1,2,3). // Update ourselves. Because we don't know upfront how many verts, lines, // polys we've created, take care to reclaim memory. // cellScalars->Delete(); cutScalars->Delete(); if (this->GenerateCutScalars) { inPD->Delete(); } output->SetPoints(newPoints); newPoints->Delete(); if (newVerts->GetNumberOfCells()) { output->SetVerts(newVerts); } newVerts->Delete(); if (newLines->GetNumberOfCells()) { output->SetLines(newLines); } newLines->Delete(); if (newPolys->GetNumberOfCells()) { output->SetPolys(newPolys); } newPolys->Delete(); this->Locator->Initialize(); // release any extra memory output->Squeeze(); } void vtkPointSetSlicer::ContourUnstructuredGridCell(vtkCell *cell, vtkDataArray *cellScalars, vtkPointLocator *locator, vtkCellArray *verts, vtkCellArray *lines, vtkCellArray *polys, vtkPointData *inPd, vtkPointData *outPd, vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd) { if (cell->GetCellType() == VTK_HEXAHEDRON) { static int CASE_MASK[8] = {1, 2, 4, 8, 16, 32, 64, 128}; POLY_CASES *polyCase; EDGE_LIST *edge; int i, j, index, *vert; volatile int pnum; int v1, v2, newCellId; double t, x1[3], x2[3], x[3], deltaScalar; vtkIdType offset = verts->GetNumberOfCells() + lines->GetNumberOfCells(); // Build the case table for (i = 0, index = 0; i < 8; i++) { if (cellScalars->GetComponent(i, 0) >= 0) { index |= CASE_MASK[i]; } } polyCase = polyCases + index; edge = polyCase->edges; // get the point number of the polygon pnum = 0; for (i = 0; i < 8; i++) if (edge[i] > -1) pnum++; else break; vtkIdType *pts = new vtkIdType[pnum]; for (i = 0; i < pnum; i++) // insert polygon { vert = edges[edge[i]]; // calculate a preferred interpolation direction deltaScalar = (cellScalars->GetComponent(vert[1], 0) - cellScalars->GetComponent(vert[0], 0)); if (deltaScalar > 0) { v1 = vert[0]; v2 = vert[1]; } else { v1 = vert[1]; v2 = vert[0]; deltaScalar = -deltaScalar; } // linear interpolation t = (deltaScalar == 0.0 ? 0.0 : (-cellScalars->GetComponent(v1, 0)) / deltaScalar); cell->GetPoints()->GetPoint(v1, x1); cell->GetPoints()->GetPoint(v2, x2); for (j = 0; j < 3; j++) { x[j] = x1[j] + t * (x2[j] - x1[j]); } if (locator->InsertUniquePoint(x, pts[i])) { if (outPd) { vtkIdType p1 = cell->GetPointIds()->GetId(v1); vtkIdType p2 = cell->GetPointIds()->GetId(v2); outPd->InterpolateEdge(inPd, pts[i], p1, p2, t); } } } // check for degenerate polygon std::vector pset; for (i = 0; i < pnum; i++) { if (std::find(pset.begin(), pset.end(), pts[i]) == pset.end()) pset.push_back(pts[i]); } if (pset.size() > 2) { i = 0; for (std::vector::iterator iter = pset.begin(); iter != pset.end(); iter++) { pts[i] = *iter; i++; } newCellId = offset + polys->InsertNextCell(pset.size(), pts); outCd->CopyData(inCd, cellId, newCellId); } delete[] pts; } else { cell->Contour(0, cellScalars, locator, verts, lines, polys, inPd, outPd, inCd, cellId, outCd); } } // Specify a spatial locator for merging points. By default, // an instance of vtkMergePoints is used. void vtkPointSetSlicer::SetLocator(vtkPointLocator *locator) { if (this->Locator == locator) { return; } if (this->Locator) { this->Locator->UnRegister(this); this->Locator = 0; } if (locator) { locator->Register(this); } this->Locator = locator; this->Modified(); } void vtkPointSetSlicer::CreateDefaultLocator() { if (this->Locator == 0) { this->Locator = vtkMergePoints::New(); this->Locator->Register(this); this->Locator->Delete(); } } void vtkPointSetSlicer::PrintSelf(std::ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Slice Plane: " << this->SlicePlane << "\n"; if (this->Locator) { os << indent << "Locator: " << this->Locator << "\n"; } else { os << indent << "Locator: (none)\n"; } os << indent << "Generate Cut Scalars: " << (this->GenerateCutScalars ? "On\n" : "Off\n"); } int vtkPointSetSlicer::edges[12][2] = { {0, 1}, {1, 2}, {3, 2}, {0, 3}, {4, 5}, {5, 6}, {7, 6}, {4, 7}, {0, 4}, {1, 5}, {2, 6}, {3, 7}}; vtkPointSetSlicer::POLY_CASES vtkPointSetSlicer::polyCases[256] = { {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{0, 3, 8, -1, -1, -1, -1, -1}}, {{1, 0, 9, -1, -1, -1, -1, -1}}, {{1, 3, 8, 9, -1, -1, -1, -1}}, {{2, 1, 10, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{2, 0, 9, 10, -1, -1, -1, -1}}, {{2, 10, 9, 8, 3, -1, -1, -1}}, {{3, 2, 11, -1, -1, -1, -1, -1}}, {{0, 2, 11, 8, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{1, 9, 8, 11, 2, -1, -1, -1}}, {{3, 1, 10, 11, -1, -1, -1, -1}}, {{0, 8, 11, 10, 1, -1, -1, -1}}, {{3, 11, 10, 9, 0, -1, -1, -1}}, {{8, 9, 10, 11, -1, -1, -1, -1}}, {{4, 7, 8, -1, -1, -1, -1, -1}}, {{3, 7, 4, 0, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{9, 1, 3, 7, 4, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{11, 2, 0, 4, 7, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{1, 2, 11, 7, 4, 9, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{4, 7, 11, 10, 9, -1, -1, -1}}, {{5, 4, 9, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{0, 4, 5, 1, -1, -1, -1, -1}}, {{8, 3, 1, 5, 4, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{10, 2, 0, 4, 5, -1, -1, -1}}, {{2, 3, 8, 4, 5, 10, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{5, 4, 8, 11, 10, -1, -1, -1}}, {{5, 7, 8, 9, -1, -1, -1, -1}}, {{9, 5, 7, 3, 0, -1, -1, -1}}, {{8, 7, 5, 1, 0, -1, -1, -1}}, {{1, 3, 7, 5, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{2, 10, 5, 7, 3, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{2, 11, 7, 5, 1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{5, 7, 11, 10, -1, -1, -1, -1}}, {{6, 5, 10, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{1, 5, 6, 2, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{9, 0, 2, 6, 5, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{11, 3, 1, 5, 6, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{3, 0, 9, 5, 6, 11, -1, -1}}, {{6, 5, 9, 8, 11, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{6, 4, 9, 10, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{10, 6, 4, 0, 1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{9, 4, 6, 2, 1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{2, 0, 4, 6, -1, -1, -1, -1}}, {{3, 8, 4, 6, 2, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{3, 11, 6, 4, 0, -1, -1, -1}}, {{6, 4, 8, 11, -1, -1, -1, -1}}, {{6, 10, 9, 8, 7, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{6, 7, 8, 0, 1, 10, -1, -1}}, {{6, 10, 1, 3, 7, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{7, 8, 0, 2, 6, -1, -1, -1}}, {{2, 6, 7, 3, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{6, 7, 11, -1, -1, -1, -1, -1}}, {{7, 6, 11, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{2, 6, 7, 3, -1, -1, -1, -1}}, {{8, 0, 2, 6, 7, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{10, 1, 3, 7, 6, -1, -1, -1}}, {{0, 1, 10, 6, 7, 8, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{7, 6, 10, 9, 8, -1, -1, -1}}, {{4, 6, 11, 8, -1, -1, -1, -1}}, {{11, 6, 4, 0, 3, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{8, 4, 6, 2, 3, -1, -1, -1}}, {{0, 2, 6, 4, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{1, 9, 4, 6, 2, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{1, 10, 6, 4, 0, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{4, 6, 10, 9, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{5, 9, 8, 11, 6, -1, -1, -1}}, {{5, 6, 11, 3, 0, 9, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{6, 11, 3, 1, 5, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{5, 9, 0, 2, 6, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{1, 5, 6, 2, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{5, 6, 10, -1, -1, -1, -1, -1}}, {{7, 5, 10, 11, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{11, 7, 5, 1, 2, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{10, 5, 7, 3, 2, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{3, 1, 5, 7, -1, -1, -1, -1}}, {{0, 8, 7, 5, 1, -1, -1, -1}}, {{0, 9, 5, 7, 3, -1, -1, -1}}, {{7, 5, 9, 8, -1, -1, -1, -1}}, {{4, 8, 11, 10, 5, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{4, 5, 10, 2, 3, 8, -1, -1}}, {{5, 10, 2, 0, 4, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{4, 8, 3, 1, 5, -1, -1, -1}}, {{0, 4, 5, 1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{4, 5, 9, -1, -1, -1, -1, -1}}, {{7, 11, 10, 9, 4, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{7, 4, 9, 1, 2, 11, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{7, 11, 2, 0, 4, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{4, 9, 1, 3, 7, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{3, 7, 4, 0, -1, -1, -1, -1}}, {{7, 4, 8, -1, -1, -1, -1, -1}}, {{10, 11, 8, 9, -1, -1, -1, -1}}, {{0, 3, 11, 10, 9, -1, -1, -1}}, {{1, 0, 8, 11, 10, -1, -1, -1}}, {{1, 3, 11, 10, -1, -1, -1, -1}}, {{2, 1, 9, 8, 11, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{2, 0, 8, 11, -1, -1, -1, -1}}, {{2, 3, 11, -1, -1, -1, -1, -1}}, {{3, 2, 10, 9, 8, -1, -1, -1}}, {{0, 2, 10, 9, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}, {{1, 2, 10, -1, -1, -1, -1, -1}}, {{3, 1, 9, 8, -1, -1, -1, -1}}, {{0, 1, 9, -1, -1, -1, -1, -1}}, {{3, 0, 8, -1, -1, -1, -1, -1}}, {{-1, -1, -1, -1, -1, -1, -1, -1}}}; diff --git a/Modules/MapperExt/src/vtkPointSetSlicer.h b/Modules/MapperExt/src/vtkPointSetSlicer.h index 4d2abfbc6c..1382347790 100644 --- a/Modules/MapperExt/src/vtkPointSetSlicer.h +++ b/Modules/MapperExt/src/vtkPointSetSlicer.h @@ -1,121 +1,121 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _VTKPOINTSETSLICER_H_ #define _VTKPOINTSETSLICER_H_ #include #include "vtkVersion.h" class vtkCutter; class vtkPlane; class vtkPointLocator; class vtkCell; class vtkDataArray; class vtkCellArray; class vtkPointData; class vtkCellData; #include "mitkCommon.h" #include "vtkPolyDataAlgorithm.h" class vtkPointSetSlicer : public vtkPolyDataAlgorithm { public: vtkTypeMacro(vtkPointSetSlicer, vtkPolyDataAlgorithm); void PrintSelf(std::ostream &os, vtkIndent indent) override; // Description: // Construct with user-specified implicit function; initial value of 0.0; and // generating cut scalars turned off. static vtkPointSetSlicer *New(); // Description: // Override GetMTime because we delegate to vtkContourValues and refer to // vtkImplicitFunction. - unsigned long GetMTime() override; + vtkMTimeType GetMTime() override; // Description // Specify the implicit function to perform the cutting. virtual void SetSlicePlane(vtkPlane *); vtkGetObjectMacro(SlicePlane, vtkPlane); // Description: // If this flag is enabled, then the output scalar values will be // interpolated from the implicit function values, and not the input scalar // data. vtkSetMacro(GenerateCutScalars, int); vtkGetMacro(GenerateCutScalars, int); vtkBooleanMacro(GenerateCutScalars, int); // Description: // Specify a spatial locator for merging points. By default, // an instance of vtkMergePoints is used. void SetLocator(vtkPointLocator *locator); vtkGetObjectMacro(Locator, vtkPointLocator); // Description: // Create default locator. Used to create one when none is specified. The // locator is used to merge coincident points. void CreateDefaultLocator(); protected: vtkPointSetSlicer(vtkPlane *cf = 0); ~vtkPointSetSlicer(); virtual int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *) override; virtual int RequestUpdateExtent(vtkInformation *, vtkInformationVector **, vtkInformationVector *) override; virtual int FillInputPortInformation(int port, vtkInformation *info) override; void UnstructuredGridCutter(vtkDataSet *input, vtkPolyData *output); void ContourUnstructuredGridCell(vtkCell *cell, vtkDataArray *cellScalars, vtkPointLocator *locator, vtkCellArray *verts, vtkCellArray *lines, vtkCellArray *polys, vtkPointData *inPd, vtkPointData *outPd, vtkCellData *inCd, vtkIdType cellId, vtkCellData *outCd); vtkPlane *SlicePlane; vtkCutter *Cutter; vtkPointLocator *Locator; int GenerateCutScalars; private: vtkPointSetSlicer(const vtkPointSetSlicer &); // Not implemented. void operator=(const vtkPointSetSlicer &); // Not implemented. static int edges[12][2]; typedef int EDGE_LIST; typedef struct { EDGE_LIST edges[8]; } POLY_CASES; static POLY_CASES polyCases[256]; }; #endif /* _VTKPOINTSETSLICER_H_ */ diff --git a/Modules/MapperExt/src/vtkUnstructuredGridMapper.cpp b/Modules/MapperExt/src/vtkUnstructuredGridMapper.cpp index c8ba584b54..27fff10ce5 100644 --- a/Modules/MapperExt/src/vtkUnstructuredGridMapper.cpp +++ b/Modules/MapperExt/src/vtkUnstructuredGridMapper.cpp @@ -1,223 +1,223 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "vtkUnstructuredGridMapper.h" #include "vtkExecutive.h" #include "vtkGarbageCollector.h" #include "vtkGeometryFilter.h" #include "vtkInformation.h" #include "vtkObjectFactory.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkScalarsToColors.h" #include "vtkUnstructuredGrid.h" vtkStandardNewMacro(vtkUnstructuredGridMapper); //---------------------------------------------------------------------------- vtkUnstructuredGridMapper::vtkUnstructuredGridMapper() { this->GeometryExtractor = 0; this->PolyDataMapper = 0; } //---------------------------------------------------------------------------- vtkUnstructuredGridMapper::~vtkUnstructuredGridMapper() { // delete internally created objects. if (this->GeometryExtractor) { this->GeometryExtractor->Delete(); } if (this->PolyDataMapper) { this->PolyDataMapper->Delete(); } } void vtkUnstructuredGridMapper::SetBoundingObject(mitk::BoundingObject *bo) { m_BoundingObject = bo; } //---------------------------------------------------------------------------- void vtkUnstructuredGridMapper::SetInput(vtkUnstructuredGrid *input) { this->SetInputDataObject(input); } //---------------------------------------------------------------------------- vtkUnstructuredGrid *vtkUnstructuredGridMapper::GetInput() { // return this->Superclass::GetInputAsDataSet(); return vtkUnstructuredGrid::SafeDownCast(this->GetExecutive()->GetInputData(0, 0)); } //---------------------------------------------------------------------------- void vtkUnstructuredGridMapper::ReleaseGraphicsResources(vtkWindow *renWin) { if (this->PolyDataMapper) { this->PolyDataMapper->ReleaseGraphicsResources(renWin); } } //---------------------------------------------------------------------------- void vtkUnstructuredGridMapper::ReleaseGraphicsResources(mitk::BaseRenderer *renderer) { if (this->PolyDataMapper) { this->PolyDataMapper->ReleaseGraphicsResources(renderer->GetVtkRenderer()->GetRenderWindow()); } } //---------------------------------------------------------------------------- // Receives from Actor -> maps data to primitives // void vtkUnstructuredGridMapper::Render(vtkRenderer *ren, vtkActor *act) { // make sure that we've been properly initialized // if (!this->GetInput()) { vtkErrorMacro(<< "No input!\n"); return; } // Need a lookup table // if (this->LookupTable == 0) { this->CreateDefaultLookupTable(); } this->LookupTable->Build(); // Now can create appropriate mapper // if (this->PolyDataMapper == 0) { vtkGeometryFilter *gf = vtkGeometryFilter::New(); vtkPolyDataMapper *pm = vtkPolyDataMapper::New(); pm->SetInputConnection(gf->GetOutputPort()); this->GeometryExtractor = gf; this->PolyDataMapper = pm; } // share clipping planes with the PolyDataMapper // if (this->ClippingPlanes != this->PolyDataMapper->GetClippingPlanes()) { this->PolyDataMapper->SetClippingPlanes(this->ClippingPlanes); } if (this->m_BoundingObject) { mitk::BoundingBox::BoundsArrayType bounds = this->m_BoundingObject->GetGeometry()->CalculateBoundingBoxRelativeToTransform(0)->GetBounds(); this->GeometryExtractor->SetExtent(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5]); this->GeometryExtractor->ExtentClippingOn(); } else { this->GeometryExtractor->ExtentClippingOff(); } this->GeometryExtractor->SetInputData(this->GetInput()); this->PolyDataMapper->SetInputConnection(this->GeometryExtractor->GetOutputPort()); // update ourselves in case something has changed this->PolyDataMapper->SetLookupTable(this->GetLookupTable()); this->PolyDataMapper->SetScalarVisibility(this->GetScalarVisibility()); this->PolyDataMapper->SetUseLookupTableScalarRange(this->GetUseLookupTableScalarRange()); this->PolyDataMapper->SetScalarRange(this->GetScalarRange()); this->PolyDataMapper->SetImmediateModeRendering(this->GetImmediateModeRendering()); this->PolyDataMapper->SetColorMode(this->GetColorMode()); this->PolyDataMapper->SetInterpolateScalarsBeforeMapping(this->GetInterpolateScalarsBeforeMapping()); this->PolyDataMapper->SetScalarMode(this->GetScalarMode()); if (this->ScalarMode == VTK_SCALAR_MODE_USE_POINT_FIELD_DATA || this->ScalarMode == VTK_SCALAR_MODE_USE_CELL_FIELD_DATA) { if (this->ArrayAccessMode == VTK_GET_ARRAY_BY_ID) { this->PolyDataMapper->ColorByArrayComponent(this->ArrayId, ArrayComponent); } else { this->PolyDataMapper->ColorByArrayComponent(this->ArrayName, ArrayComponent); } } this->PolyDataMapper->Render(ren, act); this->TimeToDraw = this->PolyDataMapper->GetTimeToDraw(); } //---------------------------------------------------------------------------- void vtkUnstructuredGridMapper::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); if (this->PolyDataMapper) { os << indent << "Poly Mapper: (" << this->PolyDataMapper << ")\n"; } else { os << indent << "Poly Mapper: (none)\n"; } if (this->GeometryExtractor) { os << indent << "Geometry Extractor: (" << this->GeometryExtractor << ")\n"; } else { os << indent << "Geometry Extractor: (none)\n"; } } //---------------------------------------------------------------------------- -unsigned long vtkUnstructuredGridMapper::GetMTime() +vtkMTimeType vtkUnstructuredGridMapper::GetMTime() { - unsigned long mTime = this->vtkMapper::GetMTime(); - unsigned long time; + vtkMTimeType mTime = this->vtkMapper::GetMTime(); + vtkMTimeType time; if (this->LookupTable != nullptr) { time = this->LookupTable->GetMTime(); mTime = (time > mTime ? time : mTime); } return mTime; } //---------------------------------------------------------------------------- int vtkUnstructuredGridMapper::FillInputPortInformation(int vtkNotUsed(port), vtkInformation *info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkUnstructuredGrid"); return 1; } //---------------------------------------------------------------------------- void vtkUnstructuredGridMapper::ReportReferences(vtkGarbageCollector *collector) { this->Superclass::ReportReferences(collector); // These filters share our input and are therefore involved in a // reference loop. vtkGarbageCollectorReport(collector, this->GeometryExtractor, "GeometryExtractor"); vtkGarbageCollectorReport(collector, this->PolyDataMapper, "PolyDataMapper"); } diff --git a/Modules/ModuleList.cmake b/Modules/ModuleList.cmake index 3197835d83..36a97fe6a3 100644 --- a/Modules/ModuleList.cmake +++ b/Modules/ModuleList.cmake @@ -1,82 +1,80 @@ # The entries in the mitk_modules list must be # ordered according to their dependencies. set(mitk_modules Core CommandLine AppUtil DCMTesting RDF LegacyIO DataTypesExt Annotation LegacyGL AlgorithmsExt MapperExt DICOMReader DICOMReaderServices DICOMTesting SceneSerializationBase PlanarFigure ImageDenoising ImageExtraction SceneSerialization Gizmo GraphAlgorithms Multilabel ImageStatistics ContourModel SurfaceInterpolation Segmentation PlanarFigureSegmentation OpenViewCore QtWidgets QtWidgetsExt Chart QmlItems SegmentationUI Classification DiffusionImaging GPGPU OpenIGTLink IGTBase IGT CameraCalibration OpenCL OpenCVVideoSupport QtOverlays ToFHardware ToFProcessing ToFUI PhotoacousticsHardware PhotoacousticsAlgorithms US USUI DicomUI - Simulation Remeshing Python QtPython Persistence OpenIGTLinkUI IGTUI - VtkShaders DicomRT RTUI IOExt XNAT TubeGraph BiophotonicsHardware TumorInvasionAnalysis MatchPointRegistration MatchPointRegistrationUI BoundingShape RenderWindowManager RenderWindowManagerUI CEST DICOMQI ) if(MITK_ENABLE_PIC_READER) list(APPEND mitk_modules IpPicSupportIO) endif() diff --git a/Modules/OpenViewCore/QVTKQuickItem.cxx b/Modules/OpenViewCore/QVTKQuickItem.cxx new file mode 100644 index 0000000000..d08007fdce --- /dev/null +++ b/Modules/OpenViewCore/QVTKQuickItem.cxx @@ -0,0 +1,374 @@ +/*======================================================================== + OpenView -- http://openview.kitware.com + + Copyright 2012 Kitware, Inc. + + Licensed under the BSD license. See LICENSE file for details. + ========================================================================*/ +#include "QVTKQuickItem.h" +#include + +#include +#include +#include +#include +#include +#include + +#include "QVTKInteractor.h" +#include "QVTKInteractorAdapter.h" +#include "vtkGenericOpenGLRenderWindow.h" +#include "vtkEventQtSlotConnect.h" +#include "vtkRenderer.h" +#include "vtkRendererCollection.h" + +#include "vtkCubeSource.h" +#include "vtkPolyDataMapper.h" +#include "vtkProperty.h" + +#include + +QVTKQuickItem::QVTKQuickItem(QQuickItem* parent) +:QQuickItem(parent) +,m_InitCalledOnce(false) +{ + setFlag(ItemHasContents); + setAcceptHoverEvents(true); + setAcceptedMouseButtons(Qt::LeftButton | Qt::MiddleButton | Qt::RightButton); + + m_interactor = vtkSmartPointer::New(); + m_interactorAdapter = new QVTKInteractorAdapter(NULL); + m_interactorAdapter->moveToThread(this->thread()); + m_interactorAdapter->setParent(this); + m_connect = vtkSmartPointer::New(); + //m_connect->Connect(m_interactor, vtkCommand::RenderEvent, this, SLOT(paint())); + vtkSmartPointer win = vtkSmartPointer::New(); + this->SetRenderWindow(win); + this->geometryChanged(QRectF(x(), y(), width(), height()), QRectF(0, 0, 100, 100)); +} + +QVTKQuickItem::~QVTKQuickItem() +{ + this->SetRenderWindow(0); +} + +void QVTKQuickItem::SetRenderWindow(vtkGenericOpenGLRenderWindow* win) +{ + if(m_win) + { + m_win->SetMapped(0); + //m_connect->Disconnect(m_win, vtkCommand::StartEvent, this, SLOT(Start())); + //m_connect->Disconnect(m_win, vtkCommand::WindowMakeCurrentEvent, this, SLOT(MakeCurrent())); + //m_connect->Disconnect(m_win, vtkCommand::EndEvent, this, SLOT(End())); + //m_connect->Disconnect(m_win, vtkCommand::WindowFrameEvent, this, SLOT(Update())); + m_connect->Disconnect(m_win, vtkCommand::WindowIsCurrentEvent, this, SLOT(IsCurrent(vtkObject*, unsigned long, void*, void*))); + m_connect->Disconnect(m_win, vtkCommand::WindowIsDirectEvent, this, SLOT(IsDirect(vtkObject*, unsigned long, void*, void*))); + m_connect->Disconnect(m_win, vtkCommand::WindowSupportsOpenGLEvent, this, SLOT(SupportsOpenGL(vtkObject*, unsigned long, void*, void*))); + } + + m_interactor->SetRenderWindow(win); + m_win = win; + m_interactor->Initialize(); + + if(m_win) + { + m_win->SetMapped(1); + m_win->SetDoubleBuffer(0); + m_win->SetFrontBuffer(COLOR_ATTACHMENT0_EXT); + m_win->SetFrontLeftBuffer(vtkgl::COLOR_ATTACHMENT0_EXT); + m_win->SetBackBuffer(vtkgl::COLOR_ATTACHMENT0_EXT); + m_win->SetBackLeftBuffer(vtkgl::COLOR_ATTACHMENT0_EXT); + + //m_connect->Connect(m_win, vtkCommand::StartEvent, this, SLOT(Start())); + //m_connect->Connect(m_win, vtkCommand::WindowMakeCurrentEvent, this, SLOT(MakeCurrent())); + //m_connect->Connect(m_win, vtkCommand::EndEvent, this, SLOT(End())); + //m_connect->Connect(m_win, vtkCommand::WindowFrameEvent, this, SLOT(Update())); + // Qt::DirectConnection in order to execute callback immediately. + // This avoids an error when vtkTexture attempts to query driver features and it is unable to determine "IsCurrent" + m_connect->Connect(m_win, vtkCommand::WindowIsCurrentEvent, this, SLOT(IsCurrent(vtkObject*, unsigned long, void*, void*)), NULL, 0.0, Qt::DirectConnection); + m_connect->Connect(m_win, vtkCommand::WindowIsDirectEvent, this, SLOT(IsDirect(vtkObject*, unsigned long, void*, void*)), NULL, 0.0, Qt::DirectConnection); + m_connect->Connect(m_win, vtkCommand::WindowSupportsOpenGLEvent, this, SLOT(SupportsOpenGL(vtkObject*, unsigned long, void*, void*)), NULL, 0.0, Qt::DirectConnection); + } +} + +vtkGenericOpenGLRenderWindow* QVTKQuickItem::GetRenderWindow() const +{ + return m_win; +} + +QVTKInteractor* QVTKQuickItem::GetInteractor() const +{ + return m_interactor; +} + +void QVTKQuickItem::itemChange(ItemChange change, const ItemChangeData &) +{ + // The ItemSceneChange event is sent when we are first attached to a canvas. + if (change == ItemSceneChange) { + QQuickWindow *c = window(); + if (!c) + { + return; + } + + // Connect our the beforeRendering signal to our paint function. + // Since this call is executed on the rendering thread it must be + // a Qt::DirectConnection + connect(c, SIGNAL(beforeRendering()), this, SLOT(paint()), Qt::DirectConnection); + + // If we allow QML to do the clearing, they would clear what we paint + // and nothing would show. + c->setClearBeforeRendering(false); + } +} + +void QVTKQuickItem::MakeCurrent() +{ + if (!this->window()) + { + m_win->SetAbortRender(1); + cerr << "Could not make current since there is no canvas!" << endl; + return; + } + if (QThread::currentThread() != this->window()->openglContext()->thread()) + { + m_win->SetAbortRender(1); + cerr << "Could not make current since we are on the wrong thread!" << endl; + return; + } + this->window()->openglContext()->makeCurrent(this->window()); +} + +void QVTKQuickItem::Start() +{ + MakeCurrent(); + + if (!m_win->GetAbortRender()) + { + m_win->PushState(); + m_win->OpenGLInitState(); + } +} + +void QVTKQuickItem::End() +{ + if (!m_win->GetAbortRender()) + { + m_win->PopState(); + } + +} + +void QVTKQuickItem::IsCurrent(vtkObject*, unsigned long, void*, void* call_data) +{ + bool* ptr = reinterpret_cast(call_data); + *ptr = QOpenGLContext::currentContext() == this->window()->openglContext(); +} + +void QVTKQuickItem::IsDirect(vtkObject*, unsigned long, void*, void* call_data) +{ + int* ptr = reinterpret_cast(call_data); + *ptr = 1; +} + +void QVTKQuickItem::SupportsOpenGL(vtkObject*, unsigned long, void*, void* call_data) +{ + int* ptr = reinterpret_cast(call_data); + *ptr = true; + //*ptr = QGLFormat::hasOpenGL(); +} + +void QVTKQuickItem::geometryChanged(const QRectF & newGeometry, const QRectF & oldGeometry) +{ + QQuickItem::geometryChanged(newGeometry, oldGeometry); + QSize oldSize(oldGeometry.width(), oldGeometry.height()); + QSize newSize(newGeometry.width(), newGeometry.height()); + QResizeEvent e(newSize, oldSize); + if (m_interactorAdapter) + { + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(&e, m_interactor); + this->m_viewLock.unlock(); + } + if(m_win.GetPointer() && window()) + { + this->m_viewLock.lock(); + m_win->SetSize(window()->width(), window()->height()); + QPointF origin = mapToScene(QPointF(0, 0)); + QPointF minPt(origin.x()/window()->width(), (window()->height() - origin.y() - height())/window()->height()); + QPointF maxPt(minPt.x() + width()/window()->width(), minPt.y() + height()/window()->height()); + if (m_win->GetRenderers()->GetFirstRenderer()) + { + m_win->GetRenderers()->GetFirstRenderer()->SetViewport(minPt.x(), minPt.y(), maxPt.x(), maxPt.y()); + } + this->m_viewLock.unlock(); + update(); + } +} + +void QVTKQuickItem::keyPressEvent(QKeyEvent* e) +{ + e->accept(); + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(e, m_interactor); + this->m_viewLock.unlock(); + update(); +} + +void QVTKQuickItem::keyReleaseEvent(QKeyEvent* e) +{ + e->accept(); + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(e, m_interactor); + this->m_viewLock.unlock(); + update(); +} + +void QVTKQuickItem::mousePressEvent(QMouseEvent* e) +{ + e->accept(); + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(e, m_interactor); + this->m_viewLock.unlock(); + update(); +} + +void QVTKQuickItem::mouseReleaseEvent(QMouseEvent* e) +{ + e->accept(); + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(e, m_interactor); + this->m_viewLock.unlock(); + update(); +} + +void QVTKQuickItem::mouseDoubleClickEvent(QMouseEvent* e) +{ + e->accept(); + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(e, m_interactor); + this->m_viewLock.unlock(); + update(); +} + +void QVTKQuickItem::mouseMoveEvent(QMouseEvent* e) +{ + e->accept(); + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(e, m_interactor); + this->m_viewLock.unlock(); + update(); +} + +void QVTKQuickItem::wheelEvent(QWheelEvent* e) +{ + e->accept(); + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(e, m_interactor); + this->m_viewLock.unlock(); + update(); +} + +void QVTKQuickItem::hoverEnterEvent(QHoverEvent* e) +{ + e->accept(); + QEvent e2(QEvent::Enter); + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(&e2, m_interactor); + this->m_viewLock.unlock(); + update(); +} + +void QVTKQuickItem::hoverLeaveEvent(QHoverEvent* e) +{ + e->accept(); + QEvent e2(QEvent::Leave); + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(&e2, m_interactor); + this->m_viewLock.unlock(); + update(); +} + +void QVTKQuickItem::hoverMoveEvent(QHoverEvent* e) +{ + e->accept(); + QMouseEvent e2(QEvent::MouseMove, e->pos(), Qt::NoButton, Qt::NoButton, e->modifiers()); + this->m_viewLock.lock(); + m_interactorAdapter->ProcessEvent(&e2, m_interactor); + this->m_viewLock.unlock(); + update(); +} + +void QVTKQuickItem::init() +{ +} + +void QVTKQuickItem::prepareForRender() +{ +} + +void QVTKQuickItem::cleanupAfterRender() +{ +} + +QSGNode* QVTKQuickItem::updatePaintNode(QSGNode* oldNode, UpdatePaintNodeData*) +{ + QSGSimpleRectNode *n = static_cast(oldNode); + if (!n) { + n = new QSGSimpleRectNode(); + } + n->markDirty(QSGNode::DirtyForceUpdate); + return n; +} + + +void QVTKQuickItem::paint() +{ + if (!this->isVisible()) + { + return; + } + + if (!this->m_InitCalledOnce) + { + m_win->GetExtensionManager()->LoadExtension("GL_VERSION_1_4"); + m_win->GetExtensionManager()->LoadExtension("GL_VERSION_2_0"); + + init(); + + this->m_InitCalledOnce = true; + } + + this->m_viewLock.lock(); + + // Let subclasses do something each render + prepareForRender(); + + // Make sure viewport is up to date. + // This is needed because geometryChanged() is not called when parent geometry changes, so we miss when widths/heights + // of surrounding elements change. + m_win->SetSize(window()->width(), window()->height()); + QPointF origin = mapToScene(QPointF(0, 0)); + QPointF minPt(origin.x()/window()->width(), (window()->height() - origin.y() - height())/window()->height()); + QPointF maxPt(minPt.x() + width()/window()->width(), minPt.y() + height()/window()->height()); + if (m_win->GetRenderers()->GetFirstRenderer()) + { + m_win->GetRenderers()->GetFirstRenderer()->SetViewport(minPt.x(), minPt.y(), maxPt.x(), maxPt.y()); + } + + // Turn off any QML shader program + vtkgl::UseProgram(0); + + // Set blending correctly + glEnable(GL_BLEND); + vtkgl::BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); + + m_win->Render(); + + // Disable alpha test for QML + glDisable(GL_ALPHA_TEST); + + cleanupAfterRender(); + + this->m_viewLock.unlock(); +} diff --git a/Modules/OpenViewCore/src/QVTKFramebufferObjectRenderer.cxx b/Modules/OpenViewCore/src/QVTKFramebufferObjectRenderer.cxx index 0129eec775..664ae6dc0f 100644 --- a/Modules/OpenViewCore/src/QVTKFramebufferObjectRenderer.cxx +++ b/Modules/OpenViewCore/src/QVTKFramebufferObjectRenderer.cxx @@ -1,98 +1,94 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "vtkInternalOpenGLRenderWindow.h" #include "QVTKFramebufferObjectRenderer.h" -#include - -#include - #include #include #include #include #include #include #include #include #include #include #include #include #include QVTKFramebufferObjectRenderer::QVTKFramebufferObjectRenderer(vtkInternalOpenGLRenderWindow *rw) : m_vtkRenderWindow(rw), m_neverRendered(true), m_readyToRender(false) { m_vtkRenderWindow->Register(NULL); m_vtkRenderWindow->QtParentRenderer = this; } QOpenGLFramebufferObject* QVTKFramebufferObjectRenderer::createFramebufferObject(const QSize &size) { QOpenGLFramebufferObjectFormat format; format.setAttachment(QOpenGLFramebufferObject::Depth); format.setTextureTarget(GL_TEXTURE_2D); format.setInternalTextureFormat(GL_RGBA32F_ARB); QOpenGLFramebufferObject* fbo = new QOpenGLFramebufferObject(size, format); m_vtkRenderWindow->SetFramebufferObject(fbo); return fbo; } void QVTKFramebufferObjectRenderer::render() { if (!m_readyToRender) { return; } // Ask VTK to render to OpenGL m_vtkQuickItem->m_viewLock.lock(); m_vtkRenderWindow->PushState(); m_vtkRenderWindow->OpenGLInitState(); m_vtkRenderWindow->InternalRender(); m_vtkRenderWindow->OpenGLEndState(); m_vtkRenderWindow->PopState(); m_vtkQuickItem->m_viewLock.unlock(); } void QVTKFramebufferObjectRenderer::synchronize(QQuickFramebufferObject * item) { m_vtkQuickItem = static_cast(item); if (m_neverRendered) { m_neverRendered = false; m_vtkQuickItem->init(); } // Execute events (that might call VTK picking to obtain z coordinates) // while UI and rendering are synchronized. m_vtkQuickItem->processPendingEvents(); // Update MITK mapper list, then mapper outputs m_readyToRender = m_vtkQuickItem->prepareForRender(); } QVTKFramebufferObjectRenderer::~QVTKFramebufferObjectRenderer() { m_vtkRenderWindow->QtParentRenderer = 0; m_vtkRenderWindow->Delete(); } diff --git a/Modules/OpenViewCore/src/QVTKQuickItem.cxx b/Modules/OpenViewCore/src/QVTKQuickItem.cxx index 7862f6bb2e..c78edae1ec 100644 --- a/Modules/OpenViewCore/src/QVTKQuickItem.cxx +++ b/Modules/OpenViewCore/src/QVTKQuickItem.cxx @@ -1,257 +1,255 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // original copyright below /*======================================================================== OpenView -- http://openview.kitware.com Copyright 2012 Kitware, Inc. Licensed under the BSD license. See LICENSE file for details. ========================================================================*/ #include "QVTKQuickItem.h" #include #include #include #include #include #include "QVTKInteractor.h" #include "QVTKMitkInteractorAdapter.h" #include "vtkGenericOpenGLRenderWindow.h" #include "vtkEventQtSlotConnect.h" -#include "vtkgl.h" -#include "vtkOpenGLExtensionManager.h" #include "vtkRenderer.h" #include "vtkRendererCollection.h" #include "vtkCubeSource.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" -#include +#include #include "vtkInternalOpenGLRenderWindow.h" #include "QVTKFramebufferObjectRenderer.h" QVTKQuickItem::QVTKQuickItem(QQuickItem* parent) : QQuickFramebufferObject(parent) { setAcceptHoverEvents(true); setAcceptedMouseButtons(Qt::LeftButton | Qt::MiddleButton | Qt::RightButton); m_interactor = vtkSmartPointer::New(); m_interactorAdapter = new QVTKMitkInteractorAdapter(this); m_connect = vtkSmartPointer::New(); m_win = vtkInternalOpenGLRenderWindow::New(); m_interactor->SetRenderWindow(m_win); m_connect->Connect(m_win, vtkCommand::WindowIsCurrentEvent, this, SLOT(IsCurrent(vtkObject*, unsigned long, void*, void*)), NULL, 0.0, Qt::DirectConnection); m_connect->Connect(m_win, vtkCommand::WindowIsDirectEvent, this, SLOT(IsDirect(vtkObject*, unsigned long, void*, void*)), NULL, 0.0, Qt::DirectConnection); m_connect->Connect(m_win, vtkCommand::WindowSupportsOpenGLEvent, this, SLOT(SupportsOpenGL(vtkObject*, unsigned long, void*, void*)), NULL, 0.0, Qt::DirectConnection); connect(this, SIGNAL(textureFollowsItemSizeChanged(bool)), this, SLOT(onTextureFollowsItemSizeChanged(bool))); } QVTKQuickItem::~QVTKQuickItem() { if(m_win) { m_connect->Disconnect(m_win, vtkCommand::WindowIsCurrentEvent, this, SLOT(IsCurrent(vtkObject*, unsigned long, void*, void*))); m_connect->Disconnect(m_win, vtkCommand::WindowIsDirectEvent, this, SLOT(IsDirect(vtkObject*, unsigned long, void*, void*))); m_connect->Disconnect(m_win, vtkCommand::WindowSupportsOpenGLEvent, this, SLOT(SupportsOpenGL(vtkObject*, unsigned long, void*, void*))); m_win->Delete(); } } QSGNode* QVTKQuickItem::updatePaintNode(QSGNode *node, QQuickItem::UpdatePaintNodeData *nodeData) { node = QQuickFramebufferObject::updatePaintNode(node, nodeData); if ( node != nullptr ) { QSGSimpleTextureNode* texNode = static_cast(node); texNode->setTextureCoordinatesTransform(QSGSimpleTextureNode::MirrorVertically); } return node; } QQuickFramebufferObject::Renderer* QVTKQuickItem::createRenderer() const { return new QVTKFramebufferObjectRenderer(static_cast(m_win)); } vtkOpenGLRenderWindow* QVTKQuickItem::GetRenderWindow() const { return m_win; } QVTKInteractor* QVTKQuickItem::GetInteractor() const { return m_interactor; } void QVTKQuickItem::IsCurrent(vtkObject*, unsigned long, void*, void* call_data) { bool* ptr = reinterpret_cast(call_data); *ptr = QOpenGLContext::currentContext() == this->window()->openglContext(); } void QVTKQuickItem::IsDirect(vtkObject*, unsigned long, void*, void* call_data) { int* ptr = reinterpret_cast(call_data); *ptr = 1; } void QVTKQuickItem::SupportsOpenGL(vtkObject*, unsigned long, void*, void* call_data) { int* ptr = reinterpret_cast(call_data); *ptr = 1; } void QVTKQuickItem::onTextureFollowsItemSizeChanged(bool follows) { if (!follows) { qWarning("QVTKQuickItem: Mouse interaction is not (yet) supported when textureFollowsItemSize==false"); } } void QVTKQuickItem::geometryChanged(const QRectF & newGeometry, const QRectF & oldGeometry) { QQuickFramebufferObject::geometryChanged(newGeometry, oldGeometry); QSize oldSize(oldGeometry.width(), oldGeometry.height()); QSize newSize(newGeometry.width(), newGeometry.height()); QResizeEvent e(newSize, oldSize); if (m_interactorAdapter) { this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(&e, m_interactor); this->m_viewLock.unlock(); } } void QVTKQuickItem::keyPressEvent(QKeyEvent* e) { e->accept(); this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(e, m_interactor); this->m_viewLock.unlock(); update(); } void QVTKQuickItem::keyReleaseEvent(QKeyEvent* e) { e->accept(); this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(e, m_interactor); this->m_viewLock.unlock(); update(); } void QVTKQuickItem::mousePressEvent(QMouseEvent* e) { e->accept(); this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(e, m_interactor); this->m_viewLock.unlock(); update(); } void QVTKQuickItem::mouseReleaseEvent(QMouseEvent* e) { e->accept(); this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(e, m_interactor); this->m_viewLock.unlock(); update(); } void QVTKQuickItem::mouseDoubleClickEvent(QMouseEvent* e) { e->accept(); this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(e, m_interactor); this->m_viewLock.unlock(); update(); } void QVTKQuickItem::mouseMoveEvent(QMouseEvent* e) { e->accept(); this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(e, m_interactor); this->m_viewLock.unlock(); update(); } void QVTKQuickItem::wheelEvent(QWheelEvent* e) { e->accept(); this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(e, m_interactor); this->m_viewLock.unlock(); update(); } void QVTKQuickItem::hoverEnterEvent(QHoverEvent* e) { e->accept(); QEvent e2(QEvent::Enter); this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(&e2, m_interactor); this->m_viewLock.unlock(); update(); } void QVTKQuickItem::hoverLeaveEvent(QHoverEvent* e) { e->accept(); QEvent e2(QEvent::Leave); this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(&e2, m_interactor); this->m_viewLock.unlock(); update(); } void QVTKQuickItem::hoverMoveEvent(QHoverEvent* e) { e->accept(); QMouseEvent e2(QEvent::MouseMove, e->pos(), Qt::NoButton, Qt::NoButton, e->modifiers()); this->m_viewLock.lock(); m_interactorAdapter->ProcessEvent(&e2, m_interactor); this->m_viewLock.unlock(); update(); } void QVTKQuickItem::init() { m_win->OpenGLInitContext(); - m_win->GetExtensionManager()->LoadExtension("GL_VERSION_1_4"); - m_win->GetExtensionManager()->LoadExtension("GL_VERSION_2_0"); +// m_win->GetExtensionManager()->LoadExtension("GL_VERSION_1_4"); +// m_win->GetExtensionManager()->LoadExtension("GL_VERSION_2_0"); } bool QVTKQuickItem::prepareForRender() { return true; } void QVTKQuickItem::cleanupAfterRender() { } diff --git a/Modules/OpenViewCore/src/vtkInternalOpenGLRenderWindow.cxx b/Modules/OpenViewCore/src/vtkInternalOpenGLRenderWindow.cxx index 39e0a384d7..d6d5ac4b1a 100644 --- a/Modules/OpenViewCore/src/vtkInternalOpenGLRenderWindow.cxx +++ b/Modules/OpenViewCore/src/vtkInternalOpenGLRenderWindow.cxx @@ -1,83 +1,80 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ +#include "vtk_glew.h" #include "vtkInternalOpenGLRenderWindow.h" - #include "QVTKFramebufferObjectRenderer.h" -#include #include vtkStandardNewMacro(vtkInternalOpenGLRenderWindow); vtkInternalOpenGLRenderWindow::~vtkInternalOpenGLRenderWindow() { this->OffScreenRendering = false; } vtkInternalOpenGLRenderWindow::vtkInternalOpenGLRenderWindow() : QtParentRenderer(0) { } void vtkInternalOpenGLRenderWindow::InternalRender() { Superclass::Render(); } void vtkInternalOpenGLRenderWindow::OpenGLEndState() { glDepthMask(GL_TRUE); } void vtkInternalOpenGLRenderWindow::OpenGLInitState() { Superclass::OpenGLInitState(); - vtkgl::UseProgram(0); - +// vtkgl::UseProgram(0); TODO18922 glEnable(GL_BLEND); glHint(GL_CLIP_VOLUME_CLIPPING_HINT_EXT, GL_FASTEST); glDepthMask(GL_TRUE); } void vtkInternalOpenGLRenderWindow::Render() { if (this->QtParentRenderer) { this->QtParentRenderer->update(); } } void vtkInternalOpenGLRenderWindow::SetFramebufferObject(QOpenGLFramebufferObject *fbo) { - this->SetFrontBuffer(vtkgl::COLOR_ATTACHMENT0); - // Why all those buffers, too?? - this->SetFrontRightBuffer(vtkgl::COLOR_ATTACHMENT0); - this->SetBackLeftBuffer(vtkgl::COLOR_ATTACHMENT0); - this->SetBackRightBuffer(vtkgl::COLOR_ATTACHMENT0); + this->SetFrontBuffer(GL_COLOR_ATTACHMENT0); + this->SetFrontLeftBuffer(GL_COLOR_ATTACHMENT0); + this->SetBackBuffer(GL_COLOR_ATTACHMENT0); + this->SetBackLeftBuffer(GL_COLOR_ATTACHMENT0); QSize fboSize = fbo->size(); this->SetSize(fboSize.width(), fboSize.height()); this->NumberOfFrameBuffers = 1; this->FrameBufferObject = static_cast(fbo->handle()); this->DepthRenderBufferObject = 0; // static_cast(depthRenderBufferObject); this->TextureObjects[0] = static_cast(fbo->texture()); this->OffScreenRendering = true; this->OffScreenUseFrameBuffer = true; this->Modified(); } diff --git a/Modules/PlanarFigure/include/mitkPlanarFigureMapper2D.h b/Modules/PlanarFigure/include/mitkPlanarFigureMapper2D.h index 7d4d75f003..3b3d7fa55f 100644 --- a/Modules/PlanarFigure/include/mitkPlanarFigureMapper2D.h +++ b/Modules/PlanarFigure/include/mitkPlanarFigureMapper2D.h @@ -1,307 +1,320 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITK_PLANAR_FIGURE_MAPPER_2D_H_ #define MITK_PLANAR_FIGURE_MAPPER_2D_H_ #include "mitkCommon.h" -#include "mitkGLMapper.h" +#include "mitkMapper.h" #include "mitkPlanarFigure.h" #include "mitkPlanarFigureControlPointStyleProperty.h" #include +#include "vtkNew.h" +#include "vtkPen.h" + +class vtkContext2D; namespace mitk { class BaseRenderer; class Contour; - class TextAnnotation2D; /** * \brief OpenGL-based mapper to render display sub-class instances of mitk::PlanarFigure * * The appearance of planar figures can be configured through properties. If no properties are specified, * default values will be used. There are four elements a planar figure consists of: * *
    *
  1. "line": the main line segments of the planar figure (note: text is drawn in the same style) *
  2. "helperline": additional line segments of planar figures, such as arrow tips, arches of angles, etc. *
  3. "outline": background which is drawn behind the lines and helperlines of the planar figure (optional) *
  4. "marker": the markers (control points) of a planar figure *
  5. "markerline": the lines by which markers (control points) are surrounded *
* * In the following, all appearance-related planar figure properties are listed: * *
    *
  1. General properties for the planar figure *
      *
    • "planarfigure.drawoutline": if true, the "outline" lines is drawn *
    • "planarfigure.drawquantities": if true, the quantities (text) associated with the planar figure is drawn *
    • "planarfigure.drawname": if true, the name specified by the dataNode is drawn *
    • "planarfigure.drawshadow": if true, a black shadow is drawn around the planar figure *
    • "planarfigure.controlpointshape": style of the control points (enum) *
    *
  2. Line widths of planar figure elements *
      *
    • "planarfigure.line.width": width of "line" segments (float value, in mm) *
    • "planarfigure.shadow.widthmodifier": the width of the shadow is defined by width of the "line" * this * modifier *
    • "planarfigure.outline.width": width of "outline" segments (float value, in mm) *
    • "planarfigure.helperline.width": width of "helperline" segments (float value, in mm) *
    *
  3. Color/opacity of planar figure elements in normal mode (unselected) *
      *
    • "planarfigure.default.line.color" *
    • "planarfigure.default.line.opacity" *
    • "planarfigure.default.outline.color" *
    • "planarfigure.default.outline.opacity" *
    • "planarfigure.default.helperline.color" *
    • "planarfigure.default.helperline.opacity" *
    • "planarfigure.default.markerline.color" *
    • "planarfigure.default.markerline.opacity" *
    • "planarfigure.default.marker.color" *
    • "planarfigure.default.marker.opacity" *
    *
  4. Color/opacity of planar figure elements in hover mode (mouse-over) *
      *
    • "planarfigure.hover.line.color" *
    • "planarfigure.hover.line.opacity" *
    • "planarfigure.hover.outline.color" *
    • "planarfigure.hover.outline.opacity" *
    • "planarfigure.hover.helperline.color" *
    • "planarfigure.hover.helperline.opacity" *
    • "planarfigure.hover.markerline.color" *
    • "planarfigure.hover.markerline.opacity" *
    • "planarfigure.hover.marker.color" *
    • "planarfigure.hover.marker.opacity" *
    *
  5. Color/opacity of planar figure elements in selected mode *
      *
    • "planarfigure.selected.line.color" *
    • "planarfigure.selected.line.opacity" *
    • "planarfigure.selected.outline.color" *
    • "planarfigure.selected.outline.opacity" *
    • "planarfigure.selected.helperline.color" *
    • "planarfigure.selected.helperline.opacity" *
    • "planarfigure.selected.markerline.color;" *
    • "planarfigure.selected.markerline.opacity" *
    • "planarfigure.selected.marker.color" *
    • "planarfigure.selected.marker.opacity" *
    *
* * @ingroup MitkPlanarFigureModule */ - class MITKPLANARFIGURE_EXPORT PlanarFigureMapper2D : public GLMapper + class MITKPLANARFIGURE_EXPORT PlanarFigureMapper2D : public Mapper { public: - mitkClassMacro(PlanarFigureMapper2D, GLMapper); + mitkClassMacro(PlanarFigureMapper2D, Mapper); itkFactorylessNewMacro(Self) itkCloneMacro(Self) - /** - * reimplemented from Baseclass - */ - virtual void Paint(BaseRenderer *renderer) override; + /** + * reimplemented from Baseclass + */ + void MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type) override; static void SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer = nullptr, bool overwrite = false); + /** \brief Apply color and opacity properties read from the PropertyList. + * The actor is not used in the GLMappers. Called by mapper subclasses. + */ + virtual void ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor *actor = nullptr) override; + protected: enum PlanarFigureDisplayMode { PF_DEFAULT = 0, PF_HOVER = 1, PF_SELECTED = 2, PF_COUNT = 3 // helper variable }; PlanarFigureMapper2D(); virtual ~PlanarFigureMapper2D(); /** * \brief Renders all the lines defined by the PlanarFigure. * * This method renders all the lines that are defined by the PlanarFigure. * That includes the mainlines and helperlines as well as their shadows * and the outlines. * * This method already takes responsibility for the setting of the relevant * openGL attributes to reduce unnecessary setting of these attributes. * (e.g. no need to set color twice if it's the same) */ void RenderLines(const PlanarFigureDisplayMode lineDisplayMode, mitk::PlanarFigure *planarFigure, mitk::Point2D &anchorPoint, const mitk::PlaneGeometry *planarFigurePlaneGeometry, const mitk::PlaneGeometry *rendererPlaneGeometry, const mitk::BaseRenderer *renderer); /** * \brief Renders the quantities of the figure below the text annotations. */ void RenderQuantities(const mitk::PlanarFigure *planarFigure, mitk::BaseRenderer *renderer, const mitk::Point2D anchorPoint, double &annotationOffset, float globalOpacity, const PlanarFigureDisplayMode lineDisplayMode); /** * \brief Renders the text annotations. */ void RenderAnnotations(mitk::BaseRenderer *renderer, const std::string name, const mitk::Point2D anchorPoint, float globalOpacity, const PlanarFigureDisplayMode lineDisplayMode, double &annotationOffset); /** * \brief Renders the control-points. */ void RenderControlPoints(const mitk::PlanarFigure *planarFigure, const PlanarFigureDisplayMode lineDisplayMode, const mitk::PlaneGeometry *planarFigurePlaneGeometry, const mitk::PlaneGeometry *rendererPlaneGeometry, mitk::BaseRenderer *renderer); void TransformObjectToDisplay(const mitk::Point2D &point2D, mitk::Point2D &displayPoint, const mitk::PlaneGeometry *objectGeometry, const mitk::PlaneGeometry *, const mitk::BaseRenderer *renderer); void DrawMarker(const mitk::Point2D &point, float *lineColor, float lineOpacity, float *markerColor, float markerOpacity, float lineWidth, PlanarFigureControlPointStyleProperty::Shape shape, const mitk::PlaneGeometry *objectGeometry, const mitk::PlaneGeometry *rendererGeometry, const mitk::BaseRenderer *renderer); /** * \brief Actually paints the polyline defined by the figure. */ void PaintPolyLine(const mitk::PlanarFigure::PolyLineType vertices, bool closed, Point2D &anchorPoint, const PlaneGeometry *planarFigurePlaneGeometry, const PlaneGeometry *rendererPlaneGeometry, const mitk::BaseRenderer *renderer); /** * \brief Internally used by RenderLines() to draw the mainlines using * PaintPolyLine(). */ void DrawMainLines(mitk::PlanarFigure *figure, Point2D &anchorPoint, const PlaneGeometry *planarFigurePlaneGeometry, const PlaneGeometry *rendererPlaneGeometry, const mitk::BaseRenderer *renderer); /** * \brief Internally used by RenderLines() to draw the helperlines using * PaintPolyLine(). */ void DrawHelperLines(mitk::PlanarFigure *figure, Point2D &anchorPoint, const PlaneGeometry *planarFigurePlaneGeometry, const PlaneGeometry *rendererPlaneGeometry, const mitk::BaseRenderer *renderer); void InitializeDefaultPlanarFigureProperties(); void InitializePlanarFigurePropertiesFromDataNode(const mitk::DataNode *node); void SetColorProperty(float property[3][3], PlanarFigureDisplayMode mode, float red, float green, float blue) { property[mode][0] = red; property[mode][1] = green; property[mode][2] = blue; } void SetFloatProperty(float *property, PlanarFigureDisplayMode mode, float value) { property[mode] = value; } /** * \brief Callback that sets m_NodeModified to true. * * This method set the bool flag m_NodeModified to true. It's a callback * that is executed when a itk::ModifiedEvet is invoked on our * DataNode. */ void OnNodeModified(); + void Initialize(mitk::BaseRenderer *renderer); + private: + bool m_IsSelected; bool m_IsHovering; bool m_DrawOutline; bool m_DrawQuantities; bool m_DrawShadow; bool m_DrawControlPoints; bool m_DrawName; bool m_DrawDashed; bool m_DrawHelperDashed; bool m_AnnotationsShadow; std::string m_AnnotationFontFamily; bool m_DrawAnnotationBold; bool m_DrawAnnotationItalic; int m_AnnotationSize; // the width of the shadow is defined as 'm_LineWidth * m_ShadowWidthFactor' float m_LineWidth; float m_ShadowWidthFactor; float m_OutlineWidth; float m_HelperlineWidth; // float m_PointWidth; float m_DevicePixelRatio; PlanarFigureControlPointStyleProperty::Shape m_ControlPointShape; float m_LineColor[3][3]; float m_LineOpacity[3]; float m_OutlineColor[3][3]; float m_OutlineOpacity[3]; float m_HelperlineColor[3][3]; float m_HelperlineOpacity[3]; float m_MarkerlineColor[3][3]; float m_MarkerlineOpacity[3]; float m_MarkerColor[3][3]; float m_MarkerOpacity[3]; float m_AnnotationColor[3][3]; // Bool flag that represents whether or not the DataNode has been modified. bool m_NodeModified; // Observer-tag for listening to itk::ModifiedEvents on the DataNode unsigned long m_NodeModifiedObserverTag; // Bool flag that indicates if a node modified observer was added bool m_NodeModifiedObserverAdded; - itk::SmartPointer m_AnnotationAnnotation; - itk::SmartPointer m_QuantityAnnotation; + bool m_Initialized; + + vtkNew m_Context; + vtkSmartPointer m_Pen; }; } // namespace mitk #endif /* MITK_PLANAR_FIGURE_MAPPER_2D_H_ */ diff --git a/Modules/PlanarFigure/src/Algorithms/mitkPlanarFigureObjectFactory.cpp b/Modules/PlanarFigure/src/Algorithms/mitkPlanarFigureObjectFactory.cpp index 4eeee2ec08..b7fb8dde90 100644 --- a/Modules/PlanarFigure/src/Algorithms/mitkPlanarFigureObjectFactory.cpp +++ b/Modules/PlanarFigure/src/Algorithms/mitkPlanarFigureObjectFactory.cpp @@ -1,140 +1,140 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPlanarFigureObjectFactory.h" #include "mitkPlanarFigureWriter.h" #include "mitkCoreObjectFactory.h" #include "mitkPlanarFigure.h" #include "mitkPlanarFigureIOFactory.h" #include "mitkPlanarFigureMapper2D.h" #include "mitkPlanarFigureVtkMapper3D.h" #include "mitkPlanarFigureWriterFactory.h" #include "mitkVtkGLMapperWrapper.h" typedef std::multimap MultimapType; mitk::PlanarFigureObjectFactory::PlanarFigureObjectFactory() : m_PlanarFigureIOFactory(PlanarFigureIOFactory::New().GetPointer()), m_PlanarFigureWriterFactory(PlanarFigureWriterFactory::New().GetPointer()) { static bool alreadyDone = false; if (!alreadyDone) { itk::ObjectFactoryBase::RegisterFactory(m_PlanarFigureIOFactory); itk::ObjectFactoryBase::RegisterFactory(m_PlanarFigureWriterFactory); m_FileWriters.push_back(PlanarFigureWriter::New().GetPointer()); CreateFileExtensionsMap(); alreadyDone = true; } } mitk::PlanarFigureObjectFactory::~PlanarFigureObjectFactory() { itk::ObjectFactoryBase::UnRegisterFactory(m_PlanarFigureWriterFactory); itk::ObjectFactoryBase::UnRegisterFactory(m_PlanarFigureIOFactory); } mitk::Mapper::Pointer mitk::PlanarFigureObjectFactory::CreateMapper(mitk::DataNode *node, MapperSlotId id) { mitk::Mapper::Pointer newMapper = nullptr; mitk::BaseData *data = node->GetData(); if (dynamic_cast(data) != nullptr) { if (id == mitk::BaseRenderer::Standard2D) { - newMapper = mitk::VtkGLMapperWrapper::New(mitk::PlanarFigureMapper2D::New().GetPointer()); + newMapper = mitk::PlanarFigureMapper2D::New(); newMapper->SetDataNode(node); } else if (id == mitk::BaseRenderer::Standard3D) { newMapper = mitk::PlanarFigureVtkMapper3D::New(); newMapper->SetDataNode(node); } } return newMapper; } void mitk::PlanarFigureObjectFactory::SetDefaultProperties(mitk::DataNode *node) { if (node == nullptr) { return; } mitk::DataNode::Pointer nodePointer = node; mitk::PlanarFigure::Pointer pf = dynamic_cast(node->GetData()); if (pf.IsNotNull()) { mitk::PlanarFigureMapper2D::SetDefaultProperties(node); mitk::PlanarFigureVtkMapper3D::SetDefaultProperties(node); node->AddProperty("color", mitk::ColorProperty::New(1.0, 1.0, 1.0), nullptr, true); node->AddProperty("opacity", mitk::FloatProperty::New(0.8), nullptr, true); } } const char *mitk::PlanarFigureObjectFactory::GetFileExtensions() { return ""; } mitk::CoreObjectFactoryBase::MultimapType mitk::PlanarFigureObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } const char *mitk::PlanarFigureObjectFactory::GetSaveFileExtensions() { // return ";;Planar Figures (*.pf)"; // for mitk::PlanarFigure and derived classes std::string fileExtension; this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); return fileExtension.c_str(); }; mitk::CoreObjectFactoryBase::MultimapType mitk::PlanarFigureObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } void mitk::PlanarFigureObjectFactory::CreateFileExtensionsMap() { m_FileExtensionsMap.insert(std::pair("*.pf", "Planar Figure Files")); m_SaveFileExtensionsMap.insert(std::pair("*.pf", "Planar Figure Files")); } void mitk::PlanarFigureObjectFactory::RegisterIOFactories() { } struct RegisterPlanarFigureObjectFactory { RegisterPlanarFigureObjectFactory() : m_Factory(mitk::PlanarFigureObjectFactory::New()) { mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(m_Factory); } ~RegisterPlanarFigureObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory(m_Factory); } mitk::PlanarFigureObjectFactory::Pointer m_Factory; }; static RegisterPlanarFigureObjectFactory registerPlanarFigureObjectFactory; diff --git a/Modules/PlanarFigure/src/Rendering/mitkPlanarFigureMapper2D.cpp b/Modules/PlanarFigure/src/Rendering/mitkPlanarFigureMapper2D.cpp index a619680f79..64fc41bc6d 100644 --- a/Modules/PlanarFigure/src/Rendering/mitkPlanarFigureMapper2D.cpp +++ b/Modules/PlanarFigure/src/Rendering/mitkPlanarFigureMapper2D.cpp @@ -1,949 +1,975 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPlanarFigureMapper2D.h" #include "mitkBaseRenderer.h" #include "mitkColorProperty.h" -#include "mitkGL.h" +#include "vtkContext2D.h" +#include "vtkContextDevice2D.h" +#include "vtkOpenGLContextDevice2D.h" #include "mitkPlaneGeometry.h" #include "mitkProperties.h" - -#include "mitkTextAnnotation2D.h" +#include "vtkTextProperty.h" #define _USE_MATH_DEFINES #include // offset which moves the planarfigures on top of the other content // the crosshair is rendered into the z = 1 layer. static const float PLANAR_OFFSET = 0.5f; mitk::PlanarFigureMapper2D::PlanarFigureMapper2D() - : m_NodeModified(true), m_NodeModifiedObserverTag(0), m_NodeModifiedObserverAdded(false) + : m_NodeModified(true), m_NodeModifiedObserverTag(0), m_NodeModifiedObserverAdded(false), m_Initialized(false) { - m_AnnotationAnnotation = mitk::TextAnnotation2D::New(); - m_QuantityAnnotation = mitk::TextAnnotation2D::New(); this->InitializeDefaultPlanarFigureProperties(); } mitk::PlanarFigureMapper2D::~PlanarFigureMapper2D() { if (m_NodeModifiedObserverAdded && GetDataNode() != nullptr) { GetDataNode()->RemoveObserver(m_NodeModifiedObserverTag); } } -void mitk::PlanarFigureMapper2D::Paint(mitk::BaseRenderer *renderer) +void mitk::PlanarFigureMapper2D::ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor * /*actor*/) { - bool visible = true; + float rgba[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; + // check for color prop and use it for rendering if it exists + GetDataNode()->GetColor(rgba, renderer, "color"); + // check for opacity prop and use it for rendering if it exists + GetDataNode()->GetOpacity(rgba[3], renderer, "opacity"); - m_AnnotationAnnotation->SetVisibility(false); + this->m_Pen->SetColorF((double)rgba[0], (double)rgba[1], (double)rgba[2], (double)rgba[3]); +} - m_QuantityAnnotation->SetVisibility(false); +void mitk::PlanarFigureMapper2D::Initialize(mitk::BaseRenderer *) +{ + this->m_Pen = vtkSmartPointer::New(); + vtkOpenGLContextDevice2D *device = NULL; + device = vtkOpenGLContextDevice2D::New(); + if (device) + { + this->m_Context->Begin(device); + device->Delete(); + this->m_Initialized = true; + this->m_Context->ApplyPen(this->m_Pen); + } + else + { + } +} + +void mitk::PlanarFigureMapper2D::MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type) +{ + if (type != mitk::VtkPropRenderer::Overlay) return; + if (!this->m_Initialized) + { + this->Initialize(renderer); + } + vtkOpenGLContextDevice2D::SafeDownCast( + this->m_Context->GetDevice())->Begin(renderer->GetVtkRenderer()); + + bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) return; // Get PlanarFigure from input mitk::PlanarFigure *planarFigure = const_cast(static_cast(GetDataNode()->GetData())); // Check if PlanarFigure has already been placed; otherwise, do nothing if (!planarFigure->IsPlaced()) { return; } // Get 2D geometry frame of PlanarFigure const mitk::PlaneGeometry *planarFigurePlaneGeometry = planarFigure->GetPlaneGeometry(); if (planarFigurePlaneGeometry == nullptr) { MITK_ERROR << "PlanarFigure does not have valid PlaneGeometry!"; return; } // Get current world 2D geometry from renderer const mitk::PlaneGeometry *rendererPlaneGeometry = renderer->GetCurrentWorldPlaneGeometry(); // If the PlanarFigure geometry is a plane geometry, check if current // world plane is parallel to and within the planar figure geometry bounds // (otherwise, display nothing) if ((planarFigurePlaneGeometry != nullptr) && (rendererPlaneGeometry != nullptr)) { double planeThickness = planarFigurePlaneGeometry->GetExtentInMM(2); if (!planarFigurePlaneGeometry->IsParallel(rendererPlaneGeometry) || !(planarFigurePlaneGeometry->DistanceFromPlane(rendererPlaneGeometry) < planeThickness / 3.0)) { // Planes are not parallel or renderer plane is not within PlanarFigure // geometry bounds --> exit return; } } else { // Plane is not valid (curved reformations are not possible yet) return; } // Apply visual appearance properties from the PropertyList ApplyColorAndOpacityProperties(renderer); - // Enable line antialiasing - glEnable(GL_LINE_SMOOTH); - glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); - glEnable(GL_DEPTH_TEST); - // Get properties from node (if present) const mitk::DataNode *node = this->GetDataNode(); this->InitializePlanarFigurePropertiesFromDataNode(node); PlanarFigureDisplayMode lineDisplayMode = PF_DEFAULT; if (m_IsSelected) { lineDisplayMode = PF_SELECTED; } else if (m_IsHovering) { lineDisplayMode = PF_HOVER; } mitk::Point2D anchorPoint; anchorPoint[0] = 0; anchorPoint[1] = 1; // render the actual lines of the PlanarFigure RenderLines(lineDisplayMode, planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); // position-offset of the annotations, is set in RenderAnnotations() and // used in RenderQuantities() double annotationOffset = 0.0; // Get Global Opacity float globalOpacity = 1.0; node->GetFloatProperty("opacity", globalOpacity); if (m_DrawControlPoints) { // draw the control-points RenderControlPoints(planarFigure, lineDisplayMode, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); } // draw name near the anchor point (point located on the right) const std::string name = node->GetName(); if (m_DrawName && !name.empty()) { RenderAnnotations(renderer, name, anchorPoint, globalOpacity, lineDisplayMode, annotationOffset); } // draw feature quantities (if requested) next to the anchor point, // but under the name (that is where 'annotationOffset' is used) if (m_DrawQuantities) { RenderQuantities(planarFigure, renderer, anchorPoint, annotationOffset, globalOpacity, lineDisplayMode); } - glLineWidth(1.0f); + this->m_Context->GetDevice()->End(); } void mitk::PlanarFigureMapper2D::PaintPolyLine(const mitk::PlanarFigure::PolyLineType vertices, bool closed, Point2D &anchorPoint, const PlaneGeometry *planarFigurePlaneGeometry, const PlaneGeometry *rendererPlaneGeometry, const mitk::BaseRenderer *renderer) { mitk::Point2D rightMostPoint; rightMostPoint.Fill(itk::NumericTraits::min()); // transform all vertices into Point2Ds in display-Coordinates and store them in vector std::vector pointlist; for (auto iter = vertices.cbegin(); iter != vertices.cend(); ++iter) { // Draw this 2D point as OpenGL vertex mitk::Point2D displayPoint; this->TransformObjectToDisplay(*iter, displayPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); pointlist.push_back(displayPoint); if (displayPoint[0] > rightMostPoint[0]) rightMostPoint = displayPoint; } // If the planarfigure is closed, we add the first control point again. // Thus we can always use 'GL_LINE_STRIP' and get rid of strange flickering // effect when using the MESA OpenGL library. if (closed) { mitk::Point2D displayPoint; this->TransformObjectToDisplay( vertices.cbegin()[0], displayPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); pointlist.push_back(displayPoint); } // now paint all the points in one run - glBegin(GL_LINE_STRIP); - for (auto pointIter = pointlist.cbegin(); pointIter != pointlist.cend(); pointIter++) + float* points = new float[pointlist.size()*2]; + for (unsigned int i = 0 ; i < pointlist.size() ; ++i) { - glVertex3f((*pointIter)[0], (*pointIter)[1], PLANAR_OFFSET); + points[i * 2] = pointlist[i][0]; + points[i * 2 + 1] = pointlist[i][1]; } - glEnd(); + this->m_Context->DrawPoly(points,pointlist.size()); anchorPoint = rightMostPoint; } void mitk::PlanarFigureMapper2D::DrawMainLines(mitk::PlanarFigure *figure, Point2D &anchorPoint, const PlaneGeometry *planarFigurePlaneGeometry, const PlaneGeometry *rendererPlaneGeometry, const mitk::BaseRenderer *renderer) { const auto numberOfPolyLines = figure->GetPolyLinesSize(); for (auto loop = 0; loop < numberOfPolyLines; ++loop) { const auto polyline = figure->GetPolyLine(loop); this->PaintPolyLine( polyline, figure->IsClosed(), anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); } } void mitk::PlanarFigureMapper2D::DrawHelperLines(mitk::PlanarFigure *figure, Point2D &anchorPoint, const PlaneGeometry *planarFigurePlaneGeometry, const PlaneGeometry *rendererPlaneGeometry, const mitk::BaseRenderer *renderer) { const auto numberOfHelperPolyLines = figure->GetHelperPolyLinesSize(); // Draw helper objects for (unsigned int loop = 0; loop < numberOfHelperPolyLines; ++loop) { const auto helperPolyLine = figure->GetHelperPolyLine(loop, renderer->GetScaleFactorMMPerDisplayUnit(), renderer->GetViewportSize()[1]); // Check if the current helper objects is to be painted if (!figure->IsHelperToBePainted(loop)) { continue; } // ... and once normally above the shadow. this->PaintPolyLine(helperPolyLine, false, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); } } void mitk::PlanarFigureMapper2D::TransformObjectToDisplay(const mitk::Point2D &point2D, mitk::Point2D &displayPoint, const mitk::PlaneGeometry *objectGeometry, const mitk::PlaneGeometry * /*rendererGeometry*/, const mitk::BaseRenderer *renderer) { mitk::Point3D point3D; // Map circle point from local 2D geometry into 3D world space objectGeometry->Map(point2D, point3D); // Project 3D world point onto display geometry - renderer->WorldToDisplay(point3D, displayPoint); + renderer->WorldToView(point3D, displayPoint); } void mitk::PlanarFigureMapper2D::DrawMarker(const mitk::Point2D &point, float *lineColor, float lineOpacity, float *markerColor, float markerOpacity, float lineWidth, PlanarFigureControlPointStyleProperty::Shape shape, const mitk::PlaneGeometry *objectGeometry, const mitk::PlaneGeometry *rendererGeometry, const mitk::BaseRenderer *renderer) { if (this->GetDataNode() != nullptr && this->GetDataNode()->GetDataInteractor().IsNull()) return; if (markerOpacity == 0 && lineOpacity == 0) return; mitk::Point2D displayPoint; this->TransformObjectToDisplay(point, displayPoint, objectGeometry, rendererGeometry, renderer); - glColor4f(markerColor[0], markerColor[1], markerColor[2], markerOpacity); - glLineWidth(lineWidth); + this->m_Context->GetPen()->SetColorF((double)markerColor[0], (double)markerColor[1], (double)markerColor[2], markerOpacity); + this->m_Context->GetPen()->SetWidth(lineWidth); switch (shape) { case PlanarFigureControlPointStyleProperty::Square: default: { // Paint filled square - // Disable line antialiasing (does not look nice for squares) - glDisable(GL_LINE_SMOOTH); if (markerOpacity > 0) { - glRectf(displayPoint[0] - 4, displayPoint[1] - 4, displayPoint[0] + 4, displayPoint[1] + 4); + m_Context->DrawRect(displayPoint[0] - 4, displayPoint[1] - 4, 8, 8); } + // Paint outline - glColor4f(lineColor[0], lineColor[1], lineColor[2], lineOpacity); - glBegin(GL_LINE_LOOP); - glVertex3f(displayPoint[0] - 4, displayPoint[1] - 4, PLANAR_OFFSET); - glVertex3f(displayPoint[0] - 4, displayPoint[1] + 4, PLANAR_OFFSET); - glVertex3f(displayPoint[0] + 4, displayPoint[1] + 4, PLANAR_OFFSET); - glVertex3f(displayPoint[0] + 4, displayPoint[1] - 4, PLANAR_OFFSET); - glEnd(); + this->m_Context->GetPen()->SetColorF((double)lineColor[0], (double)lineColor[1], (double)lineColor[2], (double)lineOpacity); + + float* outline = new float[8]; + outline[0] = displayPoint[0] - 4; + outline[1] = displayPoint[1] - 4; + outline[2] = outline[0]; + outline[3] = displayPoint[1] + 4; + outline[4] = displayPoint[0] + 4; + outline[5] = outline[3]; + outline[6] = outline[4]; + outline[7] = outline[1]; + + m_Context->DrawLines(outline, 4); break; } case PlanarFigureControlPointStyleProperty::Circle: { - float radius = 4.0; + // TODO: This code can not be reached using the properties provided in the GUI + + /*float radius = 4.0; if (markerOpacity > 0) { // Paint filled circle glBegin(GL_POLYGON); for (int angle = 0; angle < 8; ++angle) { float angleRad = angle * (float)3.14159 / 4.0; float x = displayPoint[0] + radius * (float)cos(angleRad); float y = displayPoint[1] + radius * (float)sin(angleRad); glVertex3f(x, y, PLANAR_OFFSET); } glEnd(); } // Paint outline glColor4f(lineColor[0], lineColor[1], lineColor[2], lineOpacity); glBegin(GL_LINE_LOOP); for (int angle = 0; angle < 8; ++angle) { float angleRad = angle * (float)3.14159 / 4.0; float x = displayPoint[0] + radius * (float)cos(angleRad); float y = displayPoint[1] + radius * (float)sin(angleRad); glVertex3f(x, y, PLANAR_OFFSET); } - glEnd(); + glEnd();*/ break; } } // end switch } void mitk::PlanarFigureMapper2D::InitializeDefaultPlanarFigureProperties() { m_IsSelected = false; m_IsHovering = false; m_DrawOutline = false; m_DrawQuantities = false; m_DrawShadow = false; m_DrawControlPoints = false; m_DrawName = true; m_DrawDashed = false; m_DrawHelperDashed = false; m_AnnotationsShadow = false; m_ShadowWidthFactor = 1.2; m_LineWidth = 1.0; m_OutlineWidth = 4.0; m_HelperlineWidth = 2.0; m_DevicePixelRatio = 1.0; m_ControlPointShape = PlanarFigureControlPointStyleProperty::Square; this->SetColorProperty(m_LineColor, PF_DEFAULT, 1.0, 1.0, 1.0); this->SetFloatProperty(m_LineOpacity, PF_DEFAULT, 1.0); this->SetColorProperty(m_OutlineColor, PF_DEFAULT, 0.0, 0.0, 1.0); this->SetFloatProperty(m_OutlineOpacity, PF_DEFAULT, 1.0); this->SetColorProperty(m_HelperlineColor, PF_DEFAULT, 0.4, 0.8, 0.2); this->SetFloatProperty(m_HelperlineOpacity, PF_DEFAULT, 0.4); this->SetColorProperty(m_MarkerlineColor, PF_DEFAULT, 1.0, 1.0, 1.0); this->SetFloatProperty(m_MarkerlineOpacity, PF_DEFAULT, 1.0); this->SetColorProperty(m_MarkerColor, PF_DEFAULT, 1.0, 1.0, 1.0); this->SetFloatProperty(m_MarkerOpacity, PF_DEFAULT, 0.0); this->SetColorProperty(m_AnnotationColor, PF_DEFAULT, 1.0, 1.0, 1.0); this->SetColorProperty(m_LineColor, PF_HOVER, 1.0, 0.7, 0.0); this->SetFloatProperty(m_LineOpacity, PF_HOVER, 1.0); this->SetColorProperty(m_OutlineColor, PF_HOVER, 0.0, 0.0, 1.0); this->SetFloatProperty(m_OutlineOpacity, PF_HOVER, 1.0); this->SetColorProperty(m_HelperlineColor, PF_HOVER, 0.4, 0.8, 0.2); this->SetFloatProperty(m_HelperlineOpacity, PF_HOVER, 0.4); this->SetColorProperty(m_MarkerlineColor, PF_HOVER, 1.0, 1.0, 1.0); this->SetFloatProperty(m_MarkerlineOpacity, PF_HOVER, 1.0); this->SetColorProperty(m_MarkerColor, PF_HOVER, 1.0, 0.6, 0.0); this->SetFloatProperty(m_MarkerOpacity, PF_HOVER, 0.2); this->SetColorProperty(m_AnnotationColor, PF_HOVER, 1.0, 0.7, 0.0); this->SetColorProperty(m_LineColor, PF_SELECTED, 1.0, 0.0, 0.0); this->SetFloatProperty(m_LineOpacity, PF_SELECTED, 1.0); this->SetColorProperty(m_OutlineColor, PF_SELECTED, 0.0, 0.0, 1.0); this->SetFloatProperty(m_OutlineOpacity, PF_SELECTED, 1.0); this->SetColorProperty(m_HelperlineColor, PF_SELECTED, 0.4, 0.8, 0.2); this->SetFloatProperty(m_HelperlineOpacity, PF_SELECTED, 0.4); this->SetColorProperty(m_MarkerlineColor, PF_SELECTED, 1.0, 1.0, 1.0); this->SetFloatProperty(m_MarkerlineOpacity, PF_SELECTED, 1.0); this->SetColorProperty(m_MarkerColor, PF_SELECTED, 1.0, 0.6, 0.0); this->SetFloatProperty(m_MarkerOpacity, PF_SELECTED, 1.0); this->SetColorProperty(m_AnnotationColor, PF_SELECTED, 1.0, 0.0, 0.0); } void mitk::PlanarFigureMapper2D::InitializePlanarFigurePropertiesFromDataNode(const mitk::DataNode *node) { if (node == nullptr) { return; } // if we have not added an observer for ModifiedEvents on the DataNode, // we add one now. if (!m_NodeModifiedObserverAdded) { itk::SimpleMemberCommand::Pointer nodeModifiedCommand = itk::SimpleMemberCommand::New(); nodeModifiedCommand->SetCallbackFunction(this, &mitk::PlanarFigureMapper2D::OnNodeModified); m_NodeModifiedObserverTag = node->AddObserver(itk::ModifiedEvent(), nodeModifiedCommand); m_NodeModifiedObserverAdded = true; } // If the DataNode has not been modified since the last execution of // this method, we do not run it now. if (!m_NodeModified) return; // Mark the current properties as unmodified m_NodeModified = false; // Get Global Opacity float globalOpacity = 1.0; node->GetFloatProperty("opacity", globalOpacity); node->GetBoolProperty("selected", m_IsSelected); node->GetBoolProperty("planarfigure.ishovering", m_IsHovering); node->GetBoolProperty("planarfigure.drawoutline", m_DrawOutline); node->GetBoolProperty("planarfigure.drawshadow", m_DrawShadow); node->GetBoolProperty("planarfigure.drawquantities", m_DrawQuantities); node->GetBoolProperty("planarfigure.drawcontrolpoints", m_DrawControlPoints); node->GetBoolProperty("planarfigure.drawname", m_DrawName); node->GetBoolProperty("planarfigure.drawdashed", m_DrawDashed); node->GetBoolProperty("planarfigure.helperline.drawdashed", m_DrawHelperDashed); node->GetFloatProperty("planarfigure.line.width", m_LineWidth); node->GetFloatProperty("planarfigure.shadow.widthmodifier", m_ShadowWidthFactor); node->GetFloatProperty("planarfigure.outline.width", m_OutlineWidth); node->GetFloatProperty("planarfigure.helperline.width", m_HelperlineWidth); node->GetFloatProperty("planarfigure.devicepixelratio", m_DevicePixelRatio); node->GetStringProperty("planarfigure.annotations.font.family", m_AnnotationFontFamily); node->GetBoolProperty("planarfigure.annotations.font.bold", m_DrawAnnotationBold); node->GetBoolProperty("planarfigure.annotations.font.italic", m_DrawAnnotationItalic); node->GetIntProperty("planarfigure.annotations.font.size", m_AnnotationSize); if (!node->GetBoolProperty("planarfigure.annotations.shadow", m_AnnotationsShadow)) { node->GetBoolProperty("planarfigure.drawshadow", m_AnnotationsShadow); } PlanarFigureControlPointStyleProperty::Pointer styleProperty = dynamic_cast(node->GetProperty("planarfigure.controlpointshape")); if (styleProperty.IsNotNull()) { m_ControlPointShape = styleProperty->GetShape(); } // Set default color and opacity // If property "planarfigure.default.*.color" exists, then use that color. Otherwise global "color" property is used. if (!node->GetColor(m_LineColor[PF_DEFAULT], nullptr, "planarfigure.default.line.color")) { node->GetColor(m_LineColor[PF_DEFAULT], nullptr, "color"); } node->GetFloatProperty("planarfigure.default.line.opacity", m_LineOpacity[PF_DEFAULT]); if (!node->GetColor(m_OutlineColor[PF_DEFAULT], nullptr, "planarfigure.default.outline.color")) { node->GetColor(m_OutlineColor[PF_DEFAULT], nullptr, "color"); } node->GetFloatProperty("planarfigure.default.outline.opacity", m_OutlineOpacity[PF_DEFAULT]); if (!node->GetColor(m_HelperlineColor[PF_DEFAULT], nullptr, "planarfigure.default.helperline.color")) { node->GetColor(m_HelperlineColor[PF_DEFAULT], nullptr, "color"); } node->GetFloatProperty("planarfigure.default.helperline.opacity", m_HelperlineOpacity[PF_DEFAULT]); node->GetColor(m_MarkerlineColor[PF_DEFAULT], nullptr, "planarfigure.default.markerline.color"); node->GetFloatProperty("planarfigure.default.markerline.opacity", m_MarkerlineOpacity[PF_DEFAULT]); node->GetColor(m_MarkerColor[PF_DEFAULT], nullptr, "planarfigure.default.marker.color"); node->GetFloatProperty("planarfigure.default.marker.opacity", m_MarkerOpacity[PF_DEFAULT]); if (!node->GetColor(m_AnnotationColor[PF_DEFAULT], nullptr, "planarfigure.default.annotation.color")) { if (!node->GetColor(m_AnnotationColor[PF_DEFAULT], nullptr, "planarfigure.default.line.color")) { node->GetColor(m_AnnotationColor[PF_DEFAULT], nullptr, "color"); } } // Set hover color and opacity node->GetColor(m_LineColor[PF_HOVER], nullptr, "planarfigure.hover.line.color"); node->GetFloatProperty("planarfigure.hover.line.opacity", m_LineOpacity[PF_HOVER]); node->GetColor(m_OutlineColor[PF_HOVER], nullptr, "planarfigure.hover.outline.color"); node->GetFloatProperty("planarfigure.hover.outline.opacity", m_OutlineOpacity[PF_HOVER]); node->GetColor(m_HelperlineColor[PF_HOVER], nullptr, "planarfigure.hover.helperline.color"); node->GetFloatProperty("planarfigure.hover.helperline.opacity", m_HelperlineOpacity[PF_HOVER]); node->GetColor(m_MarkerlineColor[PF_HOVER], nullptr, "planarfigure.hover.markerline.color"); node->GetFloatProperty("planarfigure.hover.markerline.opacity", m_MarkerlineOpacity[PF_HOVER]); node->GetColor(m_MarkerColor[PF_HOVER], nullptr, "planarfigure.hover.marker.color"); node->GetFloatProperty("planarfigure.hover.marker.opacity", m_MarkerOpacity[PF_HOVER]); if (!node->GetColor(m_AnnotationColor[PF_HOVER], nullptr, "planarfigure.hover.annotation.color")) { if (!node->GetColor(m_AnnotationColor[PF_HOVER], nullptr, "planarfigure.hover.line.color")) { node->GetColor(m_AnnotationColor[PF_HOVER], nullptr, "color"); } } // Set selected color and opacity node->GetColor(m_LineColor[PF_SELECTED], nullptr, "planarfigure.selected.line.color"); node->GetFloatProperty("planarfigure.selected.line.opacity", m_LineOpacity[PF_SELECTED]); node->GetColor(m_OutlineColor[PF_SELECTED], nullptr, "planarfigure.selected.outline.color"); node->GetFloatProperty("planarfigure.selected.outline.opacity", m_OutlineOpacity[PF_SELECTED]); node->GetColor(m_HelperlineColor[PF_SELECTED], nullptr, "planarfigure.selected.helperline.color"); node->GetFloatProperty("planarfigure.selected.helperline.opacity", m_HelperlineOpacity[PF_SELECTED]); node->GetColor(m_MarkerlineColor[PF_SELECTED], nullptr, "planarfigure.selected.markerline.color"); node->GetFloatProperty("planarfigure.selected.markerline.opacity", m_MarkerlineOpacity[PF_SELECTED]); node->GetColor(m_MarkerColor[PF_SELECTED], nullptr, "planarfigure.selected.marker.color"); node->GetFloatProperty("planarfigure.selected.marker.opacity", m_MarkerOpacity[PF_SELECTED]); if (!node->GetColor(m_AnnotationColor[PF_SELECTED], nullptr, "planarfigure.selected.annotation.color")) { if (!node->GetColor(m_AnnotationColor[PF_SELECTED], nullptr, "planarfigure.selected.line.color")) { node->GetColor(m_AnnotationColor[PF_SELECTED], nullptr, "color"); } } // adapt opacity values to global "opacity" property for (unsigned int i = 0; i < PF_COUNT; ++i) { m_LineOpacity[i] *= globalOpacity; m_OutlineOpacity[i] *= globalOpacity; m_HelperlineOpacity[i] *= globalOpacity; m_MarkerlineOpacity[i] *= globalOpacity; m_MarkerOpacity[i] *= globalOpacity; } } void mitk::PlanarFigureMapper2D::OnNodeModified() { m_NodeModified = true; } void mitk::PlanarFigureMapper2D::SetDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) { node->AddProperty("visible", mitk::BoolProperty::New(true), renderer, overwrite); // node->SetProperty("planarfigure.iseditable",mitk::BoolProperty::New(true)); node->AddProperty("planarfigure.isextendable", mitk::BoolProperty::New(false)); // node->AddProperty( "planarfigure.ishovering", mitk::BoolProperty::New(true) ); node->AddProperty("planarfigure.drawoutline", mitk::BoolProperty::New(false)); // node->AddProperty( "planarfigure.drawquantities", mitk::BoolProperty::New(true) ); node->AddProperty("planarfigure.drawshadow", mitk::BoolProperty::New(true)); node->AddProperty("planarfigure.drawcontrolpoints", mitk::BoolProperty::New(true)); node->AddProperty("planarfigure.drawname", mitk::BoolProperty::New(true)); node->AddProperty("planarfigure.drawdashed", mitk::BoolProperty::New(false)); node->AddProperty("planarfigure.helperline.drawdashed", mitk::BoolProperty::New(false)); node->AddProperty("planarfigure.annotations.font.family", mitk::StringProperty::New("Arial")); node->AddProperty("planarfigure.annotations.font.bold", mitk::BoolProperty::New(false)); node->AddProperty("planarfigure.annotations.font.italic", mitk::BoolProperty::New(false)); node->AddProperty("planarfigure.annotations.font.size", mitk::IntProperty::New(12)); node->AddProperty("planarfigure.line.width", mitk::FloatProperty::New(2.0)); node->AddProperty("planarfigure.shadow.widthmodifier", mitk::FloatProperty::New(2.0)); node->AddProperty("planarfigure.outline.width", mitk::FloatProperty::New(2.0)); node->AddProperty("planarfigure.helperline.width", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.default.line.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.default.outline.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.default.helperline.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.default.markerline.color", mitk::ColorProperty::New(1.0, 1.0, 1.0)); node->AddProperty("planarfigure.default.markerline.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.default.marker.color", mitk::ColorProperty::New(1.0, 1.0, 1.0)); node->AddProperty("planarfigure.default.marker.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.hover.line.color", mitk::ColorProperty::New(0.0, 1.0, 0.0)); node->AddProperty("planarfigure.hover.line.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.hover.outline.color", mitk::ColorProperty::New(0.0, 1.0, 0.0)); node->AddProperty("planarfigure.hover.outline.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.hover.helperline.color", mitk::ColorProperty::New(0.0, 1.0, 0.0)); node->AddProperty("planarfigure.hover.helperline.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.hover.markerline.color", mitk::ColorProperty::New(0.0, 1.0, 0.0)); node->AddProperty("planarfigure.hover.markerline.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.hover.marker.color", mitk::ColorProperty::New(0.0, 1.0, 0.0)); node->AddProperty("planarfigure.hover.marker.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.selected.line.color", mitk::ColorProperty::New(1.0, 0.0, 0.0)); node->AddProperty("planarfigure.selected.line.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.selected.outline.color", mitk::ColorProperty::New(1.0, 0.0, 0.0)); node->AddProperty("planarfigure.selected.outline.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.selected.helperline.color", mitk::ColorProperty::New(1.0, 0.0, 0.0)); node->AddProperty("planarfigure.selected.helperline.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.selected.markerline.color", mitk::ColorProperty::New(1.0, 0.0, 0.0)); node->AddProperty("planarfigure.selected.markerline.opacity", mitk::FloatProperty::New(1.0)); node->AddProperty("planarfigure.selected.marker.color", mitk::ColorProperty::New(1.0, 0.0, 0.0)); node->AddProperty("planarfigure.selected.marker.opacity", mitk::FloatProperty::New(1.0)); } void mitk::PlanarFigureMapper2D::RenderControlPoints(const mitk::PlanarFigure *planarFigure, const PlanarFigureDisplayMode lineDisplayMode, const mitk::PlaneGeometry *planarFigurePlaneGeometry, const mitk::PlaneGeometry *rendererPlaneGeometry, mitk::BaseRenderer *renderer) { bool isEditable = true; m_DataNode->GetBoolProperty("planarfigure.iseditable", isEditable); PlanarFigureDisplayMode pointDisplayMode = PF_DEFAULT; const unsigned int selectedControlPointsIdx = (unsigned int)planarFigure->GetSelectedControlPoint(); const unsigned int numberOfControlPoints = planarFigure->GetNumberOfControlPoints(); // Draw markers at control points (selected control point will be colored) for (unsigned int i = 0; i < numberOfControlPoints; ++i) { // Only if planar figure is marked as editable: display markers (control points) in a // different style if mouse is over them or they are selected if (isEditable) { if (i == selectedControlPointsIdx) { pointDisplayMode = PF_SELECTED; } else if (m_IsHovering && isEditable) { pointDisplayMode = PF_HOVER; } } if (m_MarkerOpacity[pointDisplayMode] == 0 && m_MarkerlineOpacity[pointDisplayMode] == 0) { continue; } if (m_DrawOutline) { // draw outlines for markers as well // linewidth for the contour is only half, as full width looks // much too thick! this->DrawMarker(planarFigure->GetControlPoint(i), m_OutlineColor[lineDisplayMode], m_MarkerlineOpacity[pointDisplayMode], m_OutlineColor[lineDisplayMode], m_MarkerOpacity[pointDisplayMode], m_OutlineWidth / 2, m_ControlPointShape, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); } this->DrawMarker(planarFigure->GetControlPoint(i), m_MarkerlineColor[pointDisplayMode], m_MarkerlineOpacity[pointDisplayMode], m_MarkerColor[pointDisplayMode], m_MarkerOpacity[pointDisplayMode], m_LineWidth, m_ControlPointShape, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); } if (planarFigure->IsPreviewControlPointVisible()) { this->DrawMarker(planarFigure->GetPreviewControlPoint(), m_MarkerlineColor[PF_HOVER], m_MarkerlineOpacity[PF_HOVER], m_MarkerColor[PF_HOVER], m_MarkerOpacity[PF_HOVER], m_LineWidth, m_ControlPointShape, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); } } -void mitk::PlanarFigureMapper2D::RenderAnnotations(mitk::BaseRenderer *renderer, +void mitk::PlanarFigureMapper2D::RenderAnnotations(mitk::BaseRenderer *, const std::string name, const mitk::Point2D anchorPoint, float globalOpacity, const PlanarFigureDisplayMode lineDisplayMode, double &annotationOffset) { if (anchorPoint[0] < mitk::eps || anchorPoint[1] < mitk::eps) { return; } - m_AnnotationAnnotation->SetText(name); - m_AnnotationAnnotation->SetColor(m_AnnotationColor[lineDisplayMode][0], - m_AnnotationColor[lineDisplayMode][1], - m_AnnotationColor[lineDisplayMode][2]); - m_AnnotationAnnotation->SetOpacity(globalOpacity); - m_AnnotationAnnotation->SetFontSize(m_AnnotationSize * m_DevicePixelRatio); - m_AnnotationAnnotation->SetBoolProperty("drawShadow", m_AnnotationsShadow); - m_AnnotationAnnotation->SetVisibility(true); - m_AnnotationAnnotation->SetStringProperty("font.family", m_AnnotationFontFamily); - m_AnnotationAnnotation->SetBoolProperty("font.bold", m_DrawAnnotationBold); - m_AnnotationAnnotation->SetBoolProperty("font.italic", m_DrawAnnotationItalic); + vtkTextProperty* textProp = vtkTextProperty::New(); + textProp->SetFontSize(m_AnnotationSize); + textProp->SetFontFamilyAsString(m_AnnotationFontFamily.c_str()); + textProp->SetJustificationToLeft(); + textProp->SetOpacity(globalOpacity); + textProp->SetShadow(0); + textProp->SetBold(m_DrawAnnotationBold); + textProp->SetItalic(m_DrawAnnotationItalic); mitk::Point2D offset; offset.Fill(5); mitk::Point2D scaledAnchorPoint; scaledAnchorPoint[0] = anchorPoint[0] * m_DevicePixelRatio; scaledAnchorPoint[1] = anchorPoint[1] * m_DevicePixelRatio; offset[0] = offset[0] * m_DevicePixelRatio; offset[1] = offset[1] * m_DevicePixelRatio; - m_AnnotationAnnotation->SetPosition2D(scaledAnchorPoint); - m_AnnotationAnnotation->SetOffsetVector(offset); - m_AnnotationAnnotation->Update(renderer); - m_AnnotationAnnotation->Paint(renderer); + if(m_DrawShadow) + { + textProp->SetColor(0.0,0.0,0.0); + this->m_Context->ApplyTextProp(textProp); + this->m_Context->DrawString(scaledAnchorPoint[0]+offset[0]+1, scaledAnchorPoint[1]+offset[1]-1, name.c_str()); + } + textProp->SetColor(m_AnnotationColor[lineDisplayMode][0], + m_AnnotationColor[lineDisplayMode][1], + m_AnnotationColor[lineDisplayMode][2]); + this->m_Context->ApplyTextProp(textProp); + this->m_Context->DrawString(scaledAnchorPoint[0]+offset[0], scaledAnchorPoint[1]+offset[1], name.c_str()); + annotationOffset -= 15.0; // annotationOffset -= m_AnnotationAnnotation->GetBoundsOnDisplay( renderer ).Size[1]; + textProp->Delete(); } void mitk::PlanarFigureMapper2D::RenderQuantities(const mitk::PlanarFigure *planarFigure, - mitk::BaseRenderer *renderer, + mitk::BaseRenderer *, const mitk::Point2D anchorPoint, double &annotationOffset, float globalOpacity, const PlanarFigureDisplayMode lineDisplayMode) { if (anchorPoint[0] < mitk::eps || anchorPoint[1] < mitk::eps) { return; } std::stringstream quantityString; quantityString.setf(ios::fixed, ios::floatfield); quantityString.precision(1); bool firstActiveFeature = true; for (unsigned int i = 0; i < planarFigure->GetNumberOfFeatures(); ++i) { if (planarFigure->IsFeatureActive(i) && planarFigure->IsFeatureVisible(i)) { if (!firstActiveFeature) { quantityString << " x "; } quantityString << planarFigure->GetQuantity(i) << " "; quantityString << planarFigure->GetFeatureUnit(i); firstActiveFeature = false; } } - m_QuantityAnnotation->SetColor(m_AnnotationColor[lineDisplayMode][0], - m_AnnotationColor[lineDisplayMode][1], - m_AnnotationColor[lineDisplayMode][2]); - - m_QuantityAnnotation->SetOpacity(globalOpacity); - m_QuantityAnnotation->SetFontSize(m_AnnotationSize * m_DevicePixelRatio); - m_QuantityAnnotation->SetBoolProperty("drawShadow", m_DrawShadow); - m_QuantityAnnotation->SetVisibility(true); - - m_AnnotationAnnotation->SetStringProperty("font.family", m_AnnotationFontFamily); - m_AnnotationAnnotation->SetBoolProperty("font.bold", m_DrawAnnotationBold); - m_AnnotationAnnotation->SetBoolProperty("font.italic", m_DrawAnnotationItalic); + vtkTextProperty* textProp = vtkTextProperty::New(); + textProp->SetFontSize(m_AnnotationSize); + textProp->SetFontFamilyAsString(m_AnnotationFontFamily.c_str()); + textProp->SetJustificationToLeft(); + textProp->SetOpacity(globalOpacity); + textProp->SetShadow(0); + textProp->SetBold(m_DrawAnnotationBold); + textProp->SetItalic(m_DrawAnnotationItalic); - m_QuantityAnnotation->SetText(quantityString.str().c_str()); mitk::Point2D offset; offset.Fill(5); - offset[1] += annotationOffset; mitk::Point2D scaledAnchorPoint; scaledAnchorPoint[0] = anchorPoint[0] * m_DevicePixelRatio; scaledAnchorPoint[1] = anchorPoint[1] * m_DevicePixelRatio; offset[0] = offset[0] * m_DevicePixelRatio; offset[1] = offset[1] * m_DevicePixelRatio; - m_QuantityAnnotation->SetPosition2D(scaledAnchorPoint); - m_QuantityAnnotation->SetOffsetVector(offset); - m_QuantityAnnotation->Update(renderer); - m_QuantityAnnotation->Paint(renderer); - // annotationOffset -= m_QuantityAnnotation->GetBoundsOnDisplay( renderer ).Size[1]; + if(m_DrawShadow) + { + textProp->SetColor(0,0,0); + this->m_Context->ApplyTextProp(textProp); + this->m_Context->DrawString(scaledAnchorPoint[0]+offset[0]+1, scaledAnchorPoint[1]+offset[1]-1, quantityString.str().c_str()); + } + textProp->SetColor(m_AnnotationColor[lineDisplayMode][0], + m_AnnotationColor[lineDisplayMode][1], + m_AnnotationColor[lineDisplayMode][2]); + this->m_Context->ApplyTextProp(textProp); + this->m_Context->DrawString(scaledAnchorPoint[0]+offset[0], scaledAnchorPoint[1]+offset[1], quantityString.str().c_str()); + annotationOffset -= 15.0; + // annotationOffset -= m_AnnotationAnnotation->GetBoundsOnDisplay( renderer ).Size[1]; + textProp->Delete(); } void mitk::PlanarFigureMapper2D::RenderLines(const PlanarFigureDisplayMode lineDisplayMode, mitk::PlanarFigure *planarFigure, mitk::Point2D &anchorPoint, const mitk::PlaneGeometry *planarFigurePlaneGeometry, const mitk::PlaneGeometry *rendererPlaneGeometry, const mitk::BaseRenderer *renderer) { - glLineStipple(1, 0x00FF); - // If we want to draw an outline, we do it here if (m_DrawOutline) { const float *color = m_OutlineColor[lineDisplayMode]; const float opacity = m_OutlineOpacity[lineDisplayMode]; // convert to a float array that also contains opacity, faster GL float *colorVector = new float[4]; colorVector[0] = color[0]; colorVector[1] = color[1]; colorVector[2] = color[2]; colorVector[3] = opacity; // set the color and opacity here as it is common for all outlines - glColor4fv(colorVector); - glLineWidth(m_OutlineWidth); + + this->m_Context->GetPen()->SetColorF((double)color[0], (double)color[1], (double)color[2], opacity); + this->m_Context->GetPen()->SetWidth(m_OutlineWidth); if (m_DrawDashed) - glEnable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::DASH_LINE); else - glDisable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::SOLID_LINE); // Draw the outline for all polylines if requested this->DrawMainLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); - glLineWidth(m_HelperlineWidth); + this->m_Context->GetPen()->SetWidth(m_HelperlineWidth); if (m_DrawHelperDashed) - glEnable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::DASH_LINE); else - glDisable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::SOLID_LINE); // Draw the outline for all helper objects if requested this->DrawHelperLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); // cleanup delete[] colorVector; } // If we want to draw a shadow, we do it here if (m_DrawShadow) { // determine the shadow opacity const float opacity = m_OutlineOpacity[lineDisplayMode]; float shadowOpacity = 0.0f; if (opacity > 0.2f) shadowOpacity = opacity - 0.2f; // convert to a float array that also contains opacity, faster GL float *shadow = new float[4]; shadow[0] = 0; shadow[1] = 0; shadow[2] = 0; shadow[3] = shadowOpacity; // set the color and opacity here as it is common for all shadows - glColor4fv(shadow); - glLineWidth(m_OutlineWidth * m_ShadowWidthFactor); + this->m_Context->GetPen()->SetColorF(0, 0, 0, shadowOpacity); + this->m_Context->GetPen()->SetWidth(m_OutlineWidth * m_ShadowWidthFactor); if (m_DrawDashed) - glEnable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::DASH_LINE); else - glDisable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::SOLID_LINE); // Draw the outline for all polylines if requested this->DrawMainLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); - glLineWidth(m_HelperlineWidth); + this->m_Context->GetPen()->SetWidth(m_HelperlineWidth); if (m_DrawHelperDashed) - glEnable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::DASH_LINE); else - glDisable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::SOLID_LINE); // Draw the outline for all helper objects if requested this->DrawHelperLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); // cleanup delete[] shadow; } // set this in brackets to avoid duplicate variables in the same scope { const float *color = m_LineColor[lineDisplayMode]; const float opacity = m_LineOpacity[lineDisplayMode]; - // convert to a float array that also contains opacity, faster GL - float *colorVector = new float[4]; - colorVector[0] = color[0]; - colorVector[1] = color[1]; - colorVector[2] = color[2]; - colorVector[3] = opacity; - // set the color and opacity here as it is common for all mainlines - glColor4fv(colorVector); - glLineWidth(m_LineWidth); + + this->m_Context->GetPen()->SetColorF((double)color[0], (double)color[1], (double)color[2], (double)opacity); + this->m_Context->GetPen()->SetWidth(m_LineWidth); if (m_DrawDashed) - glEnable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::DASH_LINE); else - glDisable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::SOLID_LINE); // Draw the main line for all polylines this->DrawMainLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); const float *helperColor = m_HelperlineColor[lineDisplayMode]; const float helperOpacity = m_HelperlineOpacity[lineDisplayMode]; - // convert to a float array that also contains opacity, faster GL - float *helperColorVector = new float[4]; - helperColorVector[0] = helperColor[0]; - helperColorVector[1] = helperColor[1]; - helperColorVector[2] = helperColor[2]; - helperColorVector[3] = helperOpacity; // we only set the color for the helperlines as the linewidth is unchanged - glColor4fv(helperColorVector); - - glLineWidth(m_HelperlineWidth); + this->m_Context->GetPen()->SetColorF((double)helperColor[0], (double)helperColor[1], (double)helperColor[2], (double)helperOpacity); + this->m_Context->GetPen()->SetWidth(m_HelperlineWidth); if (m_DrawHelperDashed) - glEnable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::DASH_LINE); else - glDisable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::SOLID_LINE); + // Draw helper objects this->DrawHelperLines(planarFigure, anchorPoint, planarFigurePlaneGeometry, rendererPlaneGeometry, renderer); - - // cleanup - delete[] colorVector; - delete[] helperColorVector; } if (m_DrawDashed || m_DrawHelperDashed) - glDisable(GL_LINE_STIPPLE); + this->m_Context->GetPen()->SetLineType(vtkPen::SOLID_LINE); } diff --git a/Modules/QtWidgets/CMakeLists.txt b/Modules/QtWidgets/CMakeLists.txt index 65a44f75f5..7307928e23 100644 --- a/Modules/QtWidgets/CMakeLists.txt +++ b/Modules/QtWidgets/CMakeLists.txt @@ -1,9 +1,9 @@ MITK_CREATE_MODULE( INCLUDE_DIRS PRIVATE resource # for xpm includes DEPENDS MitkPlanarFigure MitkAnnotation PACKAGE_DEPENDS - PUBLIC ITK|ITKIOImageBase VTK|vtkGUISupportQt+vtkGUISupportQtOpenGL Qt5|Widgets+OpenGL+Core + PUBLIC ITK|ITKIOImageBase VTK|vtkGUISupportQt Qt5|Widgets+OpenGL+Core SUBPROJECTS MITK-CoreUI ) add_subdirectory(test) diff --git a/Modules/SceneSerializationBase/src/mitkEnumerationSubclassesSerializer.cpp b/Modules/SceneSerializationBase/src/mitkEnumerationSubclassesSerializer.cpp index faa8fadd26..5e1a6e8dfd 100644 --- a/Modules/SceneSerializationBase/src/mitkEnumerationSubclassesSerializer.cpp +++ b/Modules/SceneSerializationBase/src/mitkEnumerationSubclassesSerializer.cpp @@ -1,78 +1,76 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef mitkEnumerationSubclassesSerializer_h_included #define mitkEnumerationSubclassesSerializer_h_included #include "mitkEnumerationPropertySerializer.h" #include "mitkModalityProperty.h" #include "mitkPlaneOrientationProperty.h" #include "mitkPointSetShapeProperty.h" #include "mitkRenderingModeProperty.h" -#include "mitkShaderProperty.h" #include "mitkVtkInterpolationProperty.h" #include "mitkVtkRepresentationProperty.h" #include "mitkVtkResliceInterpolationProperty.h" #include "mitkVtkScalarModeProperty.h" #include "mitkVtkVolumeRenderingProperty.h" #define MITK_REGISTER_ENUM_SUB_SERIALIZER(classname) \ \ namespace mitk \ \ { \ \ class classname##Serializer \ : public EnumerationPropertySerializer\ {public : \ \ mitkClassMacro(classname##Serializer, EnumerationPropertySerializer) itkFactorylessNewMacro(Self) \ itkCloneMacro(Self) \ \ virtual BaseProperty::Pointer Deserialize(TiXmlElement * element) override{if (!element) return nullptr; \ const char *sa(element->Attribute("value")); \ \ std::string s(sa ? sa : ""); \ classname::Pointer property = classname::New(); \ property->SetValue(s); \ \ return property.GetPointer(); \ } \ \ protected: \ classname##Serializer() {} \ virtual ~classname##Serializer() {} \ \ } \ ; \ \ } \ \ MITK_REGISTER_SERIALIZER(classname##Serializer); MITK_REGISTER_ENUM_SUB_SERIALIZER(PlaneOrientationProperty); -MITK_REGISTER_ENUM_SUB_SERIALIZER(ShaderProperty); MITK_REGISTER_ENUM_SUB_SERIALIZER(VtkInterpolationProperty); MITK_REGISTER_ENUM_SUB_SERIALIZER(VtkRepresentationProperty); MITK_REGISTER_ENUM_SUB_SERIALIZER(VtkResliceInterpolationProperty); MITK_REGISTER_ENUM_SUB_SERIALIZER(VtkScalarModeProperty); MITK_REGISTER_ENUM_SUB_SERIALIZER(VtkVolumeRenderingProperty); MITK_REGISTER_ENUM_SUB_SERIALIZER(ModalityProperty); MITK_REGISTER_ENUM_SUB_SERIALIZER(RenderingModeProperty); MITK_REGISTER_ENUM_SUB_SERIALIZER(PointSetShapeProperty); #endif diff --git a/Modules/SceneSerializationBase/test/mitkPropertySerializationTest.cpp b/Modules/SceneSerializationBase/test/mitkPropertySerializationTest.cpp index aff5341864..710694c5c3 100644 --- a/Modules/SceneSerializationBase/test/mitkPropertySerializationTest.cpp +++ b/Modules/SceneSerializationBase/test/mitkPropertySerializationTest.cpp @@ -1,281 +1,279 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkTestingMacros.h" #include "mitkCoreObjectFactory.h" #include "mitkBaseProperty.h" #include "mitkProperties.h" #include #include #include #include /* #include #include #include */ #include //#include //#include #include #include #include #include -#include #include #include #include #include #include #include #include #include "mitkBasePropertySerializer.h" #include "mitkPropertyList.h" #include "mitkPropertyListSerializer.h" #include #include #include #include /* #include #include #include #include #include #include #include #include #include #include */ void TestAllProperties(const mitk::PropertyList *propList); /**Documentation * \brief Test for all PropertySerializer classes. * */ int mitkPropertySerializationTest(int /* argc */, char * /*argv*/ []) { MITK_TEST_BEGIN("PropertySerializationTest"); mitk::PropertyListSerializer::Pointer serializer = mitk::PropertyListSerializer::New(); // make sure something from the lib is actually used (registration of // serializers) /* build list of properties that will be serialized and deserialized */ mitk::PropertyList::Pointer propList = mitk::PropertyList::New(); propList->SetProperty("booltrue", mitk::BoolProperty::New(true)); propList->SetProperty("boolfalse", mitk::BoolProperty::New(false)); propList->SetProperty("int", mitk::IntProperty::New(-32)); propList->SetProperty("float", mitk::FloatProperty::New(-31.337)); propList->SetProperty("double", mitk::DoubleProperty::New(-31.337)); propList->SetProperty("string", mitk::StringProperty::New("Hello MITK")); mitk::Point3D p3d; mitk::FillVector3D(p3d, 1.0, 2.2, -3.3); propList->SetProperty("p3d", mitk::Point3dProperty::New(p3d)); mitk::Point3I p3i; mitk::FillVector3D(p3i, 1, 2, -3); propList->SetProperty("p3i", mitk::Point3iProperty::New(p3i)); mitk::Point4D p4d; mitk::FillVector4D(p4d, 1.5, 2.6, -3.7, 4.44); propList->SetProperty("p4d", mitk::Point4dProperty::New(p4d)); mitk::Vector3D v3d; mitk::FillVector3D(v3d, 1.0, 2.2, -3.3); propList->SetProperty("v3d", mitk::Vector3DProperty::New(v3d)); propList->SetProperty("annotation", mitk::AnnotationProperty::New("My Annotation", p3d)); propList->SetProperty("clipping", mitk::ClippingProperty::New(p3d, v3d)); propList->SetProperty("color", mitk::ColorProperty::New(1.0, 0.2, 0.2)); // mitk::EnumerationProperty::Pointer en = mitk::EnumerationProperty::New(); // en->AddEnum("PC", 1); en->AddEnum("Playstation", 2); en->AddEnum("Wii", 111); en->AddEnum("XBox", 7); // en->SetValue("XBox"); // propList->SetProperty("enum", en); /* propList->SetProperty("gridrep", mitk::GridRepresentationProperty::New(2)); propList->SetProperty("gridvol", mitk::GridVolumeMapperProperty::New(0)); propList->SetProperty("OrganTypeProperty", mitk::OrganTypeProperty::New("Larynx")); */ propList->SetProperty("modality", mitk::ModalityProperty::New("Color Doppler")); // propList->SetProperty("OdfNormalizationMethodProperty", mitk::OdfNormalizationMethodProperty::New("Global // Maximum")); // propList->SetProperty("OdfScaleByProperty", mitk::OdfScaleByProperty::New("Principal Curvature")); propList->SetProperty("PlaneOrientationProperty", mitk::PlaneOrientationProperty::New("Arrows in positive direction")); - propList->SetProperty("ShaderProperty", mitk::ShaderProperty::New("fixed")); propList->SetProperty("VtkInterpolationProperty", mitk::VtkInterpolationProperty::New("Gouraud")); propList->SetProperty("VtkRepresentationProperty", mitk::VtkRepresentationProperty::New("Surface")); propList->SetProperty("VtkResliceInterpolationProperty", mitk::VtkResliceInterpolationProperty::New("Cubic")); propList->SetProperty("VtkScalarModeProperty", mitk::VtkScalarModeProperty::New("PointFieldData")); propList->SetProperty("VtkVolumeRenderingProperty", mitk::VtkVolumeRenderingProperty::New("COMPOSITE")); mitk::BoolLookupTable blt; blt.SetTableValue(0, true); blt.SetTableValue(1, false); blt.SetTableValue(2, true); propList->SetProperty("BoolLookupTableProperty", mitk::BoolLookupTableProperty::New(blt)); mitk::FloatLookupTable flt; flt.SetTableValue(0, 3.1); flt.SetTableValue(1, 3.3); flt.SetTableValue(2, 7.0); propList->SetProperty("FloatLookupTableProperty", mitk::FloatLookupTableProperty::New(flt)); mitk::IntLookupTable ilt; ilt.SetTableValue(0, 3); ilt.SetTableValue(1, 2); ilt.SetTableValue(2, 11); propList->SetProperty("IntLookupTableProperty", mitk::IntLookupTableProperty::New(ilt)); mitk::StringLookupTable slt; slt.SetTableValue(0, "Hello"); slt.SetTableValue(1, "MITK"); slt.SetTableValue(2, "world"); propList->SetProperty("StringLookupTableProperty", mitk::StringLookupTableProperty::New(slt)); propList->SetProperty("GroupTagProperty", mitk::GroupTagProperty::New()); propList->SetProperty("LevelWindowProperty", mitk::LevelWindowProperty::New(mitk::LevelWindow(100.0, 50.0))); mitk::LookupTable::Pointer lt = mitk::LookupTable::New(); lt->ChangeOpacityForAll(0.25); lt->ChangeOpacity(17, 0.88); propList->SetProperty("LookupTableProperty", mitk::LookupTableProperty::New(lt)); propList->SetProperty("StringProperty", mitk::StringProperty::New("Oh why, gruel world")); // mitk::TransferFunction::Pointer tf = mitk::TransferFunction::New(); // tf->SetTransferFunctionMode(1); // propList->SetProperty("TransferFunctionProperty", mitk::TransferFunctionProperty::New(tf)); MITK_TEST_CONDITION_REQUIRED(propList->GetMap()->size() > 0, "Initialize PropertyList"); TestAllProperties(propList); /* test default property lists of basedata objects */ // activate the following tests after MaterialProperty is deleted mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetData(mitk::PointSet::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Image::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Surface::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::VtkWidgetRendering::New()); TestAllProperties(node->GetPropertyList()); /* node->SetData(mitk::Contour::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::ContourSet::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Mesh::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Cone::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Cuboid::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Cylinder::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Ellipsoid::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::ExtrudedContour::New()); TestAllProperties(node->GetPropertyList()); node->SetData(mitk::Plane::New()); TestAllProperties(node->GetPropertyList()); //node->SetData(mitk::TrackingVolume::New()); // TrackingVolume is in IGT Module, it does not have special properties, therefore we skip it here //TestAllProperties(node->GetPropertyList()); node->SetData(mitk::UnstructuredGrid::New()); TestAllProperties(node->GetPropertyList()); */ /* untested base data types: BaseDataTestImplementation RenderWindowFrame GeometryData mitk::PlaneGeometryData GradientBackground ItkBaseDataAdapter SlicedData QBallImage SeedsImage TensorImage BoundingObject BoundingObjectGroup */ MITK_TEST_END(); } void TestAllProperties(const mitk::PropertyList *propList) { assert(propList); /* try to serialize each property in the list, then deserialize again and check for equality */ for (mitk::PropertyList::PropertyMap::const_iterator it = propList->GetMap()->begin(); it != propList->GetMap()->end(); ++it) { const mitk::BaseProperty *prop = it->second; // construct name of serializer class std::string serializername = std::string(prop->GetNameOfClass()) + "Serializer"; std::list allSerializers = itk::ObjectFactoryBase::CreateAllInstance(serializername.c_str()); MITK_TEST_CONDITION(allSerializers.size() > 0, std::string("Creating serializers for ") + serializername); if (allSerializers.size() == 0) { MITK_TEST_OUTPUT(<< "serialization not possible, skipping " << prop->GetNameOfClass()); continue; } if (allSerializers.size() > 1) { MITK_TEST_OUTPUT(<< "Warning: " << allSerializers.size() << " serializers found for " << prop->GetNameOfClass() << "testing only the first one."); } mitk::BasePropertySerializer *serializer = dynamic_cast(allSerializers.begin()->GetPointer()); MITK_TEST_CONDITION(serializer != nullptr, serializername + std::string(" is valid")); if (serializer != nullptr) { serializer->SetProperty(prop); TiXmlElement *valueelement = nullptr; try { valueelement = serializer->Serialize(); } catch (...) { } MITK_TEST_CONDITION(valueelement != nullptr, std::string("Serialize property with ") + serializername); if (valueelement == nullptr) { MITK_TEST_OUTPUT(<< "serialization failed, skipping deserialization"); continue; } mitk::BaseProperty::Pointer deserializedProp = serializer->Deserialize(valueelement); MITK_TEST_CONDITION(deserializedProp.IsNotNull(), "serializer created valid property"); if (deserializedProp.IsNotNull()) { MITK_TEST_CONDITION(*(deserializedProp.GetPointer()) == *prop, "deserialized property equals initial property for type " << prop->GetNameOfClass()); } } else { MITK_TEST_OUTPUT(<< "created serializer object is of class " << allSerializers.begin()->GetPointer()->GetNameOfClass()) } } // for all properties } diff --git a/Modules/Segmentation/Algorithms/mitkSegmentationObjectFactory.cpp b/Modules/Segmentation/Algorithms/mitkSegmentationObjectFactory.cpp index 50d81daa56..f9acd0424a 100644 --- a/Modules/Segmentation/Algorithms/mitkSegmentationObjectFactory.cpp +++ b/Modules/Segmentation/Algorithms/mitkSegmentationObjectFactory.cpp @@ -1,142 +1,142 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkSegmentationObjectFactory.h" #include "mitkBaseRenderer.h" #include "mitkCoreObjectFactory.h" #include "mitkDataNode.h" #include "mitkProperties.h" #include "mitkContour.h" #include "mitkContourMapper2D.h" #include "mitkContourSetMapper2D.h" #include "mitkContourSetVtkMapper3D.h" #include "mitkContourVtkMapper3D.h" #include mitk::SegmentationObjectFactory::SegmentationObjectFactory() : CoreObjectFactoryBase() { static bool alreadyDone = false; if (!alreadyDone) { MITK_DEBUG << "SegmentationObjectFactory c'tor" << std::endl; CreateFileExtensionsMap(); alreadyDone = true; } } mitk::Mapper::Pointer mitk::SegmentationObjectFactory::CreateMapper(mitk::DataNode *node, MapperSlotId id) { mitk::Mapper::Pointer newMapper = nullptr; mitk::BaseData *data = node->GetData(); if (id == mitk::BaseRenderer::Standard2D) { std::string classname("ContourModel"); if (dynamic_cast(node->GetData()) != nullptr) { - newMapper = mitk::VtkGLMapperWrapper::New(mitk::ContourMapper2D::New().GetPointer()); + newMapper = mitk::ContourMapper2D::New(); newMapper->SetDataNode(node); } else if (dynamic_cast(node->GetData()) != nullptr) { - newMapper = mitk::VtkGLMapperWrapper::New(mitk::ContourSetMapper2D::New().GetPointer()); + newMapper = mitk::ContourSetMapper2D::New(); newMapper->SetDataNode(node); } } else if (id == mitk::BaseRenderer::Standard3D) { if ((dynamic_cast(data) != nullptr)) { newMapper = mitk::ContourVtkMapper3D::New(); newMapper->SetDataNode(node); } else if ((dynamic_cast(data) != nullptr)) { newMapper = mitk::ContourSetVtkMapper3D::New(); newMapper->SetDataNode(node); } } return newMapper; } void mitk::SegmentationObjectFactory::SetDefaultProperties(mitk::DataNode *node) { if (node == nullptr) return; mitk::DataNode::Pointer nodePointer = node; // mitk::Image::Pointer image = dynamic_cast(node->GetData()); // if(image.IsNotNull() && image->IsInitialized()) // { // mitk::GPUVolumeMapper3D::SetDefaultProperties(node); // } // // if (dynamic_cast(node->GetData())) // { // mitk::UnstructuredGridVtkMapper3D::SetDefaultProperties(node); // } } const char *mitk::SegmentationObjectFactory::GetFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_FileExtensionsMap, fileExtension); return fileExtension.c_str(); } mitk::CoreObjectFactoryBase::MultimapType mitk::SegmentationObjectFactory::GetFileExtensionsMap() { return m_FileExtensionsMap; } mitk::CoreObjectFactoryBase::MultimapType mitk::SegmentationObjectFactory::GetSaveFileExtensionsMap() { return m_SaveFileExtensionsMap; } void mitk::SegmentationObjectFactory::CreateFileExtensionsMap() { } const char *mitk::SegmentationObjectFactory::GetSaveFileExtensions() { std::string fileExtension; this->CreateFileExtensions(m_SaveFileExtensionsMap, fileExtension); return fileExtension.c_str(); } void mitk::SegmentationObjectFactory::RegisterIOFactories() { } struct RegisterSegmentationObjectFactory { RegisterSegmentationObjectFactory() : m_Factory(mitk::SegmentationObjectFactory::New()) { mitk::CoreObjectFactory::GetInstance()->RegisterExtraFactory(m_Factory); } ~RegisterSegmentationObjectFactory() { mitk::CoreObjectFactory::GetInstance()->UnRegisterExtraFactory(m_Factory); } mitk::SegmentationObjectFactory::Pointer m_Factory; }; static RegisterSegmentationObjectFactory registerSegmentationObjectFactory; diff --git a/Modules/Segmentation/Rendering/mitkContourMapper2D.cpp b/Modules/Segmentation/Rendering/mitkContourMapper2D.cpp index 4a76736317..dad9e3f02b 100644 --- a/Modules/Segmentation/Rendering/mitkContourMapper2D.cpp +++ b/Modules/Segmentation/Rendering/mitkContourMapper2D.cpp @@ -1,123 +1,133 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourMapper2D.h" #include "mitkBaseRenderer.h" #include "mitkColorProperty.h" #include "mitkContour.h" #include "mitkPlaneGeometry.h" #include "mitkProperties.h" #include - -#include "mitkGL.h" +#include "vtk_glew.h" mitk::ContourMapper2D::ContourMapper2D() { } mitk::ContourMapper2D::~ContourMapper2D() { } -void mitk::ContourMapper2D::Paint(mitk::BaseRenderer *renderer) +void mitk::ContourMapper2D::ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor * /*actor*/) +{ + float rgba[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; + // check for color prop and use it for rendering if it exists + GetDataNode()->GetColor(rgba, renderer, "color"); + // check for opacity prop and use it for rendering if it exists + GetDataNode()->GetOpacity(rgba[3], renderer, "opacity"); + + glColor4fv(rgba); +} + +void mitk::ContourMapper2D::MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType /*type*/) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) return; //// @FIXME: Logik fuer update bool updateNeccesary = true; if (updateNeccesary) { mitk::Contour::Pointer input = const_cast(this->GetInput()); // apply color and opacity read from the PropertyList ApplyColorAndOpacityProperties(renderer); vtkLinearTransform *transform = GetDataNode()->GetVtkTransform(); // Contour::OutputType point; Contour::BoundingBoxType::PointType point; mitk::Point3D p, projected_p; float vtkp[3]; float lineWidth = 3.0; if (dynamic_cast(this->GetDataNode()->GetProperty("Width")) != nullptr) lineWidth = dynamic_cast(this->GetDataNode()->GetProperty("Width"))->GetValue(); glLineWidth(lineWidth); if (input->GetClosed()) { glBegin(GL_LINE_LOOP); } else { glBegin(GL_LINE_STRIP); } // Contour::InputType end = input->GetContourPath()->EndOfInput(); // if (end > 50000) end = 0; mitk::Contour::PointsContainerPointer points = input->GetPoints(); mitk::Contour::PointsContainerIterator pointsIt = points->Begin(); while (pointsIt != points->End()) { // while ( idx != end ) //{ // point = input->GetContourPath()->Evaluate(idx); point = pointsIt.Value(); itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp, p); renderer->GetCurrentWorldPlaneGeometry()->Project(p, projected_p); bool projectmode = false; GetDataNode()->GetVisibility(projectmode, renderer, "project"); bool drawit = false; if (projectmode) drawit = true; else { Vector3D diff = p - projected_p; if (diff.GetSquaredNorm() < 1.0) drawit = true; } if (drawit) { Point2D pt2d, tmp; renderer->WorldToDisplay(p, pt2d); glVertex2f(pt2d[0], pt2d[1]); } pointsIt++; // idx += 1; } glEnd(); glLineWidth(1.0); } } const mitk::Contour *mitk::ContourMapper2D::GetInput(void) { return static_cast(GetDataNode()->GetData()); } diff --git a/Modules/Segmentation/Rendering/mitkContourMapper2D.h b/Modules/Segmentation/Rendering/mitkContourMapper2D.h index c5cb3d6720..17405305f5 100644 --- a/Modules/Segmentation/Rendering/mitkContourMapper2D.h +++ b/Modules/Segmentation/Rendering/mitkContourMapper2D.h @@ -1,60 +1,62 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITK_CONTOUR_MAPPER_2D_H_ #define MITK_CONTOUR_MAPPER_2D_H_ #include "mitkCommon.h" -#include "mitkGLMapper.h" +#include "mitkMapper.h" #include namespace mitk { class BaseRenderer; class Contour; /** * @brief OpenGL-based mapper to display a mitk::Contour object in a 2D render window * * * @ingroup Mapper */ - class MITKSEGMENTATION_EXPORT ContourMapper2D : public GLMapper + class MITKSEGMENTATION_EXPORT ContourMapper2D : public Mapper { public: - mitkClassMacro(ContourMapper2D, GLMapper); + mitkClassMacro(ContourMapper2D, Mapper); itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** * reimplemented from Baseclass */ - virtual void Paint(BaseRenderer *renderer) override; + void MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type); + + void ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor * actor=nullptr); /** * return a refernce of the rendered data object */ const Contour *GetInput(void); protected: ContourMapper2D(); virtual ~ContourMapper2D(); }; } // namespace mitk #endif /* MITKContourMapper2D_H_HEADER_INCLUDED */ diff --git a/Modules/Segmentation/Rendering/mitkContourSetMapper2D.cpp b/Modules/Segmentation/Rendering/mitkContourSetMapper2D.cpp index 0a05ee511d..cc5beacbfa 100644 --- a/Modules/Segmentation/Rendering/mitkContourSetMapper2D.cpp +++ b/Modules/Segmentation/Rendering/mitkContourSetMapper2D.cpp @@ -1,122 +1,133 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkContourSetMapper2D.h" #include "mitkBaseRenderer.h" #include "mitkColorProperty.h" #include "mitkContourSet.h" #include "mitkPlaneGeometry.h" #include "mitkProperties.h" #include #include "mitkGL.h" mitk::ContourSetMapper2D::ContourSetMapper2D() { } mitk::ContourSetMapper2D::~ContourSetMapper2D() { } -void mitk::ContourSetMapper2D::Paint(mitk::BaseRenderer *renderer) +void mitk::ContourSetMapper2D::ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor * /*actor*/) +{ + float rgba[4] = { 1.0f, 1.0f, 1.0f, 1.0f }; + // check for color prop and use it for rendering if it exists + GetDataNode()->GetColor(rgba, renderer, "color"); + // check for opacity prop and use it for rendering if it exists + GetDataNode()->GetOpacity(rgba[3], renderer, "opacity"); + + glColor4fv(rgba); +} + +void mitk::ContourSetMapper2D::MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType /*type*/) { bool visible = true; GetDataNode()->GetVisibility(visible, renderer, "visible"); if (!visible) return; //// @FIXME: Logik fuer update bool updateNeccesary = true; if (updateNeccesary) { // apply color and opacity read from the PropertyList ApplyColorAndOpacityProperties(renderer); mitk::ContourSet::Pointer input = const_cast(this->GetInput()); mitk::ContourSet::ContourVectorType contourVec = input->GetContours(); mitk::ContourSet::ContourIterator contourIt = contourVec.begin(); while (contourIt != contourVec.end()) { mitk::Contour::Pointer nextContour = (mitk::Contour::Pointer)(*contourIt).second; vtkLinearTransform *transform = GetDataNode()->GetVtkTransform(); // Contour::OutputType point; Contour::BoundingBoxType::PointType point; mitk::Point3D p, projected_p; float vtkp[3]; glLineWidth(nextContour->GetWidth()); if (nextContour->GetClosed()) { glBegin(GL_LINE_LOOP); } else { glBegin(GL_LINE_STRIP); } // float rgba[4]={1.0f,1.0f,1.0f,1.0f}; // if ( nextContour->GetSelected() ) //{ // rgba[0] = 1.0; // rgba[1] = 0.0; // rgba[2] = 0.0; //} // glColor4fv(rgba); mitk::Contour::PointsContainerPointer points = nextContour->GetPoints(); mitk::Contour::PointsContainerIterator pointsIt = points->Begin(); while (pointsIt != points->End()) { point = pointsIt.Value(); itk2vtk(point, vtkp); transform->TransformPoint(vtkp, vtkp); vtk2itk(vtkp, p); renderer->GetCurrentWorldPlaneGeometry()->Project(p, projected_p); Vector3D diff = p - projected_p; if (diff.GetSquaredNorm() < 1.0) { Point2D pt2d, tmp; renderer->WorldToDisplay(p, pt2d); glVertex2f(pt2d[0], pt2d[1]); } pointsIt++; // idx += 1; } glEnd(); glLineWidth(1.0); contourIt++; } } } const mitk::ContourSet *mitk::ContourSetMapper2D::GetInput(void) { return static_cast(GetDataNode()->GetData()); } diff --git a/Modules/Segmentation/Rendering/mitkContourSetMapper2D.h b/Modules/Segmentation/Rendering/mitkContourSetMapper2D.h index 669791cf6a..f74ec27737 100644 --- a/Modules/Segmentation/Rendering/mitkContourSetMapper2D.h +++ b/Modules/Segmentation/Rendering/mitkContourSetMapper2D.h @@ -1,60 +1,62 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef MITK_CONTOUR_SET_MAPPER_2D_H_ #define MITK_CONTOUR_SET_MAPPER_2D_H_ #include "mitkCommon.h" #include "mitkGLMapper.h" #include namespace mitk { class BaseRenderer; class ContourSet; /** * @brief OpenGL-based mapper to display a mitk::Contour object in a 2D render window * * * @ingroup Mapper */ - class MITKSEGMENTATION_EXPORT ContourSetMapper2D : public GLMapper + class MITKSEGMENTATION_EXPORT ContourSetMapper2D : public Mapper { public: - mitkClassMacro(ContourSetMapper2D, GLMapper); + mitkClassMacro(ContourSetMapper2D, Mapper); itkFactorylessNewMacro(Self) itkCloneMacro(Self) /** - * reimplemented from Baseclass - */ - virtual void Paint(mitk::BaseRenderer *renderer) override; + * reimplemented from Baseclass + */ + void MitkRender(mitk::BaseRenderer *renderer, mitk::VtkPropRenderer::RenderType type); + + void ApplyColorAndOpacityProperties(mitk::BaseRenderer *renderer, vtkActor * actor = nullptr); /** * return a refernce of the rendered data object */ const mitk::ContourSet *GetInput(void); protected: ContourSetMapper2D(); virtual ~ContourSetMapper2D(); }; } // namespace mitk #endif /* MITK_CONTOUR_SET_MAPPER_2D_H_ */ diff --git a/Modules/Simulation/CMakeLists.txt b/Modules/Simulation/CMakeLists.txt deleted file mode 100644 index b3ef1affb1..0000000000 --- a/Modules/Simulation/CMakeLists.txt +++ /dev/null @@ -1,10 +0,0 @@ -MITK_CREATE_MODULE( - DEPENDS MitkSceneSerializationBase - PACKAGE_DEPENDS - PUBLIC SOFA - PRIVATE GLUT GLEW -) - -if(TARGET ${MODULE_TARGET}) - target_compile_options(${MODULE_TARGET} PUBLIC "$<$:/wd4068;/wd4250;/wd4251;/wd4267;/wd4275>") -endif() diff --git a/Modules/Simulation/Resources/Interactions/Simulation.xml b/Modules/Simulation/Resources/Interactions/Simulation.xml deleted file mode 100644 index c0bad251b8..0000000000 --- a/Modules/Simulation/Resources/Interactions/Simulation.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Modules/Simulation/Resources/Interactions/SimulationConfig.xml b/Modules/Simulation/Resources/Interactions/SimulationConfig.xml deleted file mode 100644 index 224f082a55..0000000000 --- a/Modules/Simulation/Resources/Interactions/SimulationConfig.xml +++ /dev/null @@ -1,40 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/Modules/Simulation/files.cmake b/Modules/Simulation/files.cmake deleted file mode 100644 index 321bbc9ab1..0000000000 --- a/Modules/Simulation/files.cmake +++ /dev/null @@ -1,30 +0,0 @@ -set(CPP_FILES - mitkGetSimulationService.cpp - mitkExportMitkVisitor.cpp - mitkIndexROI.cpp - mitkISimulationService.cpp - mitkPlaneIntersectionVisitor.cpp - mitkRoundRobinSchedulingAlgorithm.cpp - mitkSetVtkRendererVisitor.cpp - mitkSchedulableProcess.cpp - mitkScheduler.cpp - mitkSchedulingAlgorithmBase.cpp - mitkSimulation.cpp - mitkSimulationActivator.cpp - mitkSimulationInteractor.cpp - mitkSimulationIO.cpp - mitkSimulationObjectFactory.cpp - mitkSimulationSerializer.cpp - mitkSimulationService.cpp - mitkSimulationVtkMapper2D.cpp - mitkSimulationVtkMapper3D.cpp - mitkVtkModel.cpp - mitkVtkSimulationPolyDataMapper2D.cpp - mitkVtkSimulationPolyDataMapper3D.cpp - mitkWeightedRoundRobinSchedulingAlgorithm.cpp -) - -set(RESOURCE_FILES - Interactions/Simulation.xml - Interactions/SimulationConfig.xml -) diff --git a/Modules/Simulation/mitkExportMitkVisitor.cpp b/Modules/Simulation/mitkExportMitkVisitor.cpp deleted file mode 100644 index ce2c402466..0000000000 --- a/Modules/Simulation/mitkExportMitkVisitor.cpp +++ /dev/null @@ -1,230 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkExportMitkVisitor.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -void ApplyMaterial(mitk::DataNode::Pointer dataNode, const sofa::core::loader::Material& material) -{ - using sofa::defaulttype::Vec4f; - - if (dataNode.IsNull() || dynamic_cast(dataNode->GetData()) == nullptr) - return; - - if (material.useDiffuse) - dataNode->SetFloatProperty("opacity", material.diffuse[3]); - - Vec4f ambient = material.useAmbient ? material.ambient : Vec4f(); - Vec4f diffuse = material.useDiffuse ? material.diffuse : Vec4f(); - Vec4f specular = material.useSpecular ? material.specular : Vec4f(); - float shininess = material.useShininess ? std::min(material.shininess, 128.0f) : 45.0f; - - if (shininess == 0.0f) - { - specular.clear(); - shininess = 1.0f; - } - - dataNode->SetFloatProperty("material.ambientCoefficient", 1.0f); - dataNode->SetProperty("material.ambientColor", mitk::ColorProperty::New(ambient.elems)); - - dataNode->SetFloatProperty("material.diffuseCoefficient", 1.0f); - dataNode->SetProperty("color", mitk::ColorProperty::New(diffuse.elems)); - - dataNode->SetFloatProperty("material.specularCoefficient", 1.0f); - dataNode->SetProperty("material.specularColor", mitk::ColorProperty::New(specular.elems)); - dataNode->SetFloatProperty("material.specularPower", shininess); -} - -static mitk::DataNode::Pointer GetSimulationDataNode(mitk::DataStorage::Pointer dataStorage, sofa::core::objectmodel::BaseNode::SPtr rootNode) -{ - if (dataStorage.IsNull()) - return nullptr; - - if (!rootNode) - return nullptr; - - mitk::TNodePredicateDataType::Pointer predicate = mitk::TNodePredicateDataType::New(); - mitk::DataStorage::SetOfObjects::ConstPointer subset = dataStorage->GetSubset(predicate); - - for (mitk::DataStorage::SetOfObjects::ConstIterator it = subset->Begin(); it != subset->End(); ++it) - { - mitk::DataNode::Pointer dataNode = it.Value(); - mitk::Simulation::Pointer simulation = static_cast(dataNode->GetData()); - - if (simulation->GetRootNode() == rootNode) - return dataNode; - } - - return nullptr; -} - - -mitk::ExportMitkVisitor::ExportMitkVisitor(DataStorage::Pointer dataStorage, const sofa::core::ExecParams* params) - : Visitor(params), - m_DataStorage(dataStorage) -{ -} - -mitk::ExportMitkVisitor::ExportMitkVisitor(DataStorage::Pointer dataStorage, const std::string& visualModelName, const sofa::core::ExecParams* params) - : Visitor(params), - m_DataStorage(dataStorage), - m_VisualModelName(visualModelName) -{ -} - -mitk::ExportMitkVisitor::~ExportMitkVisitor() -{ -} - -sofa::simulation::Visitor::Result mitk::ExportMitkVisitor::processNodeTopDown(sofa::simulation::Node* node) -{ - if (m_DataStorage.IsNotNull()) - { - for_each(this, node, node->visualModel, &ExportMitkVisitor::processVisualModel); - return RESULT_CONTINUE; - } - - return RESULT_PRUNE; -} - -void mitk::ExportMitkVisitor::processVisualModel(sofa::simulation::Node* node, sofa::core::visual::VisualModel* visualModel) -{ - using sofa::defaulttype::ResizableExtVector; - typedef sofa::component::visualmodel::VisualModelImpl::VecCoord VecCoord; - typedef sofa::component::visualmodel::VisualModelImpl::Triangle Triangle; - typedef sofa::component::visualmodel::VisualModelImpl::Quad Quad; - typedef sofa::component::visualmodel::VisualModelImpl::Deriv Deriv; - typedef sofa::component::visualmodel::VisualModelImpl::VecTexCoord VecTexCoord; - - sofa::component::visualmodel::VisualModelImpl* visualModelImpl = dynamic_cast(visualModel); - - if (visualModelImpl == nullptr) - return; - - if (!m_VisualModelName.empty() && m_VisualModelName != visualModelImpl->name.getValue()) - return; - - vtkSmartPointer polyData = vtkSmartPointer::New(); - vtkSmartPointer points = vtkSmartPointer::New(); - - const VecCoord& vertices = visualModelImpl->m_vertices2.getValue().empty() - ? visualModelImpl->m_positions.getValue() - : visualModelImpl->m_vertices2.getValue(); - - size_t numPoints = vertices.size(); - - points->SetNumberOfPoints(numPoints); - - for (size_t i = 0; i < numPoints; ++i) - points->SetPoint(i, vertices[i].elems); - - polyData->SetPoints(points); - - vtkSmartPointer polys = vtkSmartPointer::New(); - const ResizableExtVector& triangles = visualModelImpl->m_triangles.getValue(); - - if (!triangles.empty()) - { - ResizableExtVector::const_iterator trianglesEnd = triangles.end(); - - for (ResizableExtVector::const_iterator it = triangles.begin(); it != trianglesEnd; ++it) - { - const Triangle& triangle = *it; - - polys->InsertNextCell(3); - polys->InsertCellPoint(triangle[0]); - polys->InsertCellPoint(triangle[1]); - polys->InsertCellPoint(triangle[2]); - } - } - - const ResizableExtVector& quads = visualModelImpl->m_quads.getValue(); - - if (!quads.empty()) - { - ResizableExtVector::const_iterator quadsEnd = quads.end(); - - for (ResizableExtVector::const_iterator it = quads.begin(); it != quadsEnd; ++it) - { - const Quad& quad = *it; - - polys->InsertNextCell(4); - polys->InsertCellPoint(quad[0]); - polys->InsertCellPoint(quad[1]); - polys->InsertCellPoint(quad[2]); - polys->InsertCellPoint(quad[3]); - } - } - - polyData->SetPolys(polys); - - const ResizableExtVector& normals = visualModelImpl->m_vnormals.getValue(); - - if (!normals.empty()) - { - size_t numNormals = normals.size(); - - vtkSmartPointer vtkNormals = vtkSmartPointer::New(); - vtkNormals->SetNumberOfComponents(3); - vtkNormals->SetNumberOfTuples(numNormals); - - for (size_t i = 0; i < numNormals; ++i) - vtkNormals->SetTuple(i, normals[i].elems); - - polyData->GetPointData()->SetNormals(vtkNormals); - } - - const VecTexCoord& texCoords = visualModelImpl->m_vtexcoords.getValue(); - - if (!texCoords.empty()) - { - size_t numTexCoords = texCoords.size(); - - vtkSmartPointer vtkTexCoords = vtkSmartPointer::New(); - vtkTexCoords->SetNumberOfComponents(2); - vtkTexCoords->SetNumberOfTuples(numTexCoords); - - for (size_t i = 0; i < numTexCoords; ++i) - vtkTexCoords->SetTuple(i, texCoords[i].elems); - - polyData->GetPointData()->SetTCoords(vtkTexCoords); - } - - Surface::Pointer surface = Surface::New(); - surface->SetVtkPolyData(polyData); - - DataNode::Pointer dataNode = DataNode::New(); - dataNode->SetName(visualModelImpl->name.getValue()); - dataNode->SetData(surface); - - ApplyMaterial(dataNode, visualModelImpl->material.getValue()); - - DataNode::Pointer parentDataNode = GetSimulationDataNode(m_DataStorage, node->getRoot()); - - if (parentDataNode.IsNotNull()) - surface->SetGeometry(parentDataNode->GetData()->GetGeometry()); - - m_DataStorage->Add(dataNode, parentDataNode); -} diff --git a/Modules/Simulation/mitkExportMitkVisitor.h b/Modules/Simulation/mitkExportMitkVisitor.h deleted file mode 100644 index e498e4a10f..0000000000 --- a/Modules/Simulation/mitkExportMitkVisitor.h +++ /dev/null @@ -1,47 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkExportMitkVisitor_h -#define mitkExportMitkVisitor_h - -#include -#include -#include - -namespace mitk -{ - class MITKSIMULATION_EXPORT ExportMitkVisitor : public sofa::simulation::Visitor - { - public: - explicit ExportMitkVisitor(DataStorage::Pointer dataStorage, const sofa::core::ExecParams* params = sofa::core::ExecParams::defaultInstance()); - ExportMitkVisitor(DataStorage::Pointer dataStorage, const std::string& visualModelName, const sofa::core::ExecParams* params = sofa::core::ExecParams::defaultInstance()); - ~ExportMitkVisitor(); - - using sofa::simulation::Visitor::processNodeTopDown; - Result processNodeTopDown(sofa::simulation::Node* node) override; - - private: - ExportMitkVisitor(const ExportMitkVisitor&); - ExportMitkVisitor& operator=(const ExportMitkVisitor&); - - void processVisualModel(sofa::simulation::Node* node, sofa::core::visual::VisualModel* visualModel); - - DataStorage::Pointer m_DataStorage; - std::string m_VisualModelName; - }; -} - -#endif diff --git a/Modules/Simulation/mitkGetSimulationService.cpp b/Modules/Simulation/mitkGetSimulationService.cpp deleted file mode 100644 index 06f144c648..0000000000 --- a/Modules/Simulation/mitkGetSimulationService.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkGetSimulationService.h" -#include -#include -#include - -mitk::ISimulationService* mitk::GetSimulationService(us::ModuleContext* moduleContext) -{ - if (moduleContext == nullptr) - return nullptr; - - us::ServiceReference serviceReference = moduleContext->GetServiceReference(); - return moduleContext->GetService(serviceReference); -} diff --git a/Modules/Simulation/mitkGetSimulationService.h b/Modules/Simulation/mitkGetSimulationService.h deleted file mode 100644 index 76981cb1d6..0000000000 --- a/Modules/Simulation/mitkGetSimulationService.h +++ /dev/null @@ -1,35 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkGetSimulationService_h -#define mitkGetSimulationService_h - -#include -#include - -namespace us -{ - class ModuleContext; -} - -namespace mitk -{ - class ISimulationService; - - MITKSIMULATION_EXPORT ISimulationService* GetSimulationService(us::ModuleContext* moduleContext = us::GetModuleContext()); -} - -#endif diff --git a/Modules/Simulation/mitkISimulationService.cpp b/Modules/Simulation/mitkISimulationService.cpp deleted file mode 100644 index 490e58332f..0000000000 --- a/Modules/Simulation/mitkISimulationService.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkISimulationService.h" - -mitk::ISimulationService::ISimulationService() -{ -} - -mitk::ISimulationService::~ISimulationService() -{ -} diff --git a/Modules/Simulation/mitkISimulationService.h b/Modules/Simulation/mitkISimulationService.h deleted file mode 100644 index dc75baf824..0000000000 --- a/Modules/Simulation/mitkISimulationService.h +++ /dev/null @@ -1,47 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkISimulationService_h -#define mitkISimulationService_h - -#include -#include -#include - -namespace mitk -{ - class Scheduler; - - class MITKSIMULATION_EXPORT ISimulationService - { - public: - virtual Simulation::Pointer GetActiveSimulation() const = 0; - virtual void SetActiveSimulation(Simulation::Pointer activeSimulation) = 0; - virtual Scheduler* GetScheduler() = 0; - - protected: - ISimulationService(); - virtual ~ISimulationService(); - - private: - ISimulationService(const ISimulationService&); - ISimulationService& operator=(const ISimulationService&); - }; -} - -MITK_DECLARE_SERVICE_INTERFACE(mitk::ISimulationService, "org.mitk.ISimulationService"); - -#endif diff --git a/Modules/Simulation/mitkIndexROI.cpp b/Modules/Simulation/mitkIndexROI.cpp deleted file mode 100644 index ac4dd538e0..0000000000 --- a/Modules/Simulation/mitkIndexROI.cpp +++ /dev/null @@ -1,113 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkIndexROI.h" -#include -#include -#include - -mitk::IndexROI::IndexROI() - : m_First(initData(&m_First, "first", "")), - m_Last(initData(&m_Last, "last", "")), - m_Individual(initData(&m_Individual, "individual", "")), - m_Indices(initData(&m_Indices, "indices", "")), - m_PointsInROI(initData(&m_PointsInROI, "pointsInROI", "")), - m_Position(initData(&m_Position, "position", "")) -{ -} - -mitk::IndexROI::~IndexROI() -{ -} - -void mitk::IndexROI::init() -{ - using sofa::core::loader::MeshLoader; - using sofa::core::objectmodel::BaseContext; - using sofa::core::objectmodel::BaseData; - typedef sofa::core::topology::BaseMeshTopology::SetIndex SetIndex; - typedef sofa::defaulttype::ExtVec3fTypes::VecCoord VecCoord; - - if (!m_Position.isSet()) - { - MeshLoader* loader = nullptr; - this->getContext()->get(loader, BaseContext::Local); - - if (loader != nullptr) - { - BaseData* parent = loader->findField("position"); - - if (parent != nullptr) - { - m_Position.setParent(parent); - m_Position.setReadOnly(true); - } - } - } - - if (!m_Indices.isSet()) - { - sofa::helper::WriteAccessor > indices = m_Indices; - - const VecCoord& position = m_Position.getValue(); - unsigned int numPositions = static_cast(position.size()); - unsigned int first = std::min(m_First.getValue(), numPositions); - - for (size_t i = 0; i < first; ++i) - indices.push_back(i); - - unsigned int last = numPositions - std::min(m_Last.getValue(), numPositions - first); - - for (size_t i = last; i < numPositions; ++i) - indices.push_back(i); - - SetIndex individual = m_Individual.getValue(); - size_t numIndividuals = individual.size(); - - for (size_t i = 0; i < numIndividuals; ++i) - { - unsigned int index = individual[i]; - - if (index >= first && index < last) - indices.push_back(index); - } - } - - this->addInput(&m_Indices); - this->addInput(&m_Position); - - this->addOutput(&m_PointsInROI); - - this->setDirtyValue(); -} - -void mitk::IndexROI::update() -{ - typedef sofa::core::topology::BaseMeshTopology::SetIndex SetIndex; - typedef sofa::defaulttype::ExtVec3fTypes::VecCoord VecCoord; - - this->cleanDirty(); - - sofa::helper::WriteAccessor > pointsInROI = m_PointsInROI; - pointsInROI.clear(); - - const VecCoord& position = m_Position.getValue(); - SetIndex indices = m_Indices.getValue(); - size_t numIndices = indices.size(); - - for (size_t i = 0; i < numIndices; ++i) - pointsInROI.push_back(position[indices[i]]); -} diff --git a/Modules/Simulation/mitkIndexROI.h b/Modules/Simulation/mitkIndexROI.h deleted file mode 100644 index 3271c1a362..0000000000 --- a/Modules/Simulation/mitkIndexROI.h +++ /dev/null @@ -1,50 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkIndexROI_h -#define mitkIndexROI_h - -#include -#include -#include - -namespace mitk -{ - class MITKSIMULATION_EXPORT IndexROI : public sofa::core::DataEngine - { - public: - SOFA_CLASS(IndexROI, sofa::core::DataEngine); - - void init() override; - void update() override; - - sofa::core::objectmodel::Data m_First; - sofa::core::objectmodel::Data m_Last; - sofa::core::objectmodel::Data m_Individual; - sofa::core::objectmodel::Data m_Indices; - sofa::core::objectmodel::Data m_PointsInROI; - sofa::core::objectmodel::Data m_Position; - - private: - IndexROI(); - ~IndexROI(); - - IndexROI(const MyType&); - MyType& operator=(const MyType&); - }; -} - -#endif diff --git a/Modules/Simulation/mitkPlaneIntersectionVisitor.cpp b/Modules/Simulation/mitkPlaneIntersectionVisitor.cpp deleted file mode 100644 index 6bf0e9d5da..0000000000 --- a/Modules/Simulation/mitkPlaneIntersectionVisitor.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkPlaneIntersectionVisitor.h" -#include - -mitk::PlaneIntersectionVisitor::PlaneIntersectionVisitor(const Point3D& point, const Vector3D& normal, const sofa::core::ExecParams* params) - : Visitor(params), - m_Point(point), - m_Normal(normal) -{ -} - -mitk::PlaneIntersectionVisitor::~PlaneIntersectionVisitor() -{ -} - -const std::vector& mitk::PlaneIntersectionVisitor::GetIntersections() const -{ - return m_Intersections; -} - -sofa::simulation::Visitor::Result mitk::PlaneIntersectionVisitor::processNodeTopDown(sofa::simulation::Node* node) -{ - for_each(this, node, node->visualModel, &PlaneIntersectionVisitor::processVisualModel); - return RESULT_CONTINUE; -} - -void mitk::PlaneIntersectionVisitor::processVisualModel(sofa::simulation::Node*, sofa::core::visual::VisualModel* visualModel) -{ - using sofa::component::visualmodel::VisualModelImpl; - using sofa::core::topology::Triangle; - using sofa::core::topology::Quad; - using sofa::defaulttype::ResizableExtVector; - - typedef VisualModelImpl::VecCoord VecCoord; - - VisualModelImpl* visualModelImpl = dynamic_cast(visualModel); - - if (visualModelImpl == nullptr) - return; - - const sofa::core::loader::Material& material = visualModelImpl->material.getValue(); - - if (!material.useDiffuse) - return; - - const VecCoord& verts = visualModelImpl->getVertices(); - const ResizableExtVector& tris = visualModelImpl->getTriangles(); - const ResizableExtVector& quads = visualModelImpl->getQuads(); - - float n[3] = { static_cast(m_Normal[0]), static_cast(m_Normal[1]), static_cast(m_Normal[2]) }; - float p[3] = { static_cast(m_Point[0]), static_cast(m_Point[1]), static_cast(m_Point[2]) }; - float d[4]; - int j; - const float* t0; - const float* t1; - const float* t2; - float s; - Edge edge; - Intersection intersection; - - const size_t numTriangles = tris.size(); - - for (size_t i = 0; i < numTriangles; ++i) - { - t0 = verts[tris[i][0]].data(); - t1 = verts[tris[i][1]].data(); - t2 = verts[tris[i][2]].data(); - - d[0] = n[0] * (p[0] - t0[0]) + n[1] * (p[1] - t0[1]) + n[2] * (p[2] - t0[2]); - d[1] = n[0] * (p[0] - t1[0]) + n[1] * (p[1] - t1[1]) + n[2] * (p[2] - t1[2]); - d[2] = n[0] * (p[0] - t2[0]) + n[1] * (p[1] - t2[1]) + n[2] * (p[2] - t2[2]); - - if (d[0] * d[1] < 0.0f) - { - j = d[0] * d[2] < 0.0f - ? 0 - : 1; - } - else if (d[0] * d[2] < 0.0f) - { - j = 2; - } - else - { - continue; - } - - t0 = verts[tris[i][j]].data(); - t1 = verts[tris[i][(j + 1) % 3]].data(); - t2 = verts[tris[i][(j + 2) % 3]].data(); - - s = (n[0] * (p[0] - t0[0]) + n[1] * (p[1] - t0[1]) + n[2] * (p[2] - t0[2])) / (n[0] * (t1[0] - t0[0]) + n[1] * (t1[1] - t0[1]) + n[2] * (t1[2] - t0[2])); - - edge.v0[0] = static_cast(t0[0] + s * (t1[0] - t0[0])); - edge.v0[1] = static_cast(t0[1] + s * (t1[1] - t0[1])); - edge.v0[2] = static_cast(t0[2] + s * (t1[2] - t0[2])); - - s = (n[0] * (p[0] - t0[0]) + n[1] * (p[1] - t0[1]) + n[2] * (p[2] - t0[2])) / (n[0] * (t2[0] - t0[0]) + n[1] * (t2[1] - t0[1]) + n[2] * (t2[2] - t0[2])); - - edge.v1[0] = static_cast(t0[0] + s * (t2[0] - t0[0])); - edge.v1[1] = static_cast(t0[1] + s * (t2[1] - t0[1])); - edge.v1[2] = static_cast(t0[2] + s * (t2[2] - t0[2])); - - intersection.edges.push_back(edge); - } - - const float* q0; - const float* q1; - const float* q2; - const float* q3; - - const size_t numQuads = quads.size(); - - for (size_t i = 0; i < numQuads; ++i) - { - q0 = verts[quads[i][0]].data(); - q1 = verts[quads[i][1]].data(); - q2 = verts[quads[i][2]].data(); - q3 = verts[quads[i][3]].data(); - - d[0] = n[0] * (p[0] - q0[0]) + n[1] * (p[1] - q0[1]) + n[2] * (p[2] - q0[2]); - d[1] = n[0] * (p[0] - q1[0]) + n[1] * (p[1] - q1[1]) + n[2] * (p[2] - q1[2]); - d[2] = n[0] * (p[0] - q2[0]) + n[1] * (p[1] - q2[1]) + n[2] * (p[2] - q2[2]); - d[3] = n[0] * (p[0] - q3[0]) + n[1] * (p[1] - q3[1]) + n[2] * (p[2] - q3[2]); - - if (d[0] * d[2] < 0.0f) - { - if (d[0] * d[3] < 0.0f) - { - if (d[0] * d[1] < 0.0f) - { - q2 = q0; - } - else - { - const float* q = q0; - q0 = q1; - q1 = q2; - q2 = q; - } - } - else if (d[0] * d[1] >= 0.0f) - { - q0 = q1; - q1 = q2; - } - } - else if (d[1] * d[3] < 0.0f) - { - if (d[1] * d[0] < 0.0f) - { - q3 = q2; - q2 = q1; - } - else - { - q1 = q3; - } - } - else - { - continue; - } - - s = (n[0] * (p[0] - q0[0]) + n[1] * (p[1] - q0[1]) + n[2] * (p[2] - q0[2])) / (n[0] * (q1[0] - q0[0]) + n[1] * (q1[1] - q0[1]) + n[2] * (q1[2] - q0[2])); - - edge.v0[0] = static_cast(q0[0] + s * (q1[0] - q0[0])); - edge.v0[1] = static_cast(q0[1] + s * (q1[1] - q0[1])); - edge.v0[2] = static_cast(q0[2] + s * (q1[2] - q0[2])); - - s = (n[0] * (p[0] - q2[0]) + n[1] * (p[1] - q2[1]) + n[2] * (p[2] - q2[2])) / (n[0] * (q3[0] - q2[0]) + n[1] * (q3[1] - q2[1]) + n[2] * (q3[2] - q2[2])); - - edge.v1[0] = static_cast(q2[0] + s * (q3[0] - q2[0])); - edge.v1[1] = static_cast(q2[1] + s * (q3[1] - q2[1])); - edge.v1[2] = static_cast(q2[2] + s * (q3[2] - q2[2])); - - intersection.edges.push_back(edge); - } - - if (!intersection.edges.empty()) - { - intersection.color[0] = material.diffuse[0]; - intersection.color[1] = material.diffuse[1]; - intersection.color[2] = material.diffuse[2]; - intersection.color[3] = material.diffuse[3]; - - m_Intersections.push_back(intersection); - } -} diff --git a/Modules/Simulation/mitkPlaneIntersectionVisitor.h b/Modules/Simulation/mitkPlaneIntersectionVisitor.h deleted file mode 100644 index 72ec905c17..0000000000 --- a/Modules/Simulation/mitkPlaneIntersectionVisitor.h +++ /dev/null @@ -1,63 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkPlaneIntersectionVisitor_h -#define mitkPlaneIntersectionVisitor_h - -#include -#include -#include -#include - -namespace mitk -{ - class MITKSIMULATION_EXPORT PlaneIntersectionVisitor : public sofa::simulation::Visitor - { - public: - struct Edge - { - Point3D v0; - Point3D v1; - }; - - struct Intersection - { - float color[4]; - std::vector edges; - }; - - PlaneIntersectionVisitor(const Point3D& point, const Vector3D& normal, const sofa::core::ExecParams* params = sofa::core::ExecParams::defaultInstance()); - ~PlaneIntersectionVisitor(); - - const std::vector& GetIntersections() const; - - using sofa::simulation::Visitor::processNodeTopDown; - Result processNodeTopDown(sofa::simulation::Node* node) override; - - private: - PlaneIntersectionVisitor(const PlaneIntersectionVisitor&); - PlaneIntersectionVisitor& operator=(const PlaneIntersectionVisitor&); - - void processVisualModel(sofa::simulation::Node*, sofa::core::visual::VisualModel* visualModel); - - Point3D m_Point; - Vector3D m_Normal; - - std::vector m_Intersections; - }; -} - -#endif diff --git a/Modules/Simulation/mitkRoundRobinSchedulingAlgorithm.cpp b/Modules/Simulation/mitkRoundRobinSchedulingAlgorithm.cpp deleted file mode 100644 index c7a0662c2f..0000000000 --- a/Modules/Simulation/mitkRoundRobinSchedulingAlgorithm.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSchedulableProcess.h" -#include "mitkRoundRobinSchedulingAlgorithm.h" - -mitk::RoundRobinSchedulingAlgorithm::RoundRobinSchedulingAlgorithm() -{ -} - -mitk::RoundRobinSchedulingAlgorithm::~RoundRobinSchedulingAlgorithm() -{ -} - -mitk::SchedulableProcess* mitk::RoundRobinSchedulingAlgorithm::GetNextProcess(std::vector& processQueue) -{ - size_t numProcesses = processQueue.size(); - - if (numProcesses == 0) - return nullptr; - - mitk::SchedulableProcess* process = processQueue[0]; - - if (numProcesses > 1) - { - processQueue.erase(processQueue.begin()); - processQueue.push_back(process); - } - - return process; -} diff --git a/Modules/Simulation/mitkRoundRobinSchedulingAlgorithm.h b/Modules/Simulation/mitkRoundRobinSchedulingAlgorithm.h deleted file mode 100644 index 3a2b980033..0000000000 --- a/Modules/Simulation/mitkRoundRobinSchedulingAlgorithm.h +++ /dev/null @@ -1,34 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkRoundRobinSchedulingAlgorithm_h -#define mitkRoundRobinSchedulingAlgorithm_h - -#include "mitkSchedulingAlgorithmBase.h" - -namespace mitk -{ - class RoundRobinSchedulingAlgorithm : public SchedulingAlgorithmBase - { - public: - RoundRobinSchedulingAlgorithm(); - ~RoundRobinSchedulingAlgorithm(); - - SchedulableProcess* GetNextProcess(std::vector& processQueue) override; - }; -} - -#endif diff --git a/Modules/Simulation/mitkSchedulableProcess.cpp b/Modules/Simulation/mitkSchedulableProcess.cpp deleted file mode 100644 index 0849942deb..0000000000 --- a/Modules/Simulation/mitkSchedulableProcess.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSchedulableProcess.h" -#include - -mitk::SchedulableProcess::SchedulableProcess(int priority) - : m_Priority(priority) -{ -} - -mitk::SchedulableProcess::~SchedulableProcess() -{ -} - -int mitk::SchedulableProcess::GetPriority() const -{ - return m_Priority; -} - -boost::chrono::nanoseconds mitk::SchedulableProcess::GetTotalElapsedTime() const -{ - return m_TotalElapsedTime; -} - -void mitk::SchedulableProcess::ResetTotalElapsedTime(boost::chrono::nanoseconds carryover) -{ - m_TotalElapsedTime = carryover; -} - -boost::chrono::nanoseconds mitk::SchedulableProcess::GetElapsedTime() const -{ - return m_ElapsedTime; -} - -void mitk::SchedulableProcess::SetElapsedTime(boost::chrono::nanoseconds elapsedTime) -{ - m_TotalElapsedTime += elapsedTime; - m_ElapsedTime = elapsedTime; -} diff --git a/Modules/Simulation/mitkSchedulableProcess.h b/Modules/Simulation/mitkSchedulableProcess.h deleted file mode 100644 index 5a6eaab339..0000000000 --- a/Modules/Simulation/mitkSchedulableProcess.h +++ /dev/null @@ -1,49 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSchedulableProcess_h -#define mitkSchedulableProcess_h - -#include -#include - -namespace mitk -{ - class MITKSIMULATION_EXPORT SchedulableProcess - { - public: - explicit SchedulableProcess(int priority = 0); - virtual ~SchedulableProcess(); - - int GetPriority() const; - boost::chrono::nanoseconds GetTotalElapsedTime() const; - void ResetTotalElapsedTime(boost::chrono::nanoseconds carryover = boost::chrono::nanoseconds::zero()); - boost::chrono::nanoseconds GetElapsedTime() const; - - protected: - void SetElapsedTime(boost::chrono::nanoseconds elapsedTime); - - private: - SchedulableProcess(const SchedulableProcess&); - SchedulableProcess& operator=(const SchedulableProcess&); - - int m_Priority; - boost::chrono::nanoseconds m_TotalElapsedTime; - boost::chrono::nanoseconds m_ElapsedTime; - }; -} - -#endif diff --git a/Modules/Simulation/mitkScheduler.cpp b/Modules/Simulation/mitkScheduler.cpp deleted file mode 100644 index e8d765927c..0000000000 --- a/Modules/Simulation/mitkScheduler.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkRoundRobinSchedulingAlgorithm.h" -#include "mitkSchedulableProcess.h" -#include "mitkScheduler.h" -#include "mitkWeightedRoundRobinSchedulingAlgorithm.h" -#include -#include -#include - -struct mitk::Scheduler::Impl -{ - std::vector processQueue; - SchedulingAlgorithmBase* algorithm; -}; - -mitk::Scheduler::Scheduler(SchedulingAlgorithm::Enum algorithm) - : m_Impl(new Impl) -{ - switch (algorithm) - { - case mitk::SchedulingAlgorithm::RoundRobin: - m_Impl->algorithm = new mitk::RoundRobinSchedulingAlgorithm; - break; - - case mitk::SchedulingAlgorithm::WeightedRoundRobin: - m_Impl->algorithm = new mitk::WeightedRoundRobinSchedulingAlgorithm; - break; - - default: - assert(false && "Unknown scheduling algorithm!"); - } -} - -mitk::Scheduler::~Scheduler() -{ - delete m_Impl->algorithm; - delete m_Impl; -} - -void mitk::Scheduler::AddProcess(SchedulableProcess* process) -{ - if (process == nullptr) - return; - - if (std::find(m_Impl->processQueue.begin(), m_Impl->processQueue.end(), process) == m_Impl->processQueue.end()) - m_Impl->processQueue.push_back(process); -} - -void mitk::Scheduler::RemoveProcess(SchedulableProcess* process) -{ - if (process == nullptr) - return; - - auto it = std::find(m_Impl->processQueue.begin(), m_Impl->processQueue.end(), process); - - if (it != m_Impl->processQueue.end()) - m_Impl->processQueue.erase(it); -} - -bool mitk::Scheduler::IsEmpty() const -{ - return m_Impl->processQueue.empty(); -} - -mitk::SchedulableProcess* mitk::Scheduler::GetCurrentProcess() -{ - return !m_Impl->processQueue.empty() - ? m_Impl->processQueue[0] - : nullptr; -} - -mitk::SchedulableProcess* mitk::Scheduler::GetNextProcess() -{ - return m_Impl->algorithm->GetNextProcess(m_Impl->processQueue); -} diff --git a/Modules/Simulation/mitkScheduler.h b/Modules/Simulation/mitkScheduler.h deleted file mode 100644 index efcf6f0e64..0000000000 --- a/Modules/Simulation/mitkScheduler.h +++ /dev/null @@ -1,57 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkScheduler_h -#define mitkScheduler_h - -#include - -namespace mitk -{ - class SchedulableProcess; - class SchedulingAlgorithmBase; - - namespace SchedulingAlgorithm - { - enum Enum - { - RoundRobin, - WeightedRoundRobin - }; - } - - class MITKSIMULATION_EXPORT Scheduler - { - public: - explicit Scheduler(SchedulingAlgorithm::Enum algorithm = SchedulingAlgorithm::RoundRobin); - ~Scheduler(); - - void AddProcess(SchedulableProcess* process); - void RemoveProcess(SchedulableProcess* process); - bool IsEmpty() const; - SchedulableProcess* GetCurrentProcess(); - SchedulableProcess* GetNextProcess(); - - private: - Scheduler(const Scheduler&); - Scheduler& operator=(const Scheduler&); - - struct Impl; - Impl* m_Impl; - }; -} - -#endif diff --git a/Modules/Simulation/mitkSchedulingAlgorithmBase.cpp b/Modules/Simulation/mitkSchedulingAlgorithmBase.cpp deleted file mode 100644 index 0a1586c71a..0000000000 --- a/Modules/Simulation/mitkSchedulingAlgorithmBase.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSchedulableProcess.h" -#include "mitkSchedulingAlgorithmBase.h" - -mitk::SchedulingAlgorithmBase::SchedulingAlgorithmBase() -{ -} - -mitk::SchedulingAlgorithmBase::~SchedulingAlgorithmBase() -{ -} diff --git a/Modules/Simulation/mitkSchedulingAlgorithmBase.h b/Modules/Simulation/mitkSchedulingAlgorithmBase.h deleted file mode 100644 index 3f39462171..0000000000 --- a/Modules/Simulation/mitkSchedulingAlgorithmBase.h +++ /dev/null @@ -1,40 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSchedulingAlgorithmBase_h -#define mitkSchedulingAlgorithmBase_h - -#include - -namespace mitk -{ - class SchedulableProcess; - - class SchedulingAlgorithmBase - { - public: - SchedulingAlgorithmBase(); - virtual ~SchedulingAlgorithmBase(); - - virtual SchedulableProcess* GetNextProcess(std::vector& processQueue) = 0; - - private: - SchedulingAlgorithmBase(const SchedulingAlgorithmBase&); - SchedulingAlgorithmBase& operator=(const SchedulingAlgorithmBase&); - }; -} - -#endif diff --git a/Modules/Simulation/mitkSetVtkRendererVisitor.cpp b/Modules/Simulation/mitkSetVtkRendererVisitor.cpp deleted file mode 100644 index 6ee916a666..0000000000 --- a/Modules/Simulation/mitkSetVtkRendererVisitor.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSetVtkRendererVisitor.h" -#include "mitkVtkModel.h" - -mitk::SetVtkRendererVisitor::SetVtkRendererVisitor(vtkRenderer* renderer, const sofa::core::ExecParams* params) - : Visitor(params), - m_VtkRenderer(renderer) -{ -} - -mitk::SetVtkRendererVisitor::~SetVtkRendererVisitor() -{ -} - -sofa::simulation::Visitor::Result mitk::SetVtkRendererVisitor::processNodeTopDown(sofa::simulation::Node* node) -{ - for_each(this, node, node->visualModel, &SetVtkRendererVisitor::processVisualModel); - return RESULT_CONTINUE; -} - -void mitk::SetVtkRendererVisitor::processVisualModel(sofa::simulation::Node*, sofa::core::visual::VisualModel* visualModel) -{ - VtkModel* vtkModel = dynamic_cast(visualModel); - - if (vtkModel != nullptr) - vtkModel->SetVtkRenderer(m_VtkRenderer); -} diff --git a/Modules/Simulation/mitkSetVtkRendererVisitor.h b/Modules/Simulation/mitkSetVtkRendererVisitor.h deleted file mode 100644 index bde90696dc..0000000000 --- a/Modules/Simulation/mitkSetVtkRendererVisitor.h +++ /dev/null @@ -1,46 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSetVtkRendererVisitor_h -#define mitkSetVtkRendererVisitor_h - -#include -#include - -class vtkRenderer; - -namespace mitk -{ - class MITKSIMULATION_EXPORT SetVtkRendererVisitor : public sofa::simulation::Visitor - { - public: - explicit SetVtkRendererVisitor(vtkRenderer* renderer, const sofa::core::ExecParams* params = sofa::core::ExecParams::defaultInstance()); - ~SetVtkRendererVisitor(); - - using sofa::simulation::Visitor::processNodeTopDown; - Result processNodeTopDown(sofa::simulation::Node* node) override; - - private: - SetVtkRendererVisitor(const SetVtkRendererVisitor&); - SetVtkRendererVisitor& operator=(const SetVtkRendererVisitor&); - - void processVisualModel(sofa::simulation::Node*, sofa::core::visual::VisualModel* visualModel); - - vtkRenderer* m_VtkRenderer; - }; -} - -#endif diff --git a/Modules/Simulation/mitkSimulation.cpp b/Modules/Simulation/mitkSimulation.cpp deleted file mode 100644 index 3c815459f6..0000000000 --- a/Modules/Simulation/mitkSimulation.cpp +++ /dev/null @@ -1,169 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSimulation.h" -#include -#include "mitkGeometry3D.h" - -static sofa::simulation::Simulation::SPtr CreateSimulation() -{ - const std::string key = "MultiMappingObject"; - - if (sofa::simulation::xml::BaseElement::NodeFactory::HasKey(key)) - sofa::simulation::xml::BaseElement::NodeFactory::ResetEntry(key); - - return sofa::core::objectmodel::New(); -} - -mitk::Simulation::Simulation() - : m_SOFASimulation(CreateSimulation()) -{ -} - -mitk::Simulation::~Simulation() -{ - if (m_RootNode) - { - if (m_SOFASimulation) - m_SOFASimulation->unload(m_RootNode); - } -} - -void mitk::Simulation::Animate() -{ - if (!m_RootNode || !m_SOFASimulation) - return; - - boost::chrono::high_resolution_clock::time_point t0 = boost::chrono::high_resolution_clock::now(); - m_SOFASimulation->animate(m_RootNode.get(), m_RootNode->getDt()); - this->SetElapsedTime(boost::chrono::high_resolution_clock::now() - t0); - - this->UpdateOutputInformation(); -} - -sofa::core::visual::DrawTool* mitk::Simulation::GetDrawTool() -{ - return &m_DrawTool; -} - -sofa::simulation::Node::SPtr mitk::Simulation::GetRootNode() const -{ - return m_RootNode; -} - -sofa::simulation::Simulation::SPtr mitk::Simulation::GetSOFASimulation() const -{ - return m_SOFASimulation; -} - -void mitk::Simulation::Reset() -{ - if (!m_RootNode || !m_SOFASimulation) - return; - - m_SOFASimulation->reset(m_RootNode.get()); - m_RootNode->setTime(0.0); - m_SOFASimulation->updateContext(m_RootNode.get()); -} - -bool mitk::Simulation::GetAnimationFlag() const -{ - return m_RootNode - ? m_RootNode->getContext()->getAnimate() - : false; -} - -void mitk::Simulation::SetAnimationFlag(bool animate) -{ - if (m_RootNode) - m_RootNode->getContext()->setAnimate(animate); -} - -void mitk::Simulation::SetDt(double dt) -{ - if (m_RootNode) - m_RootNode->setDt(dt); -} - -void mitk::Simulation::SetRootNode(sofa::simulation::Node::SPtr rootNode) -{ - m_RootNode = rootNode; -} - -bool mitk::Simulation::RequestedRegionIsOutsideOfTheBufferedRegion() -{ - return false; -} - -void mitk::Simulation::SetRequestedRegion(const itk::DataObject*) -{ -} - -void mitk::Simulation::SetRequestedRegionToLargestPossibleRegion() -{ -} - -void mitk::Simulation::UpdateOutputInformation() -{ - using sofa::defaulttype::BoundingBox; - using sofa::defaulttype::Vector3; - - if (this->GetSource().IsNotNull()) - this->GetSource()->UpdateOutputInformation(); - - if (m_RootNode) - { - const BoundingBox& boundingBox = m_RootNode->f_bbox.getValue(); - mitk::Geometry3D::BoundsArrayType bounds; - - if (boundingBox.isValid()) - { - const Vector3& min = boundingBox.minBBox(); - const Vector3& max = boundingBox.maxBBox(); - - bounds[0] = static_cast(min.x()); - bounds[1] = static_cast(max.x()); - bounds[2] = static_cast(min.y()); - bounds[3] = static_cast(max.y()); - bounds[4] = static_cast(min.z()); - bounds[5] = static_cast(max.z()); - } - else - { - bounds.Fill(0.0f); - } - - mitk::BaseGeometry::Pointer geometry = this->GetGeometry(); - - if (geometry.IsNull()) - { - geometry = Geometry3D::New(); - geometry->SetBounds(bounds); - this->SetGeometry(geometry); - } - else - { - geometry->SetBounds(bounds); - } - } - - this->GetTimeGeometry()->Update(); -} - -bool mitk::Simulation::VerifyRequestedRegion() -{ - return true; -} diff --git a/Modules/Simulation/mitkSimulation.h b/Modules/Simulation/mitkSimulation.h deleted file mode 100644 index cc1af57ab8..0000000000 --- a/Modules/Simulation/mitkSimulation.h +++ /dev/null @@ -1,61 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSimulation_h -#define mitkSimulation_h - -#include -#include -#include -#include -#include - -namespace mitk -{ - class MITKSIMULATION_EXPORT Simulation : public BaseData, public SchedulableProcess - { - public: - mitkClassMacro(Simulation, BaseData); - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) - - void Animate(); - sofa::core::visual::DrawTool* GetDrawTool(); - sofa::simulation::Node::SPtr GetRootNode() const; - sofa::simulation::Simulation::SPtr GetSOFASimulation() const; - void Reset(); - bool GetAnimationFlag() const; - void SetAnimationFlag(bool animate); - void SetDt(double dt); - void SetRootNode(sofa::simulation::Node::SPtr rootNode); - - bool RequestedRegionIsOutsideOfTheBufferedRegion() override; - void SetRequestedRegion(const itk::DataObject*) override; - void SetRequestedRegionToLargestPossibleRegion() override; - void UpdateOutputInformation() override; - bool VerifyRequestedRegion() override; - - private: - Simulation(); - ~Simulation(); - - sofa::simulation::Simulation::SPtr m_SOFASimulation; - sofa::simulation::Node::SPtr m_RootNode; - sofa::core::visual::DrawToolGL m_DrawTool; - }; -} - -#endif diff --git a/Modules/Simulation/mitkSimulationActivator.cpp b/Modules/Simulation/mitkSimulationActivator.cpp deleted file mode 100644 index 3650b5340a..0000000000 --- a/Modules/Simulation/mitkSimulationActivator.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSimulationIO.h" -#include "mitkSimulationService.h" -#include -#include -#include - -namespace mitk -{ - class SimulationActivator : public us::ModuleActivator - { - public: - SimulationActivator() - { - } - - ~SimulationActivator() - { - } - - void Load(us::ModuleContext* context) override - { - m_SimulationService.reset(new SimulationService); - context->RegisterService(m_SimulationService.get()); - - m_SimulationIO.reset(new SimulationIO); - } - - void Unload(us::ModuleContext*) override - { - m_SimulationIO.reset(nullptr); - m_SimulationService.reset(nullptr); - } - - private: - SimulationActivator(const SimulationActivator&); - SimulationActivator& operator=(const SimulationActivator&); - - std::unique_ptr m_SimulationService; - std::unique_ptr m_SimulationIO; - }; -} - -US_EXPORT_MODULE_ACTIVATOR(mitk::SimulationActivator); diff --git a/Modules/Simulation/mitkSimulationIO.cpp b/Modules/Simulation/mitkSimulationIO.cpp deleted file mode 100644 index a30f474275..0000000000 --- a/Modules/Simulation/mitkSimulationIO.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkGetSimulationService.h" -#include "mitkISimulationService.h" -#include "mitkSimulation.h" -#include "mitkSimulationIO.h" -#include -#include -#include -#include - -#include - -static mitk::CustomMimeType CreateSimulationMimeType() -{ - mitk::CustomMimeType mimeType(mitk::IOMimeTypes::DEFAULT_BASE_NAME() + ".simulation.sofa.scene"); - mimeType.SetCategory("Simulation"); - mimeType.AddExtension("scn"); - mimeType.AddExtension("xml"); - mimeType.SetComment("SOFA Scene File"); - - return mimeType; -} - -mitk::SimulationIO::SimulationIO() - : AbstractFileIO(Simulation::GetStaticNameOfClass(), CreateSimulationMimeType(), "SOFA Simulation Scene") -{ - this->RegisterService(); -} - -std::vector mitk::SimulationIO::Read() -{ - Simulation::Pointer simulation = Simulation::New(); - sofa::simulation::Simulation::SPtr sofaSimulation = simulation->GetSOFASimulation(); - - ISimulationService* simulationService = GetSimulationService(); - Simulation::Pointer lastActiveSimulation = simulationService->GetActiveSimulation(); - - simulationService->SetActiveSimulation(simulation); - - std::ifstream scnFile(this->GetLocalFileName().c_str()); - std::string content = std::string((std::istreambuf_iterator(scnFile)), std::istreambuf_iterator()); - scnFile.close(); - - std::istringstream stream(content); - std::string firstLine; - - if (!std::getline(stream, firstLine).good()) - mitkThrow() << "Could not load '" << this->GetLocalFileName() << "'!"; - - std::string originalPath; - - if (firstLine.size() > 21 && firstLine.substr(0, 21) == "\n"; - - scnFile << originalPath; - } - - scnFile << originalContent; -} - -mitk::IFileIO::ConfidenceLevel mitk::SimulationIO::GetWriterConfidenceLevel() const -{ - if (AbstractFileIO::GetWriterConfidenceLevel() == Unsupported) - return Unsupported; - - return dynamic_cast(this->GetInput()) == nullptr - ? Unsupported - : Supported; -} - -mitk::SimulationIO* mitk::SimulationIO::IOClone() const -{ - return new SimulationIO(*this); -} diff --git a/Modules/Simulation/mitkSimulationIO.h b/Modules/Simulation/mitkSimulationIO.h deleted file mode 100644 index 0224f0ae70..0000000000 --- a/Modules/Simulation/mitkSimulationIO.h +++ /dev/null @@ -1,42 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSimulationIO_h -#define mitkSimulationIO_h - -#include -#include - -namespace mitk -{ - class MITKSIMULATION_EXPORT SimulationIO : public AbstractFileIO - { - public: - SimulationIO(); - - using AbstractFileReader::Read; - std::vector Read() override; - ConfidenceLevel GetReaderConfidenceLevel() const override; - - void Write() override; - ConfidenceLevel GetWriterConfidenceLevel() const override; - - private: - SimulationIO* IOClone() const override; - }; -} - -#endif diff --git a/Modules/Simulation/mitkSimulationInteractor.cpp b/Modules/Simulation/mitkSimulationInteractor.cpp deleted file mode 100644 index 398631c6c1..0000000000 --- a/Modules/Simulation/mitkSimulationInteractor.cpp +++ /dev/null @@ -1,522 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "mitkSimulation.h" -#include "mitkSimulationInteractor.h" - -using sofa::component::collision::AttachBodyPerformer; -using sofa::component::collision::BaseRayContact; -using sofa::component::collision::BodyPicked; -using sofa::component::collision::ComponentMouseInteraction; -using sofa::component::collision::FixParticlePerformerConfiguration; -using sofa::component::collision::InteractionPerformer; -using sofa::component::collision::Ray; -using sofa::component::collision::RayModel; -using sofa::component::container::MechanicalObject; -using sofa::core::behavior::BaseMechanicalState; -using sofa::core::collision::DetectionOutput; -using sofa::core::collision::Pipeline; -using sofa::core::objectmodel::BaseContext; -using sofa::core::CollisionElementIterator; -using sofa::core::ExecParams; -using sofa::core::MechanicalParams; -using sofa::core::VecCoordId; -using sofa::defaulttype::dot; -using sofa::defaulttype::Vec3d; -using sofa::defaulttype::Vec3Types; -using sofa::helper::vector; -using sofa::simulation::CollisionVisitor; -using sofa::simulation::DeleteVisitor; -using sofa::simulation::MechanicalPickParticlesVisitor; -using sofa::simulation::MechanicalPropagatePositionVisitor; -using sofa::simulation::Node; - -namespace mitk -{ - class SimulationInteractor::Impl - { - public: - Impl(); - ~Impl(); - - void Initialize(Node::SPtr rootNode); - void Uninitialize(); - void AttachMouseNode(); - void DetachMouseNode(); - bool IsInteractionPerformerNotNull() const; - void UpdatePickRay(InteractionPositionEvent* event); - void FindCollision(); - void AttachCompatibleInteraction(); - void DetachInteraction(bool setNull); - void StartInteraction(const std::string& type); - void ExecuteInteraction(); - void StopInteraction(); - - private: - Impl(const Impl&); - Impl& operator=(const Impl&); - - BodyPicked FindCollisionUsingPipeline(); - BodyPicked FindCollisionUsingBruteForce(); - void ConfigureInteractionPerformer(); - - Node::SPtr m_RootNode; - Node::SPtr m_MouseNode; - MechanicalObject::SPtr m_PickRayContainer; - RayModel::SPtr m_PickRayModel; - std::vector m_InteractionComponents; - ComponentMouseInteraction* m_Interaction; - std::unique_ptr m_InteractionPerformer; - bool m_IsMouseNodeAttached; - bool m_UseCollisionPipeline; - BodyPicked m_LastBodyPicked; - }; -} - -mitk::SimulationInteractor::Impl::Impl() - : m_Interaction(nullptr), - m_IsMouseNodeAttached(false), - m_UseCollisionPipeline(true) -{ -} - -mitk::SimulationInteractor::Impl::~Impl() -{ - this->Uninitialize(); -} - -void mitk::SimulationInteractor::Impl::Initialize(const Node::SPtr rootNode) -{ - this->Uninitialize(); - - m_RootNode = rootNode; - - m_PickRayContainer = sofa::core::objectmodel::New >(); - m_PickRayContainer->setName("MousePosition"); - m_PickRayContainer->resize(1); - - m_PickRayModel = sofa::core::objectmodel::New(); - m_PickRayModel->setName("MouseCollisionModel"); - m_PickRayModel->setNbRay(1); - - m_MouseNode = rootNode->createChild("Mouse"); - m_MouseNode->addObject(m_PickRayContainer); - m_MouseNode->addObject(m_PickRayModel); - - m_MouseNode->init(ExecParams::defaultInstance()); - m_PickRayContainer->init(); - m_PickRayModel->init(); - - typedef ComponentMouseInteraction::ComponentMouseInteractionFactory Factory; - const Factory* factory = Factory::getInstance(); - - for (Factory::const_iterator it = factory->begin(); it != factory->end(); ++it) - m_InteractionComponents.push_back(it->second->createInstance(nullptr)); - - m_MouseNode->detachFromGraph(); - - Pipeline* collisionPipeline; - rootNode->getContext()->get(collisionPipeline, BaseContext::SearchRoot); - - m_UseCollisionPipeline = collisionPipeline != nullptr; -} - -void mitk::SimulationInteractor::Impl::Uninitialize() -{ - this->DetachMouseNode(); - - if (!m_InteractionComponents.empty()) - { - for (std::vector::iterator it = m_InteractionComponents.begin(); it != m_InteractionComponents.end(); ++it) - delete *it; - - m_InteractionComponents.clear(); - m_Interaction = nullptr; - } - - if (m_MouseNode) - { - m_MouseNode->execute(ExecParams::defaultInstance()); - - m_PickRayModel.reset(); - m_PickRayContainer.reset(); - m_MouseNode.reset(); - m_RootNode.reset(); - } -} - -void mitk::SimulationInteractor::Impl::AttachMouseNode() -{ - if (!m_IsMouseNodeAttached) - { - m_RootNode->addChild(m_MouseNode); - m_IsMouseNodeAttached = true; - } -} - -void mitk::SimulationInteractor::Impl::DetachMouseNode() -{ - if (m_IsMouseNodeAttached) - { - this->DetachInteraction(false); - m_MouseNode->detachFromGraph(); - m_IsMouseNodeAttached = false; - } -} - -bool mitk::SimulationInteractor::Impl::IsInteractionPerformerNotNull() const -{ - return m_InteractionPerformer.get() != nullptr; -} - -void mitk::SimulationInteractor::Impl::UpdatePickRay(InteractionPositionEvent* event) -{ - if (!m_IsMouseNodeAttached) - return; - - vtkCamera* camera = event->GetSender()->GetVtkRenderer()->GetActiveCamera(); - - Vec3d cameraOrigin(camera->GetPosition()); - Vec3d pickedPosition(event->GetPositionInWorld().GetDataPointer()); - Vec3d pickRayDirection(pickedPosition - cameraOrigin); - Vec3d focalPoint(camera->GetFocalPoint()); - - Vec3d cameraDirection(focalPoint - cameraOrigin); - cameraDirection.normalize(); - - std::pair clippingRange; - camera->GetClippingRange(clippingRange.first, clippingRange.second); - - double dotProduct = dot(cameraDirection, pickRayDirection); - double norm = pickRayDirection.norm(); - - clippingRange.first = clippingRange.first / dotProduct * norm; - clippingRange.second = clippingRange.second / dotProduct * norm; - - pickRayDirection.normalize(); - - Ray pickRay = m_PickRayModel->getRay(0); - pickRay.setOrigin(cameraOrigin + pickRayDirection * clippingRange.first); - pickRay.setDirection(pickRayDirection); - pickRay.setL(clippingRange.second - clippingRange.first); - - MechanicalPropagatePositionVisitor(MechanicalParams::defaultInstance(), 0, VecCoordId::position(), true) - .execute(m_PickRayModel->getContext()); - - MechanicalPropagatePositionVisitor(MechanicalParams::defaultInstance(), 0, VecCoordId::freePosition(), true) - .execute(m_PickRayModel->getContext()); -} - -void mitk::SimulationInteractor::Impl::FindCollision() -{ - CollisionVisitor(ExecParams::defaultInstance()).execute(m_RootNode->getContext()); - - if (m_UseCollisionPipeline) - { - m_LastBodyPicked = this->FindCollisionUsingPipeline(); - - if (m_LastBodyPicked.body != nullptr) - return; - } - - m_LastBodyPicked = this->FindCollisionUsingBruteForce(); -} - -BodyPicked mitk::SimulationInteractor::Impl::FindCollisionUsingPipeline() -{ - BodyPicked bodyPicked; - - Ray ray = m_PickRayModel->getRay(0); - const Vec3d& origin = ray.origin(); - const Vec3d& direction = ray.direction(); - const double length = ray.l(); - - const std::set& contacts = m_PickRayModel->getContacts(); - - for (std::set::const_iterator contact = contacts.begin(); contact != contacts.end(); ++contact) - { - const vector& detectionOutputs = (*contact)->getDetectionOutputs(); - - for (vector::const_iterator detectionOutput = detectionOutputs.begin(); detectionOutput != detectionOutputs.end(); ++detectionOutput) - { - CollisionElementIterator collisionElement; - int pointIndex; - - if ((*detectionOutput)->elem.first.getCollisionModel() == m_PickRayModel) - { - collisionElement = (*detectionOutput)->elem.second; - pointIndex = 1; - } - else if ((*detectionOutput)->elem.second.getCollisionModel() == m_PickRayModel) - { - collisionElement = (*detectionOutput)->elem.first; - pointIndex = 0; - } - else - { - continue; - } - - if (!collisionElement.getCollisionModel()->isSimulated()) - continue; - - const double t = ((*detectionOutput)->point[pointIndex] - origin) * direction; - - if (t < 0.0 || t > length) - continue; - - if (bodyPicked.body == nullptr || t < bodyPicked.rayLength) - { - bodyPicked.body = collisionElement.getCollisionModel(); - bodyPicked.indexCollisionElement = collisionElement.getIndex(); - bodyPicked.point = (*detectionOutput)->point[pointIndex]; - bodyPicked.dist = ((*detectionOutput)->point[1] - (*detectionOutput)->point[0]).norm(); - bodyPicked.rayLength = t; - } - } - } - - return bodyPicked; -} - -BodyPicked mitk::SimulationInteractor::Impl::FindCollisionUsingBruteForce() -{ - BodyPicked bodyPicked; - - Ray ray = m_PickRayModel->getRay(0); - const Vec3d& origin = ray.origin(); - const Vec3d& direction = ray.direction(); - const double length = ray.l(); - - MechanicalPickParticlesVisitor pickVisitor(ExecParams::defaultInstance(), origin, direction, length); - pickVisitor.execute(m_RootNode->getContext()); - - if (!pickVisitor.particles.empty()) - { - bodyPicked.mstate = pickVisitor.particles.begin()->second.first; - bodyPicked.indexCollisionElement = pickVisitor.particles.begin()->second.second; - bodyPicked.point[0] = bodyPicked.mstate->getPX(bodyPicked.indexCollisionElement); - bodyPicked.point[1] = bodyPicked.mstate->getPY(bodyPicked.indexCollisionElement); - bodyPicked.point[2] = bodyPicked.mstate->getPZ(bodyPicked.indexCollisionElement); - bodyPicked.dist = 0; - bodyPicked.rayLength = (bodyPicked.point - origin) * direction; - } - - return bodyPicked; -} - -void mitk::SimulationInteractor::Impl::AttachCompatibleInteraction() -{ - BaseContext* context; - - if (m_LastBodyPicked.body == nullptr) - { - context = m_LastBodyPicked.mstate != nullptr - ? m_LastBodyPicked.mstate->getContext() - : nullptr; - } - else - { - context = m_LastBodyPicked.body->getContext(); - } - - if (context != nullptr) - { - if (m_Interaction == nullptr || !m_Interaction->isCompatible(context)) - { - bool foundCompatibleInteractor = false; - - for (std::vector::const_iterator it = m_InteractionComponents.begin(); it != m_InteractionComponents.end(); ++it) - { - if (*it != m_Interaction && (*it)->isCompatible(context)) - { - this->DetachInteraction(false); - m_Interaction = *it; - m_Interaction->attach(m_MouseNode.get()); - - foundCompatibleInteractor = true; - break; - } - } - - if (!foundCompatibleInteractor) - this->DetachInteraction(true); - } - } - else - { - this->DetachInteraction(true); - } - - if (m_Interaction != nullptr) - { - m_Interaction->mouseInteractor->setMouseRayModel(m_PickRayModel.get()); - m_Interaction->mouseInteractor->setBodyPicked(m_LastBodyPicked); - } -} - -void mitk::SimulationInteractor::Impl::DetachInteraction(bool setNull) -{ - if (m_Interaction != nullptr) - { - m_Interaction->detach(); - - if (setNull) - m_Interaction = nullptr; - } -} - -void mitk::SimulationInteractor::Impl::StartInteraction(const std::string& type) -{ - if (m_Interaction == nullptr) - return; - - InteractionPerformer::InteractionPerformerFactory* factory = InteractionPerformer::InteractionPerformerFactory::getInstance(); - m_InteractionPerformer.reset(factory->createObject(type, m_Interaction->mouseInteractor.get())); - - if (m_InteractionPerformer.get() != nullptr) - { - this->ConfigureInteractionPerformer(); - m_Interaction->mouseInteractor->addInteractionPerformer(m_InteractionPerformer.get()); - m_InteractionPerformer->start(); - } -} - -void mitk::SimulationInteractor::Impl::ConfigureInteractionPerformer() -{ - AttachBodyPerformer* attachBodyPerformer = dynamic_cast*>(m_InteractionPerformer.get()); - - if (attachBodyPerformer != nullptr) - { - attachBodyPerformer->setStiffness(1000); - attachBodyPerformer->setArrowSize(0); - attachBodyPerformer->setShowFactorSize(1); - return; - } - - FixParticlePerformerConfiguration* fixParticlePerformer = dynamic_cast(m_InteractionPerformer.get()); - - if (fixParticlePerformer != nullptr) - fixParticlePerformer->setStiffness(10000); -} - -void mitk::SimulationInteractor::Impl::ExecuteInteraction() -{ - if (m_InteractionPerformer.get() == nullptr) - return; - - m_InteractionPerformer->execute(); -} - -void mitk::SimulationInteractor::Impl::StopInteraction() -{ - if (m_InteractionPerformer.get() == nullptr) - return; - - AttachBodyPerformer* attachBodyPerformer = dynamic_cast*>(m_InteractionPerformer.get()); - - if (attachBodyPerformer != nullptr) - attachBodyPerformer->clear(); - - m_Interaction->mouseInteractor->removeInteractionPerformer(m_InteractionPerformer.get()); - m_InteractionPerformer.release(); -} - -mitk::SimulationInteractor::SimulationInteractor() - : m_Impl(new Impl) -{ -} - -mitk::SimulationInteractor::~SimulationInteractor() -{ -} - -void mitk::SimulationInteractor::ConnectActionsAndFunctions() -{ - CONNECT_FUNCTION("startPrimaryInteraction", StartPrimaryInteraction); - CONNECT_FUNCTION("startSecondaryInteraction", StartSecondaryInteraction); - CONNECT_FUNCTION("stopInteraction", StopInteraction); - CONNECT_FUNCTION("executeInteraction", ExecuteInteraction); - CONNECT_CONDITION("isInteractionPerformerNotNull", IsInteractionPerformerNotNull); -} - -void mitk::SimulationInteractor::DataNodeChanged() -{ - this->ResetToStartState(); - - mitk::DataNode* dataNode = this->GetDataNode(); - - if (dataNode != nullptr) - { - Simulation::Pointer simulation = dynamic_cast(dataNode->GetData()); - - if (simulation.IsNotNull()) - { - m_Impl->Initialize(simulation->GetRootNode()); - return; - } - } - - m_Impl->Uninitialize(); -} - -void mitk::SimulationInteractor::StartInteraction(const std::string& type, InteractionPositionEvent* event) -{ - m_Impl->AttachMouseNode(); - m_Impl->UpdatePickRay(event); - m_Impl->FindCollision(); - m_Impl->AttachCompatibleInteraction(); - m_Impl->StartInteraction(type); -} - -void mitk::SimulationInteractor::StartPrimaryInteraction(StateMachineAction*, InteractionEvent* event) -{ - this->StartInteraction("AttachBody", dynamic_cast(event)); -} - -void mitk::SimulationInteractor::StartSecondaryInteraction(StateMachineAction*, InteractionEvent* event) -{ - this->StartInteraction("FixParticle", dynamic_cast(event)); -} - -void mitk::SimulationInteractor::StopInteraction(StateMachineAction*, InteractionEvent*) -{ - m_Impl->StopInteraction(); - m_Impl->DetachMouseNode(); -} - -void mitk::SimulationInteractor::ExecuteInteraction(StateMachineAction*, InteractionEvent* event) -{ - m_Impl->UpdatePickRay(dynamic_cast(event)); - m_Impl->ExecuteInteraction(); -} - -bool mitk::SimulationInteractor::IsInteractionPerformerNotNull(const InteractionEvent*) -{ - return m_Impl->IsInteractionPerformerNotNull(); -} diff --git a/Modules/Simulation/mitkSimulationInteractor.h b/Modules/Simulation/mitkSimulationInteractor.h deleted file mode 100644 index 6ff5ed225d..0000000000 --- a/Modules/Simulation/mitkSimulationInteractor.h +++ /dev/null @@ -1,54 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSimulationInteractor_h -#define mitkSimulationInteractor_h - -#include -#include - -namespace mitk -{ - class InteractionPositionEvent; - - class MITKSIMULATION_EXPORT SimulationInteractor : public DataInteractor - { - public: - mitkClassMacro(SimulationInteractor, DataInteractor); - itkFactorylessNewMacro(Self); - itkCloneMacro(Self); - - protected: - void ConnectActionsAndFunctions() override; - void DataNodeChanged() override; - - private: - SimulationInteractor(); - ~SimulationInteractor(); - - void StartInteraction(const std::string& type, InteractionPositionEvent* event); - void StartPrimaryInteraction(StateMachineAction* action, InteractionEvent* event); - void StartSecondaryInteraction(StateMachineAction* action, InteractionEvent* event); - void ExecuteInteraction(StateMachineAction* action, InteractionEvent* event); - void StopInteraction(StateMachineAction* action, InteractionEvent* event); - bool IsInteractionPerformerNotNull(const InteractionEvent* event); - - class Impl; - std::unique_ptr m_Impl; - }; -} - -#endif diff --git a/Modules/Simulation/mitkSimulationObjectFactory.cpp b/Modules/Simulation/mitkSimulationObjectFactory.cpp deleted file mode 100644 index 2a8dbd2252..0000000000 --- a/Modules/Simulation/mitkSimulationObjectFactory.cpp +++ /dev/null @@ -1,133 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkIndexROI.h" -#include "mitkSimulation.h" -#include "mitkSimulationObjectFactory.h" -#include "mitkSimulationVtkMapper2D.h" -#include "mitkSimulationVtkMapper3D.h" -#include "mitkVtkModel.h" -#include -#include -#include -#include -#include -#include -#include - -static void InitializeSofa() -{ - int argc = 0; - glutInit(&argc, nullptr); - - sofa::component::init(); - sofa::simulation::xml::initXml(); - - sofa::core::visual::VisualParams::defaultInstance()->setSupported(sofa::core::visual::API_OpenGL); -} - -static void RegisterSofaClasses() -{ - using sofa::core::ObjectFactory; - using sofa::core::RegisterObject; - - int IndexROIClass = RegisterObject("").add(); - int VtkModelClass = RegisterObject("").add(); - boost::ignore_unused(IndexROIClass, VtkModelClass); - - ObjectFactory::AddAlias("VisualModel", "VtkModel", true); - ObjectFactory::AddAlias("OglModel", "VtkModel", true); -} - -mitk::SimulationObjectFactory::SimulationObjectFactory() -{ - InitializeSofa(); - RegisterSofaClasses(); -} - -mitk::SimulationObjectFactory::~SimulationObjectFactory() -{ -} - -mitk::Mapper::Pointer mitk::SimulationObjectFactory::CreateMapper(mitk::DataNode* node, MapperSlotId slotId) -{ - Mapper::Pointer mapper; - - if (dynamic_cast(node->GetData()) != nullptr) - { - if (slotId == BaseRenderer::Standard2D) - { - mapper = SimulationVtkMapper2D::New(); - } - else if (slotId == BaseRenderer::Standard3D) - { - mapper = SimulationVtkMapper3D::New(); - } - - if (mapper.IsNotNull()) - mapper->SetDataNode(node); - } - - return mapper; -} - -const char* mitk::SimulationObjectFactory::GetDescription() const -{ - return "Simulation Object Factory"; -} - -const char* mitk::SimulationObjectFactory::GetFileExtensions() -{ - return nullptr; -} - -mitk::CoreObjectFactoryBase::MultimapType mitk::SimulationObjectFactory::GetFileExtensionsMap() -{ - return MultimapType(); -} - -const char* mitk::SimulationObjectFactory::GetSaveFileExtensions() -{ - return nullptr; -} - -mitk::CoreObjectFactoryBase::MultimapType mitk::SimulationObjectFactory::GetSaveFileExtensionsMap() -{ - return MultimapType(); -} - -void mitk::SimulationObjectFactory::SetDefaultProperties(mitk::DataNode* node) -{ - if (node == nullptr) - return; - - if (dynamic_cast(node->GetData()) != nullptr) - { - SimulationVtkMapper2D::SetDefaultProperties(node); - SimulationVtkMapper3D::SetDefaultProperties(node); - } -} - -void mitk::RegisterSimulationObjectFactory() -{ - static bool alreadyRegistered = false; - - if (!alreadyRegistered) - { - CoreObjectFactory::GetInstance()->RegisterExtraFactory(SimulationObjectFactory::New()); - alreadyRegistered = true; - } -} diff --git a/Modules/Simulation/mitkSimulationObjectFactory.h b/Modules/Simulation/mitkSimulationObjectFactory.h deleted file mode 100644 index 62efd548dd..0000000000 --- a/Modules/Simulation/mitkSimulationObjectFactory.h +++ /dev/null @@ -1,47 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSimulationObjectFactory_h -#define mitkSimulationObjectFactory_h - -#include -#include - -namespace mitk -{ - class MITKSIMULATION_EXPORT SimulationObjectFactory : public CoreObjectFactoryBase - { - public: - mitkClassMacro(SimulationObjectFactory, CoreObjectFactoryBase); - itkFactorylessNewMacro(Self); - - Mapper::Pointer CreateMapper(DataNode* node, MapperSlotId slotId) override; - const char* GetDescription() const override; - const char* GetFileExtensions() override; - MultimapType GetFileExtensionsMap() override; - const char* GetSaveFileExtensions() override; - MultimapType GetSaveFileExtensionsMap() override; - void SetDefaultProperties(DataNode* node) override; - - private: - SimulationObjectFactory(); - ~SimulationObjectFactory(); - }; - - MITKSIMULATION_EXPORT void RegisterSimulationObjectFactory(); -} - -#endif diff --git a/Modules/Simulation/mitkSimulationSerializer.cpp b/Modules/Simulation/mitkSimulationSerializer.cpp deleted file mode 100644 index ee94b6efd7..0000000000 --- a/Modules/Simulation/mitkSimulationSerializer.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSimulation.h" -#include "mitkSimulationSerializer.h" -#include - -MITK_REGISTER_SERIALIZER(SimulationSerializer) - -mitk::SimulationSerializer::SimulationSerializer() -{ -} - -mitk::SimulationSerializer::~SimulationSerializer() -{ -} - -std::string mitk::SimulationSerializer::Serialize() -{ - const Simulation* simulation = dynamic_cast(m_Data.GetPointer()); - - if (simulation == nullptr) - { - MITK_ERROR << " Invalid simulation object cannot be serialized!"; - return ""; - } - - std::string filename(this->GetUniqueFilenameInWorkingDirectory()); - filename += "_" + m_FilenameHint + ".scn"; - - std::string fullPath = m_WorkingDirectory; - fullPath += "/" + filename; - - try - { - IOUtil::Save(const_cast(simulation), fullPath); - } - catch (const std::exception& e) - { - MITK_ERROR << " Error serializing simulation object to " << fullPath << ": " << e.what(); - return ""; - } - - return filename; -} diff --git a/Modules/Simulation/mitkSimulationSerializer.h b/Modules/Simulation/mitkSimulationSerializer.h deleted file mode 100644 index 66932b9de8..0000000000 --- a/Modules/Simulation/mitkSimulationSerializer.h +++ /dev/null @@ -1,40 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSimulationSerializer_h -#define mitkSimulationSerializer_h - -#include -#include - -namespace mitk -{ - class MITKSIMULATION_EXPORT SimulationSerializer : public BaseDataSerializer - { - public: - mitkClassMacro(SimulationSerializer, BaseDataSerializer); - itkFactorylessNewMacro(Self); - itkCloneMacro(Self); - - std::string Serialize() override; - - protected: - SimulationSerializer(); - ~SimulationSerializer(); - }; -} - -#endif diff --git a/Modules/Simulation/mitkSimulationService.cpp b/Modules/Simulation/mitkSimulationService.cpp deleted file mode 100644 index d7e1a35a14..0000000000 --- a/Modules/Simulation/mitkSimulationService.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSimulationService.h" -#include - -static void SwitchSimuluationContext(mitk::Simulation::Pointer activeSimulation) -{ - if (activeSimulation.IsNull()) - { - sofa::simulation::setSimulation(nullptr); - sofa::core::visual::VisualParams::defaultInstance()->drawTool() = nullptr; - } - else - { - sofa::simulation::Simulation::SPtr sofaSimulation = activeSimulation->GetSOFASimulation(); - - if (sofaSimulation != sofa::simulation::getSimulation()) - { - sofa::simulation::setSimulation(sofaSimulation.get()); - sofa::core::visual::VisualParams::defaultInstance()->drawTool() = activeSimulation->GetDrawTool(); - } - } -} - -mitk::SimulationService::SimulationService() - : m_Scheduler(SchedulingAlgorithm::WeightedRoundRobin) -{ -} - -mitk::SimulationService::~SimulationService() -{ -} - -mitk::Simulation::Pointer mitk::SimulationService::GetActiveSimulation() const -{ - return m_ActiveSimulation; -} - -void mitk::SimulationService::SetActiveSimulation(Simulation::Pointer activeSimulation) -{ - SwitchSimuluationContext(activeSimulation); - m_ActiveSimulation = activeSimulation; -} - -mitk::Scheduler* mitk::SimulationService::GetScheduler() -{ - return &m_Scheduler; -} diff --git a/Modules/Simulation/mitkSimulationService.h b/Modules/Simulation/mitkSimulationService.h deleted file mode 100644 index a4ebd3dcda..0000000000 --- a/Modules/Simulation/mitkSimulationService.h +++ /dev/null @@ -1,41 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSimulationService_h -#define mitkSimulationService_h - -#include -#include - -namespace mitk -{ - class SimulationService : public ISimulationService - { - public: - SimulationService(); - ~SimulationService(); - - Simulation::Pointer GetActiveSimulation() const override; - void SetActiveSimulation(Simulation::Pointer activeSimulation) override; - Scheduler* GetScheduler() override; - - private: - Simulation::Pointer m_ActiveSimulation; - Scheduler m_Scheduler; - }; -} - -#endif diff --git a/Modules/Simulation/mitkSimulationVtkMapper2D.cpp b/Modules/Simulation/mitkSimulationVtkMapper2D.cpp deleted file mode 100644 index ce8629dbb3..0000000000 --- a/Modules/Simulation/mitkSimulationVtkMapper2D.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSimulation.h" -#include "mitkSimulationVtkMapper2D.h" -#include "mitkVtkSimulationPolyDataMapper2D.h" - -mitk::SimulationVtkMapper2D::LocalStorage::LocalStorage() - : m_Actor(vtkSmartPointer::New()) -{ -} - -mitk::SimulationVtkMapper2D::LocalStorage::~LocalStorage() -{ -} - -void mitk::SimulationVtkMapper2D::SetDefaultProperties(DataNode* node, BaseRenderer* renderer, bool overwrite) -{ - if (node != nullptr) - { - node->AddProperty("Simulation.Visual.2D Rendering", BoolProperty::New(false), renderer, overwrite); - Superclass::SetDefaultProperties(node, renderer, overwrite); - } -} - -mitk::SimulationVtkMapper2D::SimulationVtkMapper2D() -{ -} - -mitk::SimulationVtkMapper2D::~SimulationVtkMapper2D() -{ -} - -void mitk::SimulationVtkMapper2D::ApplyColorAndOpacityProperties(BaseRenderer*, vtkActor*) -{ -} - -void mitk::SimulationVtkMapper2D::GenerateDataForRenderer(BaseRenderer* renderer) -{ - DataNode* dataNode = this->GetDataNode(); - - if (dataNode == nullptr) - return; - - Simulation* simulation = dynamic_cast(dataNode->GetData()); - - if (simulation == nullptr) - return; - - LocalStorage* localStorage = m_LocalStorageHandler.GetLocalStorage(renderer); - - bool enabled = false; - dataNode->GetBoolProperty("Simulation.Visual.2D Rendering", enabled, renderer); - - if (!enabled) - { - localStorage->m_Actor->SetMapper(nullptr); - return; - } - - if (localStorage->m_Mapper == nullptr) - { - localStorage->m_Mapper = vtkSmartPointer::New(); - localStorage->m_Mapper->SetSimulation(simulation); - } - - if (localStorage->m_Actor->GetMapper() == nullptr) - localStorage->m_Actor->SetMapper(localStorage->m_Mapper); -} - -vtkProp* mitk::SimulationVtkMapper2D::GetVtkProp(BaseRenderer* renderer) -{ - return m_LocalStorageHandler.GetLocalStorage(renderer)->m_Actor; -} diff --git a/Modules/Simulation/mitkSimulationVtkMapper2D.h b/Modules/Simulation/mitkSimulationVtkMapper2D.h deleted file mode 100644 index 1a58634913..0000000000 --- a/Modules/Simulation/mitkSimulationVtkMapper2D.h +++ /dev/null @@ -1,68 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSimulationVtkMapper2D_h -#define mitkSimulationVtkMapper2D_h - -#include -#include -#include - -namespace mitk -{ - class vtkSimulationPolyDataMapper2D; - - class MITKSIMULATION_EXPORT SimulationVtkMapper2D : public VtkMapper - { - class LocalStorage : public Mapper::BaseLocalStorage - { - public: - LocalStorage(); - ~LocalStorage(); - - vtkSmartPointer m_Mapper; - vtkSmartPointer m_Actor; - - private: - LocalStorage(const LocalStorage&); - LocalStorage& operator=(const LocalStorage&); - }; - - public: - static void SetDefaultProperties(DataNode* node, BaseRenderer* renderer = nullptr, bool overwrite = false); - - mitkClassMacro(SimulationVtkMapper2D, VtkMapper); - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) - - void ApplyColorAndOpacityProperties(BaseRenderer*, vtkActor*) override; - vtkProp* GetVtkProp(BaseRenderer* renderer) override; - - protected: - void GenerateDataForRenderer(BaseRenderer* renderer) override; - - private: - SimulationVtkMapper2D(); - ~SimulationVtkMapper2D(); - - SimulationVtkMapper2D(const Self&); - Self& operator=(const Self&); - - LocalStorageHandler m_LocalStorageHandler; - }; -} - -#endif diff --git a/Modules/Simulation/mitkSimulationVtkMapper3D.cpp b/Modules/Simulation/mitkSimulationVtkMapper3D.cpp deleted file mode 100644 index 4b56fff387..0000000000 --- a/Modules/Simulation/mitkSimulationVtkMapper3D.cpp +++ /dev/null @@ -1,164 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSetVtkRendererVisitor.h" -#include "mitkSimulation.h" -#include "mitkSimulationVtkMapper3D.h" -#include "mitkVtkSimulationPolyDataMapper3D.h" -#include -#include - -mitk::SimulationVtkMapper3D::LocalStorage::LocalStorage() - : m_Actor(vtkSmartPointer::New()) -{ -} - -mitk::SimulationVtkMapper3D::LocalStorage::~LocalStorage() -{ -} - -void mitk::SimulationVtkMapper3D::SetDefaultProperties(DataNode* node, BaseRenderer* renderer, bool overwrite) -{ - if (node != nullptr) - { - Simulation* simulation = dynamic_cast(node->GetData()); - - if (simulation != nullptr) - { - sofa::simulation::Node::SPtr rootNode = simulation->GetRootNode(); - sofa::component::visualmodel::VisualStyle::SPtr visualStyle; - - rootNode->get(visualStyle); - - if (!visualStyle) - { - visualStyle = sofa::core::objectmodel::New(); - - sofa::core::visual::DisplayFlags* displayFlags = visualStyle->displayFlags.beginEdit(); - displayFlags->setShowVisualModels(); - visualStyle->displayFlags.endEdit(); - - rootNode->addObject(visualStyle); - } - - const sofa::core::visual::DisplayFlags& displayFlags = visualStyle->displayFlags.getValue(); - - node->AddProperty("Simulation.Behavior.Behavior Models", BoolProperty::New(displayFlags.getShowBehaviorModels()), renderer, overwrite); - node->AddProperty("Simulation.Behavior.Force Fields", BoolProperty::New(displayFlags.getShowForceFields()), renderer, overwrite); - node->AddProperty("Simulation.Behavior.Interactions", BoolProperty::New(displayFlags.getShowInteractionForceFields()), renderer, overwrite); - node->AddProperty("Simulation.Collision.Bounding Trees", BoolProperty::New(displayFlags.getShowBoundingCollisionModels()), renderer, overwrite); - node->AddProperty("Simulation.Collision.Collision Models", BoolProperty::New(displayFlags.getShowCollisionModels()), renderer, overwrite); - node->AddProperty("Simulation.Mapping.Mechanical Mappings", BoolProperty::New(displayFlags.getShowMechanicalMappings()), renderer, overwrite); - node->AddProperty("Simulation.Mapping.Visual Mappings", BoolProperty::New(displayFlags.getShowMappings()), renderer, overwrite); - node->AddProperty("Simulation.Options.Normals", BoolProperty::New(displayFlags.getShowNormals()), renderer, overwrite); - node->AddProperty("Simulation.Options.Wire Frame", BoolProperty::New(displayFlags.getShowWireFrame()), renderer, overwrite); - node->AddProperty("Simulation.Visual.Visual Models", BoolProperty::New(displayFlags.getShowVisualModels() != sofa::core::visual::tristate::false_value), renderer, overwrite); - } - - Superclass::SetDefaultProperties(node, renderer, overwrite); - } -} - -mitk::SimulationVtkMapper3D::SimulationVtkMapper3D() -{ -} - -mitk::SimulationVtkMapper3D::~SimulationVtkMapper3D() -{ -} - -void mitk::SimulationVtkMapper3D::ApplyColorAndOpacityProperties(BaseRenderer*, vtkActor*) -{ -} - -void mitk::SimulationVtkMapper3D::ApplySimulationProperties(BaseRenderer* renderer) -{ - DataNode* node = this->GetDataNode(); - - bool showBehaviorModels; - bool showForceFields; - bool showInteractionForceFields; - bool showBoundingCollisionModels; - bool showCollisionModels; - bool showMechanicalMappings; - bool showMappings; - bool showNormals; - bool showWireFrame; - bool showVisualModels; - - node->GetBoolProperty("Simulation.Behavior.Behavior Models", showBehaviorModels, renderer); - node->GetBoolProperty("Simulation.Behavior.Force Fields", showForceFields, renderer); - node->GetBoolProperty("Simulation.Behavior.Interactions", showInteractionForceFields, renderer); - node->GetBoolProperty("Simulation.Collision.Bounding Trees", showBoundingCollisionModels, renderer); - node->GetBoolProperty("Simulation.Collision.Collision Models", showCollisionModels, renderer); - node->GetBoolProperty("Simulation.Mapping.Mechanical Mappings", showMechanicalMappings, renderer); - node->GetBoolProperty("Simulation.Mapping.Visual Mappings", showMappings, renderer); - node->GetBoolProperty("Simulation.Options.Normals", showNormals, renderer); - node->GetBoolProperty("Simulation.Options.Wire Frame", showWireFrame, renderer); - node->GetBoolProperty("Simulation.Visual.Visual Models", showVisualModels, renderer); - - Simulation* simulation = static_cast(node->GetData()); - sofa::component::visualmodel::VisualStyle::SPtr visualStyle; - simulation->GetRootNode()->get(visualStyle); - - sofa::core::visual::DisplayFlags* displayFlags = visualStyle->displayFlags.beginEdit(); - - displayFlags->setShowBehaviorModels(showBehaviorModels); - displayFlags->setShowForceFields(showForceFields); - displayFlags->setShowInteractionForceFields(showInteractionForceFields); - displayFlags->setShowBoundingCollisionModels(showBoundingCollisionModels); - displayFlags->setShowCollisionModels(showCollisionModels); - displayFlags->setShowMechanicalMappings(showMechanicalMappings); - displayFlags->setShowMappings(showMappings); - displayFlags->setShowNormals(showNormals); - displayFlags->setShowWireFrame(showWireFrame); - displayFlags->setShowVisualModels(showVisualModels); - - visualStyle->displayFlags.endEdit(); -} - -void mitk::SimulationVtkMapper3D::GenerateDataForRenderer(BaseRenderer* renderer) -{ - DataNode* dataNode = this->GetDataNode(); - - if (dataNode == nullptr) - return; - - Simulation* simulation = dynamic_cast(dataNode->GetData()); - - if (simulation == nullptr) - return; - - LocalStorage* localStorage = m_LocalStorageHandler.GetLocalStorage(renderer); - - if (localStorage->m_Mapper == nullptr) - { - localStorage->m_Mapper = vtkSmartPointer::New(); - localStorage->m_Mapper->SetSimulation(simulation); - - localStorage->m_Actor->SetMapper(localStorage->m_Mapper); - - SetVtkRendererVisitor setVtkRendererVisitor(renderer->GetVtkRenderer()); - simulation->GetRootNode()->executeVisitor(&setVtkRendererVisitor); - } - - this->ApplySimulationProperties(renderer); -} - -vtkProp* mitk::SimulationVtkMapper3D::GetVtkProp(BaseRenderer* renderer) -{ - return m_LocalStorageHandler.GetLocalStorage(renderer)->m_Actor; -} diff --git a/Modules/Simulation/mitkSimulationVtkMapper3D.h b/Modules/Simulation/mitkSimulationVtkMapper3D.h deleted file mode 100644 index 63c336135c..0000000000 --- a/Modules/Simulation/mitkSimulationVtkMapper3D.h +++ /dev/null @@ -1,69 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkSimulationVtkMapper3D_h -#define mitkSimulationVtkMapper3D_h - -#include -#include -#include - -namespace mitk -{ - class vtkSimulationPolyDataMapper3D; - - class MITKSIMULATION_EXPORT SimulationVtkMapper3D : public VtkMapper - { - class LocalStorage : public Mapper::BaseLocalStorage - { - public: - LocalStorage(); - ~LocalStorage(); - - vtkSmartPointer m_Mapper; - vtkSmartPointer m_Actor; - - private: - LocalStorage(const LocalStorage&); - LocalStorage& operator=(const LocalStorage&); - }; - - public: - static void SetDefaultProperties(DataNode* node, BaseRenderer* renderer = nullptr, bool overwrite = false); - - mitkClassMacro(SimulationVtkMapper3D, VtkMapper); - itkFactorylessNewMacro(Self) - itkCloneMacro(Self) - - void ApplyColorAndOpacityProperties(BaseRenderer*, vtkActor*) override; - void ApplySimulationProperties(BaseRenderer* renderer); - vtkProp* GetVtkProp(BaseRenderer* renderer) override; - - protected: - void GenerateDataForRenderer(BaseRenderer* renderer) override; - - private: - SimulationVtkMapper3D(); - ~SimulationVtkMapper3D(); - - SimulationVtkMapper3D(const Self&); - Self& operator=(const Self&); - - LocalStorageHandler m_LocalStorageHandler; - }; -} - -#endif diff --git a/Modules/Simulation/mitkVtkModel.cpp b/Modules/Simulation/mitkVtkModel.cpp deleted file mode 100644 index a7cfee8f64..0000000000 --- a/Modules/Simulation/mitkVtkModel.cpp +++ /dev/null @@ -1,633 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkVtkModel.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// Defined in mitkExportMitkVisitor.cpp -void ApplyMaterial(mitk::DataNode::Pointer dataNode, const sofa::core::loader::Material& material); - -static bool InitGLEW() -{ - static bool isInitialized = false; - - // If no render window is shown, OpenGL is potentially not initialized, e.g., the - // Display tab of the Workbench might be closed while loading a SOFA scene file. - // In this case initialization is deferred (see mitk::VtkModel::internalDraw()). - if (mitk::RenderingManager::GetInstance()->GetAllRegisteredRenderWindows().empty()) - return false; - - if (!isInitialized) - { - GLenum error = glewInit(); - - if (error != GLEW_OK) - { - MITK_ERROR("glewInit") << glewGetErrorString(error); - } - else - { - isInitialized = true; - } - } - - return isInitialized; -} - -mitk::VtkModel::VtkModel() - : m_GlewIsInitialized(InitGLEW()), - m_BuffersWereCreated(false), - m_LastNumberOfVertices(0), - m_LastNumberOfTriangles(0), - m_LastNumberOfQuads(0), - m_VertexBuffer(0), - m_IndexBuffer(0), - m_VtkRenderer(nullptr), - m_Mode(OpenGL) -{ -} - -mitk::VtkModel::~VtkModel() -{ - if (m_Mode == OpenGL && m_BuffersWereCreated) - { - glDeleteBuffers(1, &m_IndexBuffer); - glDeleteBuffers(1, &m_VertexBuffer); - } -} - -void mitk::VtkModel::CreateIndexBuffer() -{ - if (m_Mode == OpenGL) - { - glGenBuffers(1, &m_IndexBuffer); - } - else if (m_Mode == Surface) - { - m_Polys = vtkSmartPointer::New(); - } - - this->InitIndexBuffer(); -} - -void mitk::VtkModel::CreateVertexBuffer() -{ - if (m_Mode == OpenGL) - { - glGenBuffers(1, &m_VertexBuffer); - } - else if (m_Mode == Surface) - { - m_Points = vtkSmartPointer::New(); - m_Normals = vtkSmartPointer::New(); - m_TexCoords = vtkSmartPointer::New(); - } - - this->InitVertexBuffer(); -} - -void mitk::VtkModel::DrawGroup(int group, bool transparent) -{ - if (m_Mode == OpenGL) - { - this->DrawOpenGLGroup(group, transparent); - } - else if (m_Mode == Surface) - { - this->DrawSurfaceGroup(group, transparent); - } -} - -void mitk::VtkModel::DrawOpenGLGroup(int group, bool) -{ - using sofa::core::loader::Material; - using sofa::defaulttype::ResizableExtVector; - using sofa::defaulttype::Vec4f; - - const VecCoord& vertices = this->getVertices(); - const ResizableExtVector& normals = this->getVnormals(); - const ResizableExtVector& triangles = this->getTriangles(); - const ResizableExtVector& quads = this->getQuads(); - - FaceGroup faceGroup; - - if (group == -1) - { - faceGroup.nbt = triangles.size(); - faceGroup.nbq = quads.size(); - } - else - { - faceGroup = groups.getValue()[group]; - } - - Material material = faceGroup.materialId != -1 - ? materials.getValue()[faceGroup.materialId] - : this->material.getValue(); - - if (material.useTexture && material.activated) - { - m_Textures[faceGroup.materialId]->Load(m_VtkRenderer); - - glEnable(GL_TEXTURE_2D); - glTexCoordPointer(2, GL_FLOAT, 0, reinterpret_cast(vertices.size() * sizeof(VecCoord::value_type) + normals.size() * sizeof(Deriv))); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - } - - Vec4f ambient = material.useAmbient ? material.ambient : Vec4f(); - Vec4f diffuse = material.useDiffuse ? material.diffuse : Vec4f(); - Vec4f specular = material.useSpecular ? material.specular : Vec4f(); - Vec4f emissive = material.useEmissive ? material.emissive : Vec4f(); - float shininess = material.useShininess ? std::min(material.shininess, 128.0f) : 45.0f; - - if (shininess == 0.0f) - { - specular.clear(); - shininess = 1.0f; - } - - glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient.ptr()); - glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse.ptr()); - glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular.ptr()); - glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emissive.ptr()); - glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, shininess); - - if (faceGroup.nbt != 0) - glDrawElements(GL_TRIANGLES, faceGroup.nbt * 3, GL_UNSIGNED_INT, reinterpret_cast(faceGroup.tri0 * sizeof(Triangle))); - - if (faceGroup.nbq != 0) - glDrawElements(GL_QUADS, faceGroup.nbq * 4, GL_UNSIGNED_INT, reinterpret_cast(triangles.size() * sizeof(Triangle) + faceGroup.quad0 * sizeof(Quad))); - - if (material.useTexture && material.activated) - { - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisable(GL_TEXTURE_2D); - - m_Textures[faceGroup.materialId]->PostRender(m_VtkRenderer); - } -} - -void mitk::VtkModel::DrawSurfaceGroup(int, bool) -{ - m_PolyData->SetPoints(m_Points); - m_PolyData->SetPolys(m_Polys); - - vtkPointData* pointData = m_PolyData->GetPointData(); - - pointData->SetNormals(m_Normals->GetSize() != 0 - ? m_Normals - : nullptr); - - pointData->SetTCoords(m_TexCoords->GetSize() != 0 - ? m_TexCoords - : nullptr); - - m_PolyData->Modified(); -} - -void mitk::VtkModel::DrawGroups(bool transparent) -{ - using sofa::core::objectmodel::Data; - using sofa::helper::ReadAccessor; - using sofa::helper::vector; - - ReadAccessor > > groups = this->groups; - - if (groups.empty()) - { - this->DrawGroup(-1, transparent); - } - else - { - int numGroups = static_cast(groups.size()); - - for (int i = 0; i < numGroups; ++i) - this->DrawGroup(i, transparent); - } -} - -void mitk::VtkModel::InitIndexBuffer() -{ - using sofa::defaulttype::ResizableExtVector; - - const ResizableExtVector& triangles = this->getTriangles(); - const ResizableExtVector& quads = this->getQuads(); - - if (m_Mode == OpenGL) - { - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexBuffer); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, triangles.size() * sizeof(Triangle) + quads.size() * sizeof(Quad), nullptr, GL_DYNAMIC_DRAW); - } - - this->UpdateIndexBuffer(); -} - -void mitk::VtkModel::InitVertexBuffer() -{ - using sofa::defaulttype::ResizableExtVector; - - const VecCoord& vertices = this->getVertices(); - const ResizableExtVector normals = this->getVnormals(); - const VecTexCoord& texCoords = this->getVtexcoords(); - - if (m_Mode == OpenGL) - { - glBindBuffer(GL_ARRAY_BUFFER, m_VertexBuffer); - glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(VecCoord::value_type) + normals.size() * sizeof(Deriv) + texCoords.size() * sizeof(VecTexCoord::value_type), nullptr, GL_DYNAMIC_DRAW); - } - else if (m_Mode == Surface) - { - m_Points->SetNumberOfPoints(vertices.size()); - - m_Normals->SetNumberOfComponents(3); - m_Normals->SetNumberOfTuples(normals.size()); - - m_TexCoords->SetNumberOfComponents(2); - m_TexCoords->SetNumberOfTuples(texCoords.size()); - } - - this->UpdateVertexBuffer(); -} - -void mitk::VtkModel::internalDraw(const sofa::core::visual::VisualParams* vparams, bool transparent) -{ - using sofa::core::visual::DisplayFlags; - using sofa::defaulttype::ResizableExtVector; - - if (m_Mode == OpenGL && !m_GlewIsInitialized) - { - // Try lazy initialization since initialization potentially failed so far - // due to missing render windows (see InitGLEW()). - m_GlewIsInitialized = InitGLEW(); - - if (m_GlewIsInitialized) - { - this->updateBuffers(); - } - else - { - return; - } - } - - const DisplayFlags& displayFlags = vparams->displayFlags(); - - if (!displayFlags.getShowVisualModels()) - return; - - if (m_BuffersWereCreated == false) - return; - - if (m_Mode == OpenGL) - { - glEnable(GL_LIGHTING); - glColor3f(1.0f, 1.0f, 1.0f); - glPolygonMode(GL_FRONT_AND_BACK, displayFlags.getShowWireFrame() ? GL_LINE : GL_FILL); - - const VecCoord& vertices = this->getVertices(); - - glBindBuffer(GL_ARRAY_BUFFER, m_VertexBuffer); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexBuffer); - - this->ValidateBoundBuffers(); - - glVertexPointer(3, GL_FLOAT, 0, nullptr); - glNormalPointer(GL_FLOAT, 0, reinterpret_cast(vertices.size() * sizeof(VecCoord::value_type))); - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_NORMAL_ARRAY); - } - - this->DrawGroups(transparent); - - if (m_Mode == OpenGL) - { - glDisableClientState(GL_NORMAL_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); - - if (displayFlags.getShowWireFrame()) - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); - - glDisable(GL_LIGHTING); - } - - if (displayFlags.getShowNormals()) - this->DrawNormals(); -} - -void mitk::VtkModel::DrawNormals() -{ - using sofa::defaulttype::ResizableExtVector; - - if (m_Mode == OpenGL) - { - const VecCoord& vertices = this->getVertices(); - const ResizableExtVector& normals = this->getVnormals(); - size_t numVertices = vertices.size(); - Coord normal; - - glBegin(GL_LINES); - - for (size_t i = 0; i < numVertices; ++i) - { - glVertex3fv(vertices[i].ptr()); - normal = vertices[i] + normals[i]; - glVertex3fv(normal.ptr()); - } - - glEnd(); - } -} - -bool mitk::VtkModel::loadTextures() -{ - using sofa::helper::system::DataRepository; - using sofa::helper::vector; - using sofa::core::loader::Material; - - m_Textures.clear(); - - std::vector materialIndices; - - const vector& materials = this->materials.getValue(); - unsigned int numMaterials = materials.size(); - - for (unsigned int i = 0; i < numMaterials; ++i) - { - const Material& material = materials[i]; - - if (material.useTexture && material.activated) - materialIndices.push_back(i); - } - - bool retValue = true; - size_t numTextures = materialIndices.size(); - - for (size_t i = 0; i < numTextures; ++i) - { - std::string filename = materials[materialIndices[i]].textureFilename; - - if (!DataRepository.findFile(filename)) - { - MITK_ERROR("VtkModel") << "File \"" << filename << "\" not found!"; - retValue = false; - continue; - } - - vtkSmartPointer imageReader = vtkSmartPointer::Take(vtkImageReader2Factory::CreateImageReader2(filename.c_str())); - - if (imageReader == nullptr) - { - MITK_ERROR("VtkModel") << "File \"" << filename << "\" has unknown image format!"; - retValue = false; - continue; - } - - imageReader->SetFileName(filename.c_str()); - imageReader->UpdateWholeExtent(); - - vtkSmartPointer texture = vtkSmartPointer::New(); - texture->SetInputConnection(imageReader->GetOutputPort()); - texture->InterpolateOn(); - - m_Textures.insert(std::make_pair(materialIndices[i], texture)); - } - - return retValue; -} - -mitk::DataNode::Pointer mitk::VtkModel::GetDataNode() const -{ - return m_DataNode; -} - -mitk::VtkModel::Mode mitk::VtkModel::GetMode() const -{ - return m_Mode; -} - -void mitk::VtkModel::SetMode(Mode mode) -{ - if (m_Mode == mode) - return; - - if (mode == OpenGL) - { - m_DataNode = nullptr; - m_Surface = nullptr; - m_PolyData = nullptr; - m_TexCoords = nullptr; - m_Normals = nullptr; - m_Polys = nullptr; - m_Points = nullptr; - } - else if (mode == Surface) - { - if (m_Mode == OpenGL && m_BuffersWereCreated) - { - glDeleteBuffers(1, &m_IndexBuffer); - m_IndexBuffer = 0; - - glDeleteBuffers(1, &m_VertexBuffer); - m_VertexBuffer = 0; - } - - m_PolyData = vtkSmartPointer::New(); - - m_Surface = Surface::New(); - m_Surface->SetVtkPolyData(m_PolyData); - - m_DataNode = DataNode::New(); - m_DataNode->SetName(name.getValue()); - m_DataNode->SetData(m_Surface); - - ApplyMaterial(m_DataNode, this->material.getValue()); - } - - m_Mode = mode; - - m_BuffersWereCreated = false; - this->updateBuffers(); -} - -void mitk::VtkModel::SetVtkRenderer(vtkRenderer* renderer) -{ - m_VtkRenderer = renderer; -} - -void mitk::VtkModel::updateBuffers() -{ - using sofa::defaulttype::ResizableExtVector; - - if (m_Mode == OpenGL && !m_GlewIsInitialized) - return; - - const VecCoord& vertices = this->getVertices(); - const ResizableExtVector& triangles = this->getTriangles(); - const ResizableExtVector& quads = this->getQuads(); - - if (!m_BuffersWereCreated) - { - this->CreateVertexBuffer(); - this->CreateIndexBuffer(); - - m_BuffersWereCreated = true; - } - else - { - if (m_LastNumberOfVertices != vertices.size()) - this->InitVertexBuffer(); - else - this->UpdateVertexBuffer(); - - if (m_LastNumberOfTriangles != triangles.size() || m_LastNumberOfQuads != quads.size()) - this->InitIndexBuffer(); - else - this->UpdateIndexBuffer(); - } - - m_LastNumberOfVertices = vertices.size(); - m_LastNumberOfTriangles = triangles.size(); - m_LastNumberOfQuads = quads.size(); -} - -void mitk::VtkModel::UpdateIndexBuffer() -{ - using sofa::defaulttype::ResizableExtVector; - - const ResizableExtVector& triangles = this->getTriangles(); - const ResizableExtVector& quads = this->getQuads(); - - GLsizeiptr sizeOfTriangleIndices = triangles.size() * sizeof(Triangle); - GLsizeiptr sizeOfQuadIndices = quads.size() * sizeof(Quad); - - if (m_Mode == OpenGL) - { - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IndexBuffer); - glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, sizeOfTriangleIndices, triangles.getData()); - glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, sizeOfTriangleIndices, sizeOfQuadIndices, quads.getData()); - } - else if (m_Mode == Surface) - { - m_Polys->Initialize(); - - if (!triangles.empty()) - { - ResizableExtVector::const_iterator trianglesEnd = triangles.end(); - - for (ResizableExtVector::const_iterator it = triangles.begin(); it != trianglesEnd; ++it) - { - const Triangle& triangle = *it; - - m_Polys->InsertNextCell(3); - m_Polys->InsertCellPoint(triangle[0]); - m_Polys->InsertCellPoint(triangle[1]); - m_Polys->InsertCellPoint(triangle[2]); - } - } - - if (!quads.empty()) - { - ResizableExtVector::const_iterator quadsEnd = quads.end(); - - for (ResizableExtVector::const_iterator it = quads.begin(); it != quadsEnd; ++it) - { - const Quad& quad = *it; - - m_Polys->InsertNextCell(4); - m_Polys->InsertCellPoint(quad[0]); - m_Polys->InsertCellPoint(quad[1]); - m_Polys->InsertCellPoint(quad[2]); - m_Polys->InsertCellPoint(quad[3]); - } - } - } -} - -void mitk::VtkModel::UpdateVertexBuffer() -{ - using sofa::defaulttype::ResizableExtVector; - - const VecCoord& vertices = this->getVertices(); - const ResizableExtVector normals = this->getVnormals(); - const VecTexCoord& texCoords = this->getVtexcoords(); - - if (m_Mode == OpenGL) - { - GLsizeiptr sizeOfVertices = vertices.size() * sizeof(VecCoord::value_type); - GLsizeiptr sizeOfNormals = normals.size() * sizeof(Deriv); - - glBindBuffer(GL_ARRAY_BUFFER, m_VertexBuffer); - glBufferSubData(GL_ARRAY_BUFFER, 0, sizeOfVertices, vertices.getData()); - glBufferSubData(GL_ARRAY_BUFFER, sizeOfVertices, sizeOfNormals, normals.getData()); - - if (!m_Textures.empty()) - { - GLsizeiptr sizeOfTexCoords = texCoords.size() * sizeof(VecTexCoord::value_type); - glBufferSubData(GL_ARRAY_BUFFER, sizeOfVertices + sizeOfNormals, sizeOfTexCoords, texCoords.getData()); - } - } - else if (m_Mode == Surface) - { - size_t numPoints = vertices.size(); - - for (size_t i = 0; i < numPoints; ++i) - m_Points->SetPoint(i, vertices[i].elems); - - if (!normals.empty()) - { - size_t numNormals = normals.size(); - - for (size_t i = 0; i < numNormals; ++i) - m_Normals->SetTuple(i, normals[i].elems); - } - - if (!texCoords.empty()) - { - size_t numTexCoords = texCoords.size(); - - for (size_t i = 0; i < numTexCoords; ++i) - m_TexCoords->SetTuple(i, normals[i].elems); - } - } -} - -void mitk::VtkModel::ValidateBoundBuffers() -{ - if (m_Mode != OpenGL) - return; - - GLint indexBufferSize; - glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &indexBufferSize); - - if (indexBufferSize == 0) - { - glDeleteBuffers(1, &m_IndexBuffer); - this->CreateIndexBuffer(); - - glDeleteBuffers(1, &m_VertexBuffer); - this->CreateVertexBuffer(); - } -} diff --git a/Modules/Simulation/mitkVtkModel.h b/Modules/Simulation/mitkVtkModel.h deleted file mode 100644 index 7939e888d7..0000000000 --- a/Modules/Simulation/mitkVtkModel.h +++ /dev/null @@ -1,99 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkVtkModel_h -#define mitkVtkModel_h - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class vtkOpenGLTexture; -class vtkRenderer; - -namespace mitk -{ - class MITKSIMULATION_EXPORT VtkModel : public sofa::component::visualmodel::VisualModelImpl - { - public: - enum Mode - { - OpenGL, - Surface - }; - - SOFA_CLASS(VtkModel, sofa::component::visualmodel::VisualModelImpl); - - void internalDraw(const sofa::core::visual::VisualParams* vparams, bool transparent) override; - bool loadTextures() override; - void SetVtkRenderer(vtkRenderer* renderer); - void updateBuffers() override; - - DataNode::Pointer GetDataNode() const; - - Mode GetMode() const; - void SetMode(Mode mode); - - private: - VtkModel(); - ~VtkModel(); - - VtkModel(MyType&); - MyType& operator=(const MyType&); - - void CreateIndexBuffer(); - void CreateVertexBuffer(); - void DrawGroup(int group, bool transparent); - void DrawOpenGLGroup(int group, bool transparent); - void DrawSurfaceGroup(int group, bool transparent); - void DrawGroups(bool transparent); - void DrawNormals(); - void InitIndexBuffer(); - void InitVertexBuffer(); - void UpdateIndexBuffer(); - void UpdateVertexBuffer(); - void ValidateBoundBuffers(); - - bool m_GlewIsInitialized; - bool m_BuffersWereCreated; - size_t m_LastNumberOfVertices; - size_t m_LastNumberOfTriangles; - size_t m_LastNumberOfQuads; - GLuint m_VertexBuffer; - GLuint m_IndexBuffer; - std::map > m_Textures; - vtkRenderer* m_VtkRenderer; - Mode m_Mode; - vtkSmartPointer m_Points; - vtkSmartPointer m_Polys; - vtkSmartPointer m_Normals; - vtkSmartPointer m_TexCoords; - vtkSmartPointer m_PolyData; - Surface::Pointer m_Surface; - DataNode::Pointer m_DataNode; - }; -} - -#endif diff --git a/Modules/Simulation/mitkVtkSimulationPolyDataMapper2D.cpp b/Modules/Simulation/mitkVtkSimulationPolyDataMapper2D.cpp deleted file mode 100644 index 18cd79fce4..0000000000 --- a/Modules/Simulation/mitkVtkSimulationPolyDataMapper2D.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkGetSimulationService.h" -#include "mitkISimulationService.h" -#include "mitkPlaneIntersectionVisitor.h" -#include "mitkVtkSimulationPolyDataMapper2D.h" -#include -#include -#include -#include -#include -#include - -namespace mitk -{ - vtkStandardNewMacro(vtkSimulationPolyDataMapper2D); -} - -mitk::vtkSimulationPolyDataMapper2D::vtkSimulationPolyDataMapper2D() - : m_SimulationService(GetSimulationService()) -{ -} - -mitk::vtkSimulationPolyDataMapper2D::~vtkSimulationPolyDataMapper2D() -{ -} - -void mitk::vtkSimulationPolyDataMapper2D::Render(vtkRenderer* renderer, vtkActor*) -{ - typedef PlaneIntersectionVisitor::Edge Edge; - typedef PlaneIntersectionVisitor::Intersection Intersection; - - vtkRenderWindow* renderWindow = renderer->GetRenderWindow(); - - if (renderWindow->CheckAbortStatus() == 1) - return; - - if (renderWindow->SupportsOpenGL() == 0) - return; - - if (m_Simulation.IsNull()) - return; - - if (!renderWindow->IsCurrent()) - renderWindow->MakeCurrent(); - - BaseRenderer* mitkRenderer = BaseRenderer::GetInstance(renderer->GetRenderWindow()); - - if (mitkRenderer == nullptr) - return; - - SliceNavigationController* sliceNavigationController = mitkRenderer->GetSliceNavigationController(); - - if (sliceNavigationController == nullptr) - return; - - const PlaneGeometry* planeGeometry = sliceNavigationController->GetCurrentPlaneGeometry(); - - if (planeGeometry == nullptr) - return; - - renderer->GetRenderWindow()->MakeCurrent(); - - m_SimulationService->SetActiveSimulation(m_Simulation); - - PlaneIntersectionVisitor planeIntersectionVisitor(planeGeometry->GetOrigin(), planeGeometry->GetNormal()); - m_Simulation->GetRootNode()->executeVisitor(&planeIntersectionVisitor); - - glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); - glEnable(GL_COLOR_MATERIAL); - - const std::vector& intersections = planeIntersectionVisitor.GetIntersections(); - std::vector::const_iterator intersectionsEnd = intersections.end(); - - for (std::vector::const_iterator intersectionIt = intersections.begin(); intersectionIt != intersectionsEnd; ++intersectionIt) - { - const std::vector& edges = intersectionIt->edges; - std::vector::const_iterator edgesEnd = edges.end(); - - glColor4fv(intersectionIt->color); - glBegin(GL_LINES); - - for (std::vector::const_iterator edgeIt = edges.begin(); edgeIt != edgesEnd; ++edgeIt) - { - glVertex3dv(edgeIt->v0.GetDataPointer()); - glVertex3dv(edgeIt->v1.GetDataPointer()); - } - - glEnd(); - } - - glDisable(GL_COLOR_MATERIAL); -} - -void mitk::vtkSimulationPolyDataMapper2D::RenderPiece(vtkRenderer*, vtkActor*) -{ -} - -void mitk::vtkSimulationPolyDataMapper2D::SetSimulation(Simulation::Pointer simulation) -{ - m_Simulation = simulation; -} - -double* mitk::vtkSimulationPolyDataMapper2D::GetBounds() -{ - if (m_Simulation.IsNull()) - return Superclass::GetBounds(); - - sofa::simulation::Node::SPtr rootNode = m_Simulation->GetRootNode(); - const sofa::defaulttype::BoundingBox& bbox = rootNode->f_bbox.getValue(); - const sofa::defaulttype::Vector3& min = bbox.minBBox(); - const sofa::defaulttype::Vector3& max = bbox.maxBBox(); - - Bounds[0] = min.x(); - Bounds[1] = max.x(); - Bounds[2] = min.y(); - Bounds[3] = max.y(); - Bounds[4] = min.z(); - Bounds[5] = max.z(); - - return this->Bounds; -} diff --git a/Modules/Simulation/mitkVtkSimulationPolyDataMapper2D.h b/Modules/Simulation/mitkVtkSimulationPolyDataMapper2D.h deleted file mode 100644 index a414706fe5..0000000000 --- a/Modules/Simulation/mitkVtkSimulationPolyDataMapper2D.h +++ /dev/null @@ -1,49 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkVtkSimulationPolyDataMapper2D_h -#define mitkVtkSimulationPolyDataMapper2D_h - -#include -#include -#include - -namespace mitk -{ - class ISimulationService; - - class MITKSIMULATION_EXPORT vtkSimulationPolyDataMapper2D : public vtkPolyDataMapper - { - public: - static vtkSimulationPolyDataMapper2D* New(); - vtkTypeMacro(vtkSimulationPolyDataMapper2D, vtkPolyDataMapper); - - using vtkPolyDataMapper::GetBounds; - double* GetBounds() override; - void Render(vtkRenderer* renderer, vtkActor* actor) override; - void RenderPiece(vtkRenderer*, vtkActor*) override; - void SetSimulation(mitk::Simulation::Pointer simulation); - - private: - vtkSimulationPolyDataMapper2D(); - ~vtkSimulationPolyDataMapper2D(); - - Simulation::Pointer m_Simulation; - ISimulationService* m_SimulationService; - }; -} - -#endif diff --git a/Modules/Simulation/mitkVtkSimulationPolyDataMapper3D.cpp b/Modules/Simulation/mitkVtkSimulationPolyDataMapper3D.cpp deleted file mode 100644 index 6d6e7c528b..0000000000 --- a/Modules/Simulation/mitkVtkSimulationPolyDataMapper3D.cpp +++ /dev/null @@ -1,95 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkGetSimulationService.h" -#include "mitkISimulationService.h" -#include "mitkVtkSimulationPolyDataMapper3D.h" -#include -#include -#include -#include - -namespace mitk -{ - vtkStandardNewMacro(vtkSimulationPolyDataMapper3D); -} - -mitk::vtkSimulationPolyDataMapper3D::vtkSimulationPolyDataMapper3D() - : m_SimulationService(GetSimulationService()) -{ -} - -mitk::vtkSimulationPolyDataMapper3D::~vtkSimulationPolyDataMapper3D() -{ -} - -void mitk::vtkSimulationPolyDataMapper3D::Render(vtkRenderer* renderer, vtkActor*) -{ - vtkRenderWindow* renderWindow = renderer->GetRenderWindow(); - - if (renderWindow->CheckAbortStatus() == 1) - return; - - if (renderWindow->SupportsOpenGL() == 0) - return; - - if (m_Simulation.IsNull()) - return; - - if (!renderWindow->IsCurrent()) - renderWindow->MakeCurrent(); - - m_SimulationService->SetActiveSimulation(m_Simulation); - - sofa::core::visual::VisualParams* vParams = sofa::core::visual::VisualParams::defaultInstance(); - sofa::simulation::Simulation::SPtr sofaSimulation = m_Simulation->GetSOFASimulation(); - sofa::simulation::Node::SPtr rootNode = m_Simulation->GetRootNode(); - - sofaSimulation->updateVisual(rootNode.get()); - sofaSimulation->draw(vParams, rootNode.get()); - - // SOFA potentially disables GL_BLEND but VTK relies on it. - glEnable(GL_BLEND); -} - -void mitk::vtkSimulationPolyDataMapper3D::RenderPiece(vtkRenderer*, vtkActor*) -{ -} - -void mitk::vtkSimulationPolyDataMapper3D::SetSimulation(Simulation::Pointer simulation) -{ - m_Simulation = simulation; -} - -double* mitk::vtkSimulationPolyDataMapper3D::GetBounds() -{ - if (m_Simulation.IsNull()) - return Superclass::GetBounds(); - - sofa::simulation::Node::SPtr rootNode = m_Simulation->GetRootNode(); - const sofa::defaulttype::BoundingBox& bbox = rootNode->f_bbox.getValue(); - const sofa::defaulttype::Vector3& min = bbox.minBBox(); - const sofa::defaulttype::Vector3& max = bbox.maxBBox(); - - Bounds[0] = min.x(); - Bounds[1] = max.x(); - Bounds[2] = min.y(); - Bounds[3] = max.y(); - Bounds[4] = min.z(); - Bounds[5] = max.z(); - - return this->Bounds; -} diff --git a/Modules/Simulation/mitkVtkSimulationPolyDataMapper3D.h b/Modules/Simulation/mitkVtkSimulationPolyDataMapper3D.h deleted file mode 100644 index 57ec13c93f..0000000000 --- a/Modules/Simulation/mitkVtkSimulationPolyDataMapper3D.h +++ /dev/null @@ -1,50 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkVtkSimulationPolyDataMapper3D_h -#define mitkVtkSimulationPolyDataMapper3D_h - -#include -#include -#include - -namespace mitk -{ - class ISimulationService; - - class MITKSIMULATION_EXPORT vtkSimulationPolyDataMapper3D : public vtkPolyDataMapper - { - public: - static vtkSimulationPolyDataMapper3D* New(); - vtkTypeMacro(vtkSimulationPolyDataMapper3D, vtkPolyDataMapper); - - using vtkPolyDataMapper::GetBounds; - double* GetBounds() override; - - void Render(vtkRenderer* renderer, vtkActor* actor) override; - void RenderPiece(vtkRenderer*, vtkActor*) override; - void SetSimulation(mitk::Simulation::Pointer simulation); - - private: - vtkSimulationPolyDataMapper3D(); - ~vtkSimulationPolyDataMapper3D(); - - Simulation::Pointer m_Simulation; - ISimulationService* m_SimulationService; - }; -} - -#endif diff --git a/Modules/Simulation/mitkWeightedRoundRobinSchedulingAlgorithm.cpp b/Modules/Simulation/mitkWeightedRoundRobinSchedulingAlgorithm.cpp deleted file mode 100644 index a8049f71b0..0000000000 --- a/Modules/Simulation/mitkWeightedRoundRobinSchedulingAlgorithm.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkSchedulableProcess.h" -#include "mitkWeightedRoundRobinSchedulingAlgorithm.h" -#include - -static bool CompareElapsedTime(mitk::SchedulableProcess* lhs, mitk::SchedulableProcess* rhs) -{ - return lhs->GetElapsedTime() < rhs->GetElapsedTime(); -} - -mitk::WeightedRoundRobinSchedulingAlgorithm::WeightedRoundRobinSchedulingAlgorithm() -{ -} - -mitk::WeightedRoundRobinSchedulingAlgorithm::~WeightedRoundRobinSchedulingAlgorithm() -{ -} - -mitk::SchedulableProcess* mitk::WeightedRoundRobinSchedulingAlgorithm::GetNextProcess(std::vector& processQueue) -{ - const double threshold = 1.5; - size_t numProcesses = processQueue.size(); - - if (numProcesses == 0) - return nullptr; - - boost::chrono::nanoseconds maxElapsedTime = (*std::max_element(processQueue.begin(), processQueue.end(), CompareElapsedTime))->GetElapsedTime(); - mitk::SchedulableProcess* process = processQueue[0]; - - if (numProcesses > 1) - { - boost::chrono::nanoseconds totalElapsedTime = process->GetTotalElapsedTime(); - boost::chrono::nanoseconds elapsedTime = process->GetElapsedTime(); - - if (totalElapsedTime >= maxElapsedTime || totalElapsedTime + elapsedTime >= maxElapsedTime * threshold) - { - process->ResetTotalElapsedTime(); - - processQueue.erase(processQueue.begin()); - processQueue.push_back(process); - } - } - - return process; -} diff --git a/Modules/Simulation/mitkWeightedRoundRobinSchedulingAlgorithm.h b/Modules/Simulation/mitkWeightedRoundRobinSchedulingAlgorithm.h deleted file mode 100644 index 6b97227ecf..0000000000 --- a/Modules/Simulation/mitkWeightedRoundRobinSchedulingAlgorithm.h +++ /dev/null @@ -1,34 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkWeightedRoundRobinSchedulingAlgorithm_h -#define mitkWeightedRoundRobinSchedulingAlgorithm_h - -#include "mitkSchedulingAlgorithmBase.h" - -namespace mitk -{ - class WeightedRoundRobinSchedulingAlgorithm : public SchedulingAlgorithmBase - { - public: - WeightedRoundRobinSchedulingAlgorithm(); - ~WeightedRoundRobinSchedulingAlgorithm(); - - SchedulableProcess* GetNextProcess(std::vector& processQueue) override; - }; -} - -#endif diff --git a/Modules/VtkShaders/CMakeLists.txt b/Modules/VtkShaders/CMakeLists.txt deleted file mode 100644 index 88ec853c71..0000000000 --- a/Modules/VtkShaders/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -MITK_CREATE_MODULE(VtkShaders - DEPENDS MitkCore - AUTOLOAD_WITH MitkCore -) diff --git a/Modules/VtkShaders/files.cmake b/Modules/VtkShaders/files.cmake deleted file mode 100644 index 1e8df320a0..0000000000 --- a/Modules/VtkShaders/files.cmake +++ /dev/null @@ -1,13 +0,0 @@ -set(CPP_FILES - vtkXMLMaterial.cpp - vtkXMLMaterialParser.cpp - vtkXMLShader.cpp - mitkVtkShaderRepository.cpp - mitkVtkShadersActivator.cpp - mitkVtkShaderProgram.cpp -) - - -set(RESOURCE_FILES - Shaders/mitkShaderLighting.xml -) diff --git a/Modules/VtkShaders/resource/Shaders/mitkShaderLighting.xml b/Modules/VtkShaders/resource/Shaders/mitkShaderLighting.xml deleted file mode 100644 index 5f4e2c54c7..0000000000 --- a/Modules/VtkShaders/resource/Shaders/mitkShaderLighting.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - attribute vec3 scalars; - - uniform vec3 LightPosition; - uniform vec3 SkyColor; - uniform vec3 GroundColor; - - varying vec3 DiffuseColor; - - - void main(void) - { - vec3 ecPosition = vec3(gl_ModelViewMatrix * gl_Vertex); - vec3 tnorm = normalize(gl_NormalMatrix * gl_Normal); - vec3 lightVec = normalize(LightPosition - ecPosition); - float costheta = dot(tnorm, lightVec); - float a = 0.5 + 0.5 * costheta; - - DiffuseColor = mix(GroundColor, SkyColor, a); - - gl_Position = ftransform(); - - } - - - varying vec3 DiffuseColor; - void main(void) - { - gl_FragColor = vec4(DiffuseColor, 1.0); - } - - diff --git a/Modules/VtkShaders/src/mitkVtkShaderProgram.cpp b/Modules/VtkShaders/src/mitkVtkShaderProgram.cpp deleted file mode 100644 index 218ed05f38..0000000000 --- a/Modules/VtkShaders/src/mitkVtkShaderProgram.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkVtkShaderProgram.h" - -#include "vtkShader2.h" - -mitk::VtkShaderProgram::VtkShaderProgram() : m_VtkShaderProgram(nullptr) -{ -} - -mitk::VtkShaderProgram::~VtkShaderProgram() -{ -} - -void mitk::VtkShaderProgram::Activate() -{ - if (m_VtkShaderProgram) - { - m_VtkShaderProgram->Use(); - } -} - -void mitk::VtkShaderProgram::Deactivate() -{ - if (m_VtkShaderProgram) - { - m_VtkShaderProgram->Restore(); - } -} - -void mitk::VtkShaderProgram::SetVtkShaderProgram(vtkSmartPointer p) -{ - m_VtkShaderProgram = p; -} - -vtkSmartPointer mitk::VtkShaderProgram::GetVtkShaderProgram() const -{ - return m_VtkShaderProgram; -} - -itk::TimeStamp &mitk::VtkShaderProgram::GetShaderTimestampUpdate() -{ - return m_ShaderTimestampUpdate; -} diff --git a/Modules/VtkShaders/src/mitkVtkShaderProgram.h b/Modules/VtkShaders/src/mitkVtkShaderProgram.h deleted file mode 100644 index 816c04a619..0000000000 --- a/Modules/VtkShaders/src/mitkVtkShaderProgram.h +++ /dev/null @@ -1,58 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef _MITKVTKSHADERPROGRAM_H_ -#define _MITKVTKSHADERPROGRAM_H_ - -#include - -#include -#include - -namespace mitk -{ - /** - * \brief SHADERTODO - */ - class VtkShaderProgram : public IShaderRepository::ShaderProgram - { - public: - mitkClassMacro(VtkShaderProgram, IShaderRepository::ShaderProgram) itkFactorylessNewMacro(Self) - - /** - * Constructor - */ - VtkShaderProgram(); - - /** - * Destructor - */ - virtual ~VtkShaderProgram(); - - virtual void Activate() override; - virtual void Deactivate() override; - - void SetVtkShaderProgram(vtkSmartPointer p); - vtkSmartPointer GetVtkShaderProgram() const; - itk::TimeStamp &GetShaderTimestampUpdate(); - - private: - vtkSmartPointer m_VtkShaderProgram; - itk::TimeStamp m_ShaderTimestampUpdate; - }; - -} // end of namespace mitk -#endif diff --git a/Modules/VtkShaders/src/mitkVtkShaderRepository.cpp b/Modules/VtkShaders/src/mitkVtkShaderRepository.cpp deleted file mode 100644 index ac71216d6f..0000000000 --- a/Modules/VtkShaders/src/mitkVtkShaderRepository.cpp +++ /dev/null @@ -1,644 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#define SR_INFO MITK_INFO("shader.repository") -#define SR_WARN MITK_WARN("shader.repository") -#define SR_ERROR MITK_ERROR("shader.repository") - -#include "mitkVtkShaderRepository.h" -#include "mitkDataNode.h" -#include "mitkProperties.h" -#include "mitkShaderProperty.h" -#include "mitkVtkShaderProgram.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -int mitk::VtkShaderRepository::shaderId = 0; -const bool mitk::VtkShaderRepository::debug = false; - -mitk::VtkShaderRepository::VtkShaderRepository() -{ - LoadShaders(); -} - -mitk::VtkShaderRepository::~VtkShaderRepository() -{ -} - -mitk::IShaderRepository::ShaderProgram::Pointer mitk::VtkShaderRepository::CreateShaderProgram() -{ - mitk::IShaderRepository::ShaderProgram::Pointer shaderProg = (mitk::VtkShaderProgram::New()).GetPointer(); - return shaderProg; -} - -void mitk::VtkShaderRepository::LoadShaders() -{ - itk::Directory::Pointer dir = itk::Directory::New(); - - std::string dirPath = "./vtk_shader"; - - if (dir->Load(dirPath.c_str())) - { - int n = dir->GetNumberOfFiles(); - for (int r = 0; r < n; r++) - { - const char *filename = dir->GetFile(r); - - std::string extension = itksys::SystemTools::GetFilenameExtension(filename); - - if (extension.compare(".xml") == 0) - { - Shader::Pointer element = Shader::New(); - - element->SetName(itksys::SystemTools::GetFilenameWithoutExtension(filename)); - std::string filePath = dirPath + std::string("/") + element->GetName() + std::string(".xml"); - - SR_INFO(debug) << "found shader '" << element->GetName() << "'"; - - std::ifstream fileStream(filePath.c_str()); - element->LoadXmlShader(fileStream); - - shaders.push_back(element); - } - } - } -} - -mitk::VtkShaderRepository::Shader::Pointer mitk::VtkShaderRepository::GetShaderImpl(const std::string &name) const -{ - std::list::const_iterator i = shaders.begin(); - - while (i != shaders.end()) - { - if ((*i)->GetName() == name) - return (*i); - - i++; - } - - return Shader::Pointer(); -} - -int mitk::VtkShaderRepository::LoadShader(std::istream &stream, const std::string &filename) -{ - Shader::Pointer element = Shader::New(); - element->SetName(filename); - element->SetId(shaderId++); - element->LoadXmlShader(stream); - shaders.push_back(element); - SR_INFO(debug) << "found shader '" << element->GetName() << "'"; - return element->GetId(); -} - -bool mitk::VtkShaderRepository::UnloadShader(int id) -{ - for (std::list::iterator i = shaders.begin(); i != shaders.end(); ++i) - { - if ((*i)->GetId() == id) - { - shaders.erase(i); - return true; - } - } - return false; -} - -mitk::VtkShaderRepository::Shader::Shader() -{ -} - -mitk::VtkShaderRepository::Shader::~Shader() -{ -} - -void mitk::VtkShaderRepository::Shader::SetVertexShaderCode(const std::string &code) -{ - this->m_VertexShaderCode = code; -} - -std::string mitk::VtkShaderRepository::Shader::GetVertexShaderCode() const -{ - return this->m_VertexShaderCode; -} - -void mitk::VtkShaderRepository::Shader::SetFragmentShaderCode(const std::string &code) -{ - this->m_FragmentShaderCode = code; -} - -std::string mitk::VtkShaderRepository::Shader::GetFragmentShaderCode() const -{ - return this->m_FragmentShaderCode; -} - -void mitk::VtkShaderRepository::Shader::SetGeometryShaderCode(const std::string &code) -{ - this->m_GeometryShaderCode = code; -} - -std::string mitk::VtkShaderRepository::Shader::GetGeometryShaderCode() const -{ - return this->m_GeometryShaderCode; -} - -std::list mitk::VtkShaderRepository::Shader::GetUniforms() const -{ - return uniforms; -} - -void mitk::VtkShaderRepository::Shader::LoadXmlShader(std::istream &stream) -{ - std::string content; - content.reserve(2048); - char buffer[2048]; - while (stream.read(buffer, sizeof(buffer))) - { - content.append(buffer, sizeof(buffer)); - } - content.append(buffer, static_cast(stream.gcount())); - - if (content.empty()) - return; - - this->SetMaterialXml(content); - - vtkXMLMaterialParser *parser = vtkXMLMaterialParser::New(); - vtkXMLMaterial *material = vtkXMLMaterial::New(); - parser->SetMaterial(material); - parser->Parse(content.c_str()); - parser->Delete(); - if (material == nullptr) - return; - - // Vertexshader uniforms - { - vtkXMLShader *s = material->GetVertexShader(); - if (s) - { - SetVertexShaderCode(s->GetCode()); - vtkXMLDataElement *x = s->GetRootElement(); - int n = x->GetNumberOfNestedElements(); - for (int r = 0; r < n; r++) - { - vtkXMLDataElement *y = x->GetNestedElement(r); - if (strcmp(y->GetName(), "ApplicationUniform") == 0 || strcmp(y->GetName(), "Uniform") == 0) - { - Uniform::Pointer element = Uniform::New(); - element->LoadFromXML(y); - uniforms.push_back(element); - } - } - } - } - - // Fragmentshader uniforms - { - vtkXMLShader *s = material->GetFragmentShader(); - if (s) - { - SetFragmentShaderCode(s->GetCode()); - vtkXMLDataElement *x = s->GetRootElement(); - int n = x->GetNumberOfNestedElements(); - for (int r = 0; r < n; r++) - { - vtkXMLDataElement *y = x->GetNestedElement(r); - if (strcmp(y->GetName(), "ApplicationUniform") == 0 || strcmp(y->GetName(), "Uniform") == 0) - { - Uniform::Pointer element = Uniform::New(); - element->LoadFromXML(y); - uniforms.push_back(element); - } - } - } - } - - // Geometryshader uniforms - { - vtkXMLShader *s = material->GetGeometryShader(); - if (s) - { - SetGeometryShaderCode(s->GetCode()); - vtkXMLDataElement *x = s->GetRootElement(); - int n = x->GetNumberOfNestedElements(); - for (int r = 0; r < n; r++) - { - vtkXMLDataElement *y = x->GetNestedElement(r); - if (strcmp(y->GetName(), "ApplicationUniform") == 0 || strcmp(y->GetName(), "Uniform") == 0) - { - Uniform::Pointer element = Uniform::New(); - element->LoadFromXML(y); - uniforms.push_back(element); - } - } - } - } - material->Delete(); -} - -mitk::VtkShaderRepository::Shader::Uniform::Uniform() -{ -} - -mitk::VtkShaderRepository::Shader::Uniform::~Uniform() -{ -} - -void mitk::VtkShaderRepository::Shader::Uniform::LoadFromXML(vtkXMLDataElement *y) -{ - // MITK_INFO << "found uniform '" << y->GetAttribute("name") << "' type=" << y->GetAttribute("type");// << " default=" - // << y->GetAttribute("value"); - - name = y->GetAttribute("name"); - - const char *sType = y->GetAttribute("type"); - - if (!strcmp(sType, "float")) - type = glsl_float; - else if (!strcmp(sType, "vec2")) - type = glsl_vec2; - else if (!strcmp(sType, "vec3")) - type = glsl_vec3; - else if (!strcmp(sType, "vec4")) - type = glsl_vec4; - else if (!strcmp(sType, "int")) - type = glsl_int; - else if (!strcmp(sType, "ivec2")) - type = glsl_ivec2; - else if (!strcmp(sType, "ivec3")) - type = glsl_ivec3; - else if (!strcmp(sType, "ivec4")) - type = glsl_ivec4; - else - { - type = glsl_none; - SR_WARN << "unknown type for uniform '" << name << "'"; - } - - defaultFloat[0] = defaultFloat[1] = defaultFloat[2] = defaultFloat[3] = 0; - - const char *sDefault = y->GetAttribute("value"); - - if (sDefault) - { - switch (type) - { - case glsl_float: - sscanf(sDefault, "%f", &defaultFloat[0]); - break; - - case glsl_vec2: - sscanf(sDefault, "%f %f", &defaultFloat[0], &defaultFloat[1]); - break; - - case glsl_vec3: - sscanf(sDefault, "%f %f %f", &defaultFloat[0], &defaultFloat[1], &defaultFloat[2]); - break; - - case glsl_vec4: - sscanf(sDefault, "%f %f %f %f", &defaultFloat[0], &defaultFloat[1], &defaultFloat[2], &defaultFloat[3]); - break; - - case glsl_int: - sscanf(sDefault, "%d", &defaultInt[0]); - break; - - case glsl_ivec2: - sscanf(sDefault, "%d %d", &defaultInt[0], &defaultInt[1]); - break; - - case glsl_ivec3: - sscanf(sDefault, "%d %d %d", &defaultInt[0], &defaultInt[1], &defaultInt[2]); - break; - - case glsl_ivec4: - sscanf(sDefault, "%d %d %d %d", &defaultInt[0], &defaultInt[1], &defaultInt[2], &defaultInt[3]); - break; - - case glsl_none: - break; - } - } -} - -void mitk::VtkShaderRepository::AddDefaultProperties(mitk::DataNode *node, - mitk::BaseRenderer *renderer, - bool overwrite) const -{ - node->AddProperty("shader", mitk::ShaderProperty::New(), renderer, overwrite); - - std::list::const_iterator i = shaders.begin(); - - while (i != shaders.end()) - { - std::list uniforms = (*i)->GetUniforms(); - - std::string shaderName = (*i)->GetName(); - - std::list::const_iterator j = uniforms.begin(); - - while (j != uniforms.end()) - { - std::string propertyName = "shader." + shaderName + "." + (*j)->name; - - switch ((*j)->type) - { - case Shader::Uniform::glsl_float: - node->AddProperty(propertyName.c_str(), mitk::FloatProperty::New((*j)->defaultFloat[0]), renderer, overwrite); - break; - - case Shader::Uniform::glsl_vec2: - node->AddProperty( - (propertyName + ".x").c_str(), mitk::FloatProperty::New((*j)->defaultFloat[0]), renderer, overwrite); - node->AddProperty( - (propertyName + ".y").c_str(), mitk::FloatProperty::New((*j)->defaultFloat[1]), renderer, overwrite); - break; - - case Shader::Uniform::glsl_vec3: - node->AddProperty( - (propertyName + ".x").c_str(), mitk::FloatProperty::New((*j)->defaultFloat[0]), renderer, overwrite); - node->AddProperty( - (propertyName + ".y").c_str(), mitk::FloatProperty::New((*j)->defaultFloat[1]), renderer, overwrite); - node->AddProperty( - (propertyName + ".z").c_str(), mitk::FloatProperty::New((*j)->defaultFloat[2]), renderer, overwrite); - break; - - case Shader::Uniform::glsl_vec4: - node->AddProperty( - (propertyName + ".x").c_str(), mitk::FloatProperty::New((*j)->defaultFloat[0]), renderer, overwrite); - node->AddProperty( - (propertyName + ".y").c_str(), mitk::FloatProperty::New((*j)->defaultFloat[1]), renderer, overwrite); - node->AddProperty( - (propertyName + ".z").c_str(), mitk::FloatProperty::New((*j)->defaultFloat[2]), renderer, overwrite); - node->AddProperty( - (propertyName + ".w").c_str(), mitk::FloatProperty::New((*j)->defaultFloat[3]), renderer, overwrite); - break; - - case Shader::Uniform::glsl_int: - node->AddProperty(propertyName.c_str(), mitk::IntProperty::New((*j)->defaultInt[0]), renderer, overwrite); - break; - - case Shader::Uniform::glsl_ivec2: - node->AddProperty( - (propertyName + ".x").c_str(), mitk::IntProperty::New((*j)->defaultInt[0]), renderer, overwrite); - node->AddProperty( - (propertyName + ".y").c_str(), mitk::IntProperty::New((*j)->defaultInt[1]), renderer, overwrite); - break; - - case Shader::Uniform::glsl_ivec3: - node->AddProperty( - (propertyName + ".x").c_str(), mitk::IntProperty::New((*j)->defaultInt[0]), renderer, overwrite); - node->AddProperty( - (propertyName + ".y").c_str(), mitk::IntProperty::New((*j)->defaultInt[1]), renderer, overwrite); - node->AddProperty( - (propertyName + ".z").c_str(), mitk::IntProperty::New((*j)->defaultInt[2]), renderer, overwrite); - break; - - case Shader::Uniform::glsl_ivec4: - node->AddProperty( - (propertyName + ".x").c_str(), mitk::IntProperty::New((*j)->defaultInt[0]), renderer, overwrite); - node->AddProperty( - (propertyName + ".y").c_str(), mitk::IntProperty::New((*j)->defaultInt[1]), renderer, overwrite); - node->AddProperty( - (propertyName + ".z").c_str(), mitk::IntProperty::New((*j)->defaultInt[2]), renderer, overwrite); - node->AddProperty( - (propertyName + ".w").c_str(), mitk::IntProperty::New((*j)->defaultInt[3]), renderer, overwrite); - break; - - case Shader::Uniform::glsl_none: - break; - } - - j++; - } - - i++; - } -} - -std::list mitk::VtkShaderRepository::GetShaders() const -{ - std::list result; - for (std::list::const_iterator i = shaders.begin(); i != shaders.end(); ++i) - { - result.push_back(i->GetPointer()); - } - return result; -} - -mitk::IShaderRepository::Shader::Pointer mitk::VtkShaderRepository::GetShader(const std::string &name) const -{ - for (std::list::const_iterator i = shaders.begin(); i != shaders.end(); ++i) - { - if ((*i)->GetName() == name) - return i->GetPointer(); - } - return IShaderRepository::Shader::Pointer(); -} - -mitk::IShaderRepository::Shader::Pointer mitk::VtkShaderRepository::GetShader(int id) const -{ - for (std::list::const_iterator i = shaders.begin(); i != shaders.end(); ++i) - { - if ((*i)->GetId() == id) - return i->GetPointer(); - } - return IShaderRepository::Shader::Pointer(); -} - -void mitk::VtkShaderRepository::UpdateShaderProgram(ShaderProgram *shaderProgram, - DataNode *node, - BaseRenderer *renderer) const -{ - VtkShaderProgram *mitkVtkShaderProgram = dynamic_cast(shaderProgram); - mitk::ShaderProperty *sep = dynamic_cast(node->GetProperty("shader", renderer)); - if (!sep) - { - mitkVtkShaderProgram->SetVtkShaderProgram(0); - return; - } - - Shader::Pointer s = GetShaderImpl(sep->GetValueAsString()); - - // Need update pipeline mode - if (sep->GetMTime() > mitkVtkShaderProgram->GetShaderTimestampUpdate().GetMTime()) - { - if (s.IsNull()) - { - mitkVtkShaderProgram->SetVtkShaderProgram(0); - mitkVtkShaderProgram->GetShaderTimestampUpdate().Modified(); - return; - } - - vtkSmartPointer program = vtkSmartPointer::New(); -#if ((VTK_MAJOR_VERSION < 6) || ((VTK_MAJOR_VERSION == 6) && (VTK_MINOR_VERSION == 0))) - program->SetContext(dynamic_cast(renderer->GetRenderWindow())); -#else - program->SetContext(renderer->GetRenderWindow()); -#endif - // The vertext shader - vtkShader2 *shader = vtkShader2::New(); - shader->SetType(VTK_SHADER_TYPE_VERTEX); - shader->SetSourceCode(s->GetVertexShaderCode().c_str()); -#if ((VTK_MAJOR_VERSION < 6) || ((VTK_MAJOR_VERSION == 6) && (VTK_MINOR_VERSION == 0))) - shader->SetContext(dynamic_cast(renderer->GetRenderWindow())); -#else - shader->SetContext(renderer->GetRenderWindow()); -#endif - program->GetShaders()->AddItem(shader); - shader->Delete(); - - // The fragment shader - shader = vtkShader2::New(); - shader->SetType(VTK_SHADER_TYPE_FRAGMENT); - shader->SetSourceCode(s->GetFragmentShaderCode().c_str()); -#if ((VTK_MAJOR_VERSION < 6) || ((VTK_MAJOR_VERSION == 6) && (VTK_MINOR_VERSION == 0))) - shader->SetContext(dynamic_cast(renderer->GetRenderWindow())); -#else - shader->SetContext(renderer->GetRenderWindow()); -#endif - program->GetShaders()->AddItem(shader); - shader->Delete(); - - if (s->GetGeometryShaderCode().size() > 0) - { - // The Geometry shader - shader = vtkShader2::New(); - shader->SetType(VTK_SHADER_TYPE_GEOMETRY); - shader->SetSourceCode(s->GetGeometryShaderCode().c_str()); -#if ((VTK_MAJOR_VERSION < 6) || ((VTK_MAJOR_VERSION == 6) && (VTK_MINOR_VERSION == 0))) - shader->SetContext(dynamic_cast(renderer->GetRenderWindow())); -#else - shader->SetContext(renderer->GetRenderWindow()); -#endif - program->GetShaders()->AddItem(shader); - shader->Delete(); - } - - program->Build(); - - mitkVtkShaderProgram->SetVtkShaderProgram(program); - - mitkVtkShaderProgram->GetShaderTimestampUpdate().Modified(); - } - - if (s.IsNull()) - return; - - // update uniforms - vtkShaderProgram2 *p = mitkVtkShaderProgram->GetVtkShaderProgram(); - - if (!p) - return; - - std::list::const_iterator j = s->uniforms.begin(); - - while (j != s->uniforms.end()) - { - std::string propertyName = "shader." + s->GetName() + "." + (*j)->name; - - // MITK_INFO << "querying property: " << propertyName; - - // mitk::BaseProperty *p = node->GetProperty( propertyName.c_str(), renderer ); - - // if( p && p->GetMTime() > MTime.GetMTime() ) - { - float fval[4]; - int ival[4]; - - // MITK_INFO << "copying property " << propertyName << " ->->- " << (*j)->name << " type=" << (*j)->type ; - - switch ((*j)->type) - { - case Shader::Uniform::glsl_float: - node->GetFloatProperty(propertyName.c_str(), fval[0], renderer); - p->GetUniformVariables()->SetUniformf((*j)->name.c_str(), 1, fval); - break; - - case Shader::Uniform::glsl_vec2: - node->GetFloatProperty((propertyName + ".x").c_str(), fval[0], renderer); - node->GetFloatProperty((propertyName + ".y").c_str(), fval[1], renderer); - p->GetUniformVariables()->SetUniformf((*j)->name.c_str(), 2, fval); - break; - - case Shader::Uniform::glsl_vec3: - node->GetFloatProperty((propertyName + ".x").c_str(), fval[0], renderer); - node->GetFloatProperty((propertyName + ".y").c_str(), fval[1], renderer); - node->GetFloatProperty((propertyName + ".z").c_str(), fval[2], renderer); - // p->SetUniform3f( (*j)->name.c_str(), fval ); - p->GetUniformVariables()->SetUniformf((*j)->name.c_str(), 3, fval); - break; - - case Shader::Uniform::glsl_vec4: - node->GetFloatProperty((propertyName + ".x").c_str(), fval[0], renderer); - node->GetFloatProperty((propertyName + ".y").c_str(), fval[1], renderer); - node->GetFloatProperty((propertyName + ".z").c_str(), fval[2], renderer); - node->GetFloatProperty((propertyName + ".w").c_str(), fval[3], renderer); - p->GetUniformVariables()->SetUniformf((*j)->name.c_str(), 4, fval); - break; - - case Shader::Uniform::glsl_int: - node->GetIntProperty(propertyName.c_str(), ival[0], renderer); - p->GetUniformVariables()->SetUniformi((*j)->name.c_str(), 1, ival); - break; - - case Shader::Uniform::glsl_ivec2: - node->GetIntProperty((propertyName + ".x").c_str(), ival[0], renderer); - node->GetIntProperty((propertyName + ".y").c_str(), ival[1], renderer); - p->GetUniformVariables()->SetUniformi((*j)->name.c_str(), 2, ival); - break; - - case Shader::Uniform::glsl_ivec3: - node->GetIntProperty((propertyName + ".x").c_str(), ival[0], renderer); - node->GetIntProperty((propertyName + ".y").c_str(), ival[1], renderer); - node->GetIntProperty((propertyName + ".z").c_str(), ival[2], renderer); - // p->SetUniform3f( (*j)->name.c_str(), fval ); - p->GetUniformVariables()->SetUniformi((*j)->name.c_str(), 3, ival); - break; - - case Shader::Uniform::glsl_ivec4: - node->GetIntProperty((propertyName + ".x").c_str(), ival[0], renderer); - node->GetIntProperty((propertyName + ".y").c_str(), ival[1], renderer); - node->GetIntProperty((propertyName + ".z").c_str(), ival[2], renderer); - node->GetIntProperty((propertyName + ".w").c_str(), ival[3], renderer); - p->GetUniformVariables()->SetUniformi((*j)->name.c_str(), 4, ival); - break; - - case Shader::Uniform::glsl_none: - break; - } - } - - j++; - } - - return; -} diff --git a/Modules/VtkShaders/src/mitkVtkShaderRepository.h b/Modules/VtkShaders/src/mitkVtkShaderRepository.h deleted file mode 100644 index 01f67664e7..0000000000 --- a/Modules/VtkShaders/src/mitkVtkShaderRepository.h +++ /dev/null @@ -1,164 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef _MITKVTKSHADERREPOSITORY_H_ -#define _MITKVTKSHADERREPOSITORY_H_ - -#include "mitkIShaderRepository.h" -#include -#include - -class vtkXMLDataElement; -class vtkXMLMaterial; -class vtkProperty; - -namespace mitk -{ - /** - * \brief Management class for vtkShader XML descriptions. - * - * Looks for all XML shader files in a given directory and adds default properties - * for each shader object (shader uniforms) to the specified mitk::DataNode. - * - * Additionally, it provides a utility function for applying properties for shaders - * in mappers. - */ - class VtkShaderRepository : public IShaderRepository - { - protected: - class Shader : public IShaderRepository::Shader - { - public: - mitkClassMacro(Shader, IShaderRepository::Shader) itkFactorylessNewMacro(Self) - - class Uniform : public itk::Object - { - public: - mitkClassMacroItkParent(Uniform, itk::Object) itkFactorylessNewMacro(Self) - - enum Type { - glsl_none, - glsl_float, - glsl_vec2, - glsl_vec3, - glsl_vec4, - glsl_int, - glsl_ivec2, - glsl_ivec3, - glsl_ivec4 - }; - - /** - * Constructor - */ - Uniform(); - - /** - * Destructor - */ - ~Uniform(); - - Type type; - std::string name; - - int defaultInt[4]; - float defaultFloat[4]; - - void LoadFromXML(vtkXMLDataElement *e); - }; - - std::list uniforms; - - /** - * Constructor - */ - Shader(); - - /** - * Destructor - */ - ~Shader(); - - void SetVertexShaderCode(const std::string &code); - std::string GetVertexShaderCode() const; - - void SetFragmentShaderCode(const std::string &code); - std::string GetFragmentShaderCode() const; - - void SetGeometryShaderCode(const std::string &code); - std::string GetGeometryShaderCode() const; - - std::list GetUniforms() const; - - private: - friend class VtkShaderRepository; - - std::string m_VertexShaderCode; - std::string m_FragmentShaderCode; - std::string m_GeometryShaderCode; - - void LoadXmlShader(std::istream &stream); - }; - - void LoadShaders(); - - Shader::Pointer GetShaderImpl(const std::string &name) const; - - private: - std::list shaders; - - static int shaderId; - static const bool debug; - - public: - /** - * Constructor - */ - VtkShaderRepository(); - - /** - * Destructor - */ - ~VtkShaderRepository(); - - ShaderProgram::Pointer CreateShaderProgram() override; - - std::list GetShaders() const override; - - IShaderRepository::Shader::Pointer GetShader(const std::string &name) const override; - - IShaderRepository::Shader::Pointer GetShader(int id) const override; - - /** \brief Adds all parsed shader uniforms to property list of the given DataNode; - * used by mappers. - */ - void AddDefaultProperties(mitk::DataNode *node, mitk::BaseRenderer *renderer, bool overwrite) const override; - - /** \brief Applies shader and shader specific variables of the specified DataNode - * to the VTK object by updating the shader variables of its vtkProperty. - */ - - int LoadShader(std::istream &stream, const std::string &name) override; - - bool UnloadShader(int id) override; - - void UpdateShaderProgram(mitk::IShaderRepository::ShaderProgram *shaderProgram, - DataNode *node, - BaseRenderer *renderer) const override; - }; - -} // end of namespace mitk -#endif diff --git a/Modules/VtkShaders/src/mitkVtkShadersActivator.cpp b/Modules/VtkShaders/src/mitkVtkShadersActivator.cpp deleted file mode 100644 index 7d3951823a..0000000000 --- a/Modules/VtkShaders/src/mitkVtkShadersActivator.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace mitk -{ - class VtkShadersActivator : public us::ModuleActivator - { - public: - VtkShadersActivator() {} - ~VtkShadersActivator() {} - void Load(us::ModuleContext *context) override - { - m_VtkShaderRepository.reset(new VtkShaderRepository); - context->RegisterService(m_VtkShaderRepository.get()); - } - - void Unload(us::ModuleContext *) override { m_VtkShaderRepository.reset(nullptr); } - private: - VtkShadersActivator(const VtkShadersActivator &); - VtkShadersActivator &operator=(const VtkShadersActivator &); - - std::unique_ptr m_VtkShaderRepository; - }; -} - -US_EXPORT_MODULE_ACTIVATOR(mitk::VtkShadersActivator) diff --git a/Modules/VtkShaders/src/vtkXMLMaterial.cpp b/Modules/VtkShaders/src/vtkXMLMaterial.cpp deleted file mode 100644 index ab5602a23d..0000000000 --- a/Modules/VtkShaders/src/vtkXMLMaterial.cpp +++ /dev/null @@ -1,300 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkXMLMaterial.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -#include "vtkXMLMaterial.h" - -#include "vtkObjectFactory.h" -#include "vtkSmartPointer.h" -#include "vtkXMLDataElement.h" -#include "vtkXMLMaterialParser.h" -#include "vtkXMLShader.h" - -#include -#include - -class vtkXMLMaterialInternals -{ -public: - typedef std::vector VectorOfElements; - typedef std::vector> VectorOfShaders; - VectorOfElements Properties; - VectorOfShaders VertexShaders; - VectorOfShaders FragmentShaders; - VectorOfShaders GeometryShaders; - VectorOfElements Textures; - void Initialize() - { - this->Properties.clear(); - this->VertexShaders.clear(); - this->FragmentShaders.clear(); - this->GeometryShaders.clear(); - this->Textures.clear(); - } -}; - -vtkStandardNewMacro(vtkXMLMaterial); - -//----------------------------------------------------------------------------- -vtkXMLMaterial::vtkXMLMaterial() -{ - this->RootElement = nullptr; - this->Internals = new vtkXMLMaterialInternals; -} - -//----------------------------------------------------------------------------- -vtkXMLMaterial::~vtkXMLMaterial() -{ - this->SetRootElement(nullptr); - delete this->Internals; -} - -vtkXMLMaterial *vtkXMLMaterial::CreateInstance(const char *name) -{ - if (!name) - { - return nullptr; - } - - vtkXMLMaterialParser *parser = vtkXMLMaterialParser::New(); - vtkXMLMaterial *material = vtkXMLMaterial::New(); - parser->SetMaterial(material); - - // First, look for material library files. - // Then, look for Repository files. - - char *filename = vtkXMLShader::LocateFile(name); - if (filename) - { - parser->SetFileName(filename); - delete[] filename; - parser->Parse(); - parser->Delete(); - return material; - } - - parser->Delete(); - material->Delete(); - return nullptr; -} - -//----------------------------------------------------------------------------- -void vtkXMLMaterial::SetRootElement(vtkXMLDataElement *root) -{ - this->Internals->Initialize(); - - vtkSetObjectBodyMacro(RootElement, vtkXMLDataElement, root); - if (this->RootElement) - { - // Update the internal data structure to - // avoid repeated searches. - int numElems = this->RootElement->GetNumberOfNestedElements(); - for (int i = 0; i < numElems; i++) - { - vtkXMLDataElement *elem = this->RootElement->GetNestedElement(i); - const char *name = elem->GetName(); - if (!name) - { - continue; - } - if (strcmp(name, "Property") == 0) - { - this->Internals->Properties.push_back(elem); - } - else if (strcmp(name, "Shader") == 0) - { - vtkXMLShader *shader = vtkXMLShader::New(); - shader->SetRootElement(elem); - - switch (shader->GetScope()) - { - case vtkXMLShader::SCOPE_VERTEX: - this->Internals->VertexShaders.push_back(shader); - break; - case vtkXMLShader::SCOPE_FRAGMENT: - this->Internals->FragmentShaders.push_back(shader); - break; - case vtkXMLShader::SCOPE_GEOMETRY: - this->Internals->GeometryShaders.push_back(shader); - break; - default: - vtkErrorMacro("Invalid scope for shader: " << shader->GetName()); - } - - shader->Delete(); - } - else if (strcmp(name, "Texture") == 0) - { - this->Internals->Textures.push_back(elem); - } - } - } -} - -//----------------------------------------------------------------------------- -int vtkXMLMaterial::GetNumberOfProperties() -{ - return static_cast(this->Internals->Properties.size()); -} - -//----------------------------------------------------------------------------- -int vtkXMLMaterial::GetNumberOfTextures() -{ - return static_cast(this->Internals->Textures.size()); -} - -//----------------------------------------------------------------------------- -int vtkXMLMaterial::GetNumberOfVertexShaders() -{ - return static_cast(this->Internals->VertexShaders.size()); -} - -//----------------------------------------------------------------------------- -int vtkXMLMaterial::GetNumberOfFragmentShaders() -{ - return static_cast(this->Internals->FragmentShaders.size()); -} - -int vtkXMLMaterial::GetNumberOfGeometryShaders() -{ - return static_cast(this->Internals->GeometryShaders.size()); -} - -//----------------------------------------------------------------------------- -vtkXMLDataElement *vtkXMLMaterial::GetProperty(int id) -{ - if (id < this->GetNumberOfProperties()) - { - return this->Internals->Properties[id]; - } - return nullptr; -} - -//----------------------------------------------------------------------------- -vtkXMLDataElement *vtkXMLMaterial::GetTexture(int index) -{ - if (index < this->GetNumberOfTextures()) - { - return this->Internals->Textures[index]; - } - return nullptr; -} - -//----------------------------------------------------------------------------- -vtkXMLShader *vtkXMLMaterial::GetVertexShader(int id) -{ - if (id < this->GetNumberOfVertexShaders()) - { - return this->Internals->VertexShaders[id].GetPointer(); - } - return nullptr; -} - -//----------------------------------------------------------------------------- -vtkXMLShader *vtkXMLMaterial::GetFragmentShader(int id) -{ - if (id < this->GetNumberOfFragmentShaders()) - { - return this->Internals->FragmentShaders[id].GetPointer(); - } - return nullptr; -} - -vtkXMLShader *vtkXMLMaterial::GetGeometryShader(int id) -{ - if (id < this->GetNumberOfGeometryShaders()) - { - return this->Internals->GeometryShaders[id].GetPointer(); - } - return nullptr; -} - -//---------------------------------------------------------------------------- - -// ---------------------------------------------------------------------------- -// Description: -// Get the style the shaders. -// \post valid_result: result==1 || result==2 -int vtkXMLMaterial::GetShaderStyle() -{ - int result = 1; - int vStyle = 0; - if (this->GetVertexShader()) - { - vStyle = this->GetVertexShader()->GetStyle(); - } - int fStyle = 0; - if (this->GetFragmentShader()) - { - fStyle = this->GetFragmentShader()->GetStyle(); - } - int gStyle = 0; - if (this->GetGeometryShader()) - { - gStyle = this->GetGeometryShader()->GetStyle(); - } - if (vStyle != 0 && fStyle != 0 && !gStyle && vStyle != fStyle) - { - vtkErrorMacro(<< "vertex shader and fragment shader style differ."); - } - else - { - if (vStyle != 0) - { - result = vStyle; - } - else - { - result = fStyle; - } - } - - assert("post: valid_result" && (result == 1 || result == 2)); - return result; -} - -//----------------------------------------------------------------------------- -void vtkXMLMaterial::PrintSelf(ostream &os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "Number of Properties: " << this->GetNumberOfProperties() << endl; - os << indent << "Number of Vertex Shaders: " << this->GetNumberOfVertexShaders() << endl; - os << indent << "Number of Fragment Shaders: " << this->GetNumberOfFragmentShaders() << endl; - os << indent << "RootElement: "; - if (this->RootElement) - { - os << endl; - this->RootElement->PrintSelf(os, indent.GetNextIndent()); - } - else - { - os << "(null)" << endl; - } -} diff --git a/Modules/VtkShaders/src/vtkXMLMaterial.h b/Modules/VtkShaders/src/vtkXMLMaterial.h deleted file mode 100644 index 61c675f58e..0000000000 --- a/Modules/VtkShaders/src/vtkXMLMaterial.h +++ /dev/null @@ -1,122 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkXMLMaterial.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -// .NAME vtkXMLMaterial - encapsulates a VTK Material description. -// .SECTION Description -// vtkXMLMaterial encapsulates VTK Material description. It keeps a pointer -// to vtkXMLDataElement that defines the material and provides -// access to Shaders/Properties defined in it. -// .SECTION Thanks -// Shader support in VTK includes key contributions by Gary Templet at -// Sandia National Labs. - -#ifndef __vtkXMLMaterial_h -#define __vtkXMLMaterial_h - -#include "vtkObject.h" -#include "vtkRenderingCoreModule.h" // For export macro - -class vtkXMLDataElement; -class vtkXMLMaterialInternals; -class vtkXMLShader; - -class vtkXMLMaterial : public vtkObject -{ -public: - static vtkXMLMaterial *New(); - vtkTypeMacro(vtkXMLMaterial, vtkObject); - void PrintSelf(ostream &os, vtkIndent indent) override; - - // Description: - // Create a new instance. It searches for the material - // using the following order: first, check the MaterialLibrary; second, - // treat the name as an absolute path and try to locate it; third, - // search the Material repository. Returns null is it fails to - // locate the material. - static vtkXMLMaterial *CreateInstance(const char *name); - - // Description: - // Get number of elements of type Property. - int GetNumberOfProperties(); - - // Description: - // Get number of elements of type Texture. - int GetNumberOfTextures(); - - // Description: - // Get number of Vertex shaders. - int GetNumberOfVertexShaders(); - - // Description: - // Get number of fragment shaders. - int GetNumberOfFragmentShaders(); - int GetNumberOfGeometryShaders(); - - // Description: - // Get the ith vtkXMLDataElement of type . - vtkXMLDataElement *GetProperty(int id = 0); - - // Description: - // Get the ith vtkXMLDataElement of type . - vtkXMLDataElement *GetTexture(int id = 0); - - // Description: - // Get the ith vtkXMLDataElement of type . - vtkXMLShader *GetVertexShader(int id = 0); - - // Description: - // Get the ith vtkXMLDataElement of type . - vtkXMLShader *GetFragmentShader(int id = 0); - - vtkXMLShader *GetGeometryShader(int id = 0); - - // Description: - // Get/Set the XML root element that describes this material. - vtkGetObjectMacro(RootElement, vtkXMLDataElement); - void SetRootElement(vtkXMLDataElement *); - - // Description: - // Get the style the shaders. - // \post valid_result: result==1 || result==2 - int GetShaderStyle(); - -protected: - vtkXMLMaterial(); - ~vtkXMLMaterial(); - - vtkXMLDataElement *RootElement; - vtkXMLMaterialInternals *Internals; - -private: - vtkXMLMaterial(const vtkXMLMaterial &); // Not implemented. - void operator=(const vtkXMLMaterial &); // Not implemented. -}; - -#endif diff --git a/Modules/VtkShaders/src/vtkXMLMaterialParser.cpp b/Modules/VtkShaders/src/vtkXMLMaterialParser.cpp deleted file mode 100644 index 0a85a9a7f6..0000000000 --- a/Modules/VtkShaders/src/vtkXMLMaterialParser.cpp +++ /dev/null @@ -1,166 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkXMLMaterialParser.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -/* - * Copyright 2003 Sandia Corporation. - * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive - * license for use of this work by or on behalf of the - * U.S. Government. Redistribution and use in source and binary forms, with - * or without modification, are permitted provided that this Notice and any - * statement of authorship are reproduced on all copies. - */ - -#include "vtkXMLMaterialParser.h" - -#include "vtkObjectFactory.h" -#include "vtkSmartPointer.h" -#include "vtkXMLDataElement.h" -#include "vtkXMLMaterial.h" - -#include "vtkXMLUtilities.h" - -#include - -//----------------------------------------------------------------------------- -class vtkXMLMaterialParserInternals -{ -public: - typedef std::vector> VectorOfElements; - VectorOfElements Stack; -}; - -//----------------------------------------------------------------------------- -vtkStandardNewMacro(vtkXMLMaterialParser); -vtkCxxSetObjectMacro(vtkXMLMaterialParser, Material, vtkXMLMaterial); - -//----------------------------------------------------------------------------- -vtkXMLMaterialParser::vtkXMLMaterialParser() -{ - this->Material = vtkXMLMaterial::New(); - this->Material->Register(this); - this->Material->Delete(); - this->Internals = new vtkXMLMaterialParserInternals; -} - -//----------------------------------------------------------------------------- -vtkXMLMaterialParser::~vtkXMLMaterialParser() -{ - delete this->Internals; - this->SetMaterial(nullptr); -} - -//----------------------------------------------------------------------------- -int vtkXMLMaterialParser::Parse(const char *str) -{ - return this->Superclass::Parse(str); -} - -//----------------------------------------------------------------------------- -int vtkXMLMaterialParser::Parse(const char *str, unsigned int length) -{ - return this->Superclass::Parse(str, length); -} - -//----------------------------------------------------------------------------- -int vtkXMLMaterialParser::Parse() -{ - this->Internals->Stack.clear(); - return this->Superclass::Parse(); -} - -//----------------------------------------------------------------------------- -int vtkXMLMaterialParser::InitializeParser() -{ - int ret = this->Superclass::InitializeParser(); - if (ret) - { - this->Internals->Stack.clear(); - } - return ret; -} - -//----------------------------------------------------------------------------- -void vtkXMLMaterialParser::StartElement(const char *name, const char **atts) -{ - vtkXMLDataElement *element = vtkXMLDataElement::New(); - element->SetName(name); - element->SetXMLByteIndex(this->GetXMLByteIndex()); - vtkXMLUtilities::ReadElementFromAttributeArray(element, atts, VTK_ENCODING_NONE); - const char *id = element->GetAttribute("id"); - if (id) - { - element->SetId(id); - } - this->Internals->Stack.push_back(element); - element->Delete(); -} - -//----------------------------------------------------------------------------- -void vtkXMLMaterialParser::EndElement(const char *vtkNotUsed(name)) -{ - vtkXMLDataElement *finished = this->Internals->Stack.back().GetPointer(); - int prev_pos = static_cast(this->Internals->Stack.size()) - 2; - if (prev_pos >= 0) - { - this->Internals->Stack[prev_pos].GetPointer()->AddNestedElement(finished); - } - else - { - this->Material->SetRootElement(finished); - } - - this->Internals->Stack.pop_back(); -} - -//----------------------------------------------------------------------------- -void vtkXMLMaterialParser::CharacterDataHandler(const char *inData, int inLength) -{ - if (this->Internals->Stack.size() > 0) - { - vtkXMLDataElement *elem = this->Internals->Stack.back().GetPointer(); - elem->AddCharacterData(inData, inLength); - } - /* - // this wont happen as the XML parser will flag it as an error. - else - { - vtkErrorMacro("Character data not enclosed in XML tags"); - } - */ -} - -//----------------------------------------------------------------------------- -void vtkXMLMaterialParser::PrintSelf(ostream &os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "Material: "; - this->Material->PrintSelf(os, indent.GetNextIndent()); -} diff --git a/Modules/VtkShaders/src/vtkXMLMaterialParser.h b/Modules/VtkShaders/src/vtkXMLMaterialParser.h deleted file mode 100644 index 893c94c976..0000000000 --- a/Modules/VtkShaders/src/vtkXMLMaterialParser.h +++ /dev/null @@ -1,140 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkXMLMaterialParser.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ - -/* - * Copyright 2004 Sandia Corporation. - * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive - * license for use of this work by or on behalf of the - * U.S. Government. Redistribution and use in source and binary forms, with - * or without modification, are permitted provided that this Notice and any - * statement of authorship are reproduced on all copies. - */ - -// .NAME vtkXMLMaterialParser - Parses VTK Material file -// -// .SECTION Description -// vtkXMLMaterialParser parses a VTK Material file and provides that file's -// description of a number of vertex and fragment shaders along with data -// values specified for data members of vtkProperty. This material is to be -// applied to an actor through it's vtkProperty and augments VTK's concept -// of a vtkProperty to include explicitly include vertex and fragment shaders -// and parameter settings for those shaders. This effectively makes reflectance -// models and other shaders a material property. If no shaders are specified -// VTK should default to standard rendering. -// -// .SECTION Design -// vtkXMLMaterialParser provides access to 3 distinct types of first-level -// vtkXMLDataElements that describe a VTK material. These elements are as -// follows: -// -// vtkProperty - describe values for vtkProperty data members -// -// vtkVertexShader - a vertex shader and enough information to -// install it into the hardware rendering pipeline including values for -// specific shader parameters and structures. -// -// vtkFragmentShader - a fragment shader and enough information to -// install it into the hardware rendering pipeline including values for -// specific shader parameters and structures. -// -// The design of the material file closely follows that of vtk's xml -// descriptions of it's data sets. This allows use of the very handy -// vtkXMLDataElement which provides easy access to an xml element's -// attribute values. Inlined data is currently not handled. -// -// Ideally this class would be a Facade to a DOM parser, but VTK only -// provides access to expat, a SAX parser. Other vtk classes that parse -// xml files are tuned to read vtkDataSets and don't provide the functionality -// to handle generic xml data. As such they are of little use here. -// -// This class may be extended for better data handling or may become a -// Facade to a DOM parser should on become part of the VTK code base. -// .SECTION Thanks -// Shader support in VTK includes key contributions by Gary Templet at -// Sandia National Labs. - -#ifndef __vtkXMLMaterialParser_h -#define __vtkXMLMaterialParser_h - -#include "vtkRenderingCoreModule.h" // For export macro -#include "vtkXMLParser.h" - -class vtkXMLMaterial; -class vtkXMLMaterialParserInternals; - -class vtkXMLMaterialParser : public vtkXMLParser -{ -public: - static vtkXMLMaterialParser *New(); - vtkTypeMacro(vtkXMLMaterialParser, vtkXMLParser); - void PrintSelf(ostream &os, vtkIndent indent) override; - - // Description: - // Set/Get the vtkXMLMaterial representation of the parsed material. - vtkGetObjectMacro(Material, vtkXMLMaterial); - void SetMaterial(vtkXMLMaterial *); - - // Description: - // Overridden to initialize the internal structures before - // the parsing begins. - virtual int Parse() override; - virtual int Parse(const char *inputString) override; - virtual int Parse(const char *inputString, unsigned int length) override; - - // Description: - // Overridden to clean up internal structures before the chunk-parsing - // begins. - virtual int InitializeParser() override; - -protected: - vtkXMLMaterialParser(); - ~vtkXMLMaterialParser(); - - // Description: - // Event for handling the start of an element - virtual void StartElement(const char *name, const char **atts) override; - - // Description: - // Event for handling the end of an element - virtual void EndElement(const char *) override; - - // Description: - // Handle character data, not yet implemented - virtual void CharacterDataHandler(const char *data, int length) override; - - vtkXMLMaterial *Material; - vtkXMLMaterialParserInternals *Internals; - -private: - vtkXMLMaterialParser(const vtkXMLMaterialParser &); // Not implemented - void operator=(const vtkXMLMaterialParser &); // Not implemented -}; -#endif diff --git a/Modules/VtkShaders/src/vtkXMLShader.cpp b/Modules/VtkShaders/src/vtkXMLShader.cpp deleted file mode 100644 index 0955aa6da8..0000000000 --- a/Modules/VtkShaders/src/vtkXMLShader.cpp +++ /dev/null @@ -1,293 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkXMLShader.cxx - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -#include "vtkXMLShader.h" - -#include "vtkObjectFactory.h" -#include "vtkXMLDataElement.h" - -#include -#include - -vtkStandardNewMacro(vtkXMLShader); -vtkCxxSetObjectMacro(vtkXMLShader, SourceLibraryElement, vtkXMLDataElement); -//----------------------------------------------------------------------------- -vtkXMLShader::vtkXMLShader() : Code(nullptr), RootElement(nullptr), SourceLibraryElement(nullptr), Args(nullptr) -{ -} - -//----------------------------------------------------------------------------- -vtkXMLShader::~vtkXMLShader() -{ - if (this->RootElement) - { - this->RootElement->UnRegister(this); - this->RootElement = nullptr; - } - this->SetSourceLibraryElement(nullptr); - this->SetCode(nullptr); - this->CleanupArgs(); -} - -//----------------------------------------------------------------------------- -void vtkXMLShader::SetRootElement(vtkXMLDataElement *root) -{ - vtkSetObjectBodyMacro(RootElement, vtkXMLDataElement, root); - this->SetCode(nullptr); - this->SetSourceLibraryElement(nullptr); // release the SourceLibrary element. -} - -//----------------------------------------------------------------------------- -// Note that this method allocates a new string which must be deleted by -// the caller. -char *vtkXMLShader::LocateFile(const char *filename) -{ - if (!filename) - { - return nullptr; - } - - // if filename is absolute path, return the same. - if (vtksys::SystemTools::FileExists(filename)) - { - return vtksys::SystemTools::DuplicateString(filename); - } - - // Fetch any runtime defined user paths for materials - std::vector paths; - std::string userpaths; - vtksys::SystemTools::GetEnv("USER_MATERIALS_DIRS", userpaths); - if (userpaths.size() > 0) - { - vtksys::SystemTools::Split(userpaths.c_str(), paths, ';'); - } - -#ifdef VTK_MATERIALS_DIRS - // search thru default paths to locate file. - vtksys::SystemTools::Split(VTK_MATERIALS_DIRS, paths, ';'); -#endif - for (unsigned int i = 0; i < paths.size(); i++) - { - std::string path = paths[i]; - if (path.size() == 0) - { - continue; - } - vtksys::SystemTools::ConvertToUnixSlashes(path); - if (path[path.size() - 1] != '/') - { - path += "/"; - } - path += filename; - if (vtksys::SystemTools::FileExists(path.c_str())) - { - return vtksys::SystemTools::DuplicateString(path.c_str()); - } - } - return nullptr; -} - -//----------------------------------------------------------------------------- -int vtkXMLShader::GetScope() -{ - if (this->RootElement) - { - const char *scope = this->RootElement->GetAttribute("scope"); - if (!scope) - { - vtkErrorMacro("Shader description missing \"scope\" attribute."); - } - else if (strcmp(scope, "Vertex") == 0) - { - return vtkXMLShader::SCOPE_VERTEX; - } - else if (strcmp(scope, "Fragment") == 0) - { - return vtkXMLShader::SCOPE_FRAGMENT; - } - else if (strcmp(scope, "Geometry") == 0) - { - return vtkXMLShader::SCOPE_GEOMETRY; - } - } - return vtkXMLShader::SCOPE_NONE; -} - -// ---------------------------------------------------------------------------- -// \post valid_result: result==1 || result==2 -int vtkXMLShader::GetStyle() -{ - int result = 1; - if (this->RootElement) - { - const char *loc = this->RootElement->GetAttribute("style"); - if (loc == nullptr) - { - // fine. this attribute is optional. - } - else - { - if (strcmp(loc, "1") == 0) - { - // fine. default value. - } - else - { - if (strcmp(loc, "2") == 0) - { - result = 2; // new style - } - else - { - vtkErrorMacro(<< "style number not supported. Expect 1 or 2. We force it to be 1."); - } - } - } - } - - assert("post valid_result" && (result == 1 || result == 2)); - return result; -} - -//----------------------------------------------------------------------------- -const char *vtkXMLShader::GetName() -{ - return (this->RootElement) ? this->RootElement->GetAttribute("name") : nullptr; -} - -//----------------------------------------------------------------------------- -const char *vtkXMLShader::GetEntry() -{ - return (this->RootElement) ? this->RootElement->GetAttribute("entry") : nullptr; -} - -//----------------------------------------------------------------------------- -const char **vtkXMLShader::GetArgs() -{ - this->CleanupArgs(); - if (!this->RootElement || !this->RootElement->GetAttribute("args")) - { - return nullptr; - } - - std::vector args; - vtksys::SystemTools::Split(this->RootElement->GetAttribute("args"), args, ' '); - - int i; - int size = static_cast(args.size()); - if (size == 0) - { - return nullptr; - } - this->Args = new char *[size + 1]; - for (i = 0; i < size; i++) - { - this->Args[i] = vtksys::SystemTools::DuplicateString(args[i].c_str()); - } - this->Args[size] = nullptr; - return const_cast(this->Args); -} - -//----------------------------------------------------------------------------- -const char *vtkXMLShader::GetCode() -{ - return this->RootElement->GetCharacterData(); -} - -//----------------------------------------------------------------------------- -void vtkXMLShader::CleanupArgs() -{ - if (this->Args) - { - char **a = this->Args; - while (*a) - { - delete[](*a); - a++; - } - delete[] this->Args; - this->Args = nullptr; - } -} - -//----------------------------------------------------------------------------- -void vtkXMLShader::PrintSelf(ostream &os, vtkIndent indent) -{ - this->Superclass::PrintSelf(os, indent); - os << indent << "Name: " << (this->GetName() ? this->GetName() : "(none)") << endl; - os << indent << "Scope: "; - switch (this->GetScope()) - { - case SCOPE_NONE: - os << "None"; - break; - case SCOPE_MIXED: - os << "Mixed"; - break; - case SCOPE_VERTEX: - os << "Vertex"; - break; - case SCOPE_FRAGMENT: - os << "Fragment"; - break; - case SCOPE_GEOMETRY: - os << "Geometry"; - break; - } - os << endl; - - os << indent << "Entry: " << (this->GetEntry() ? this->GetEntry() : "(none)") << endl; - os << indent << "Args: "; - const char **args = this->GetArgs(); - if (!args) - { - os << "(none)" << endl; - } - else - { - while (*args) - { - os << indent << *args << " "; - args++; - } - os << endl; - } - - os << indent << "RootElement: "; - if (this->RootElement) - { - os << endl; - this->RootElement->PrintSelf(os, indent.GetNextIndent()); - } - else - { - os << "(none)" << endl; - } -} diff --git a/Modules/VtkShaders/src/vtkXMLShader.h b/Modules/VtkShaders/src/vtkXMLShader.h deleted file mode 100644 index 2e08590882..0000000000 --- a/Modules/VtkShaders/src/vtkXMLShader.h +++ /dev/null @@ -1,129 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -/*========================================================================= - - Program: Visualization Toolkit - Module: vtkXMLShader.h - - Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen - All rights reserved. - See Copyright.txt or http://www.kitware.com/Copyright.htm for details. - - This software is distributed WITHOUT ANY WARRANTY; without even - the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR - PURPOSE. See the above copyright notice for more information. - -=========================================================================*/ -// .NAME vtkXMLShader - encapsulates a Shader XML description. -// .SECTION Description -// vtkXMLShader encapsulates the XML description for a Shader. -// It provides convenient access to various attributes/properties -// of a shader. -// .SECTION Thanks -// Shader support in VTK includes key contributions by Gary Templet at -// Sandia National Labs. - -#ifndef __vtkXMLShader_h -#define __vtkXMLShader_h - -#include "vtkObject.h" -#include "vtkRenderingCoreModule.h" // For export macro - -class vtkXMLDataElement; - -class vtkXMLShader : public vtkObject -{ -public: - static vtkXMLShader *New(); - vtkTypeMacro(vtkXMLShader, vtkObject); - void PrintSelf(ostream &os, vtkIndent indent) override; - - // Description: - // Get/Set the XML root element that describes this shader. - vtkGetObjectMacro(RootElement, vtkXMLDataElement); - void SetRootElement(vtkXMLDataElement *); - - // Description: - // Returns the type of the shader as defined in the XML description. - int GetScope(); - - // Description: - // Returns the style of the shader as optionaly defined in the XML - // description. If not present, default style is 1. "style=2" means it is - // a shader without a main(). In style 2, the "main" function for the vertex - // shader part is void propFuncVS(void), the main function for the fragment - // shader part is void propFuncFS(). This is useful when combining a shader - // at the actor level and a shader defines at the renderer level, like - // the depth peeling pass. - // \post valid_result: result==1 || result==2 - int GetStyle(); - - // Description: - // Get the name of the Shader. - const char *GetName(); - - // Description: - // Get the entry point to the shader code as defined in the XML. - const char *GetEntry(); - - // Description: - // Get the shader code. - const char *GetCode(); - - // Description: - // Returns an null terminate array of the pointers to space sepatared Args - // defined in the XML description. - const char **GetArgs(); - - // Description: - // Searches the file in the VTK_MATERIALS_DIRS. - // Note that this allocates new memory for the string. - // The caller must delete it. - static char *LocateFile(const char *filename); - - // BTX - - enum ScopeCodes - { - SCOPE_NONE = 0, - SCOPE_MIXED, - SCOPE_VERTEX, - SCOPE_FRAGMENT, - SCOPE_GEOMETRY - }; - - // ETX -protected: - vtkXMLShader(); - ~vtkXMLShader(); - - char *Code; // cache for the code. - vtkSetStringMacro(Code); - - vtkXMLDataElement *RootElement; - vtkXMLDataElement *SourceLibraryElement; - void SetSourceLibraryElement(vtkXMLDataElement *); - - char **Args; - void CleanupArgs(); - -private: - vtkXMLShader(const vtkXMLShader &); // Not implemented. - void operator=(const vtkXMLShader &); // Not implemented. -}; - -#endif diff --git a/Plugins/PluginList.cmake b/Plugins/PluginList.cmake index 851b793d99..1a830c4d39 100644 --- a/Plugins/PluginList.cmake +++ b/Plugins/PluginList.cmake @@ -1,101 +1,99 @@ # Plug-ins must be ordered according to their dependencies set(MITK_PLUGINS org.blueberry.core.runtime:ON org.blueberry.core.expressions:OFF org.blueberry.core.commands:OFF org.blueberry.core.jobs:OFF org.blueberry.ui.qt:OFF org.blueberry.ui.qt.help:ON org.blueberry.ui.qt.log:ON org.blueberry.ui.qt.objectinspector:OFF #org.blueberry.test:ON #org.blueberry.uitest:ON #Testing/org.blueberry.core.runtime.tests:ON #Testing/org.blueberry.osgi.tests:ON org.mitk.core.services:ON org.mitk.gui.common:ON org.mitk.planarfigure:ON org.mitk.core.ext:OFF org.mitk.core.jobs:OFF - org.mitk.simulation:OFF org.mitk.gui.qt.application:ON org.mitk.gui.qt.coreapplication:OFF org.mitk.gui.qt.ext:OFF org.mitk.gui.qt.extapplication:OFF org.mitk.gui.qt.common:ON org.mitk.gui.qt.stdmultiwidgeteditor:ON org.mitk.gui.qt.common.legacy:OFF org.mitk.gui.qt.cmdlinemodules:OFF org.mitk.gui.qt.diffusionimagingapp:OFF org.mitk.gui.qt.datamanager:ON org.mitk.gui.qt.datamanagerlight:OFF org.mitk.gui.qt.properties:ON org.mitk.gui.qt.basicimageprocessing:OFF org.mitk.gui.qt.dicom:OFF org.mitk.gui.qt.dicominspector:OFF org.mitk.gui.qt.diffusionimaging:OFF org.mitk.gui.qt.diffusionimaging.connectomics:OFF org.mitk.gui.qt.diffusionimaging.denoising:OFF org.mitk.gui.qt.diffusionimaging.fiberfox:OFF org.mitk.gui.qt.diffusionimaging.fiberprocessing:OFF org.mitk.gui.qt.diffusionimaging.ivim:OFF org.mitk.gui.qt.diffusionimaging.odfpeaks:OFF org.mitk.gui.qt.diffusionimaging.partialvolume:OFF org.mitk.gui.qt.diffusionimaging.preprocessing:OFF org.mitk.gui.qt.diffusionimaging.reconstruction:OFF org.mitk.gui.qt.diffusionimaging.registration:OFF org.mitk.gui.qt.diffusionimaging.tbss:OFF org.mitk.gui.qt.diffusionimaging.tractography:OFF org.mitk.gui.qt.dosevisualization:OFF org.mitk.gui.qt.geometrytools:OFF org.mitk.gui.qt.igtexamples:OFF org.mitk.gui.qt.igttracking:OFF org.mitk.gui.qt.lasercontrol:OFF org.mitk.gui.qt.openigtlink:OFF org.mitk.gui.qt.imagecropper:OFF org.mitk.gui.qt.imagenavigator:ON org.mitk.gui.qt.viewnavigator:OFF org.mitk.gui.qt.materialeditor:OFF org.mitk.gui.qt.measurementtoolbox:OFF org.mitk.gui.qt.moviemaker:OFF org.mitk.gui.qt.pointsetinteraction:OFF org.mitk.gui.qt.pointsetinteractionmultispectrum:OFF org.mitk.gui.qt.python:OFF org.mitk.gui.qt.remeshing:OFF org.mitk.gui.qt.segmentation:OFF - org.mitk.gui.qt.simulation:OFF org.mitk.gui.qt.aicpregistration:OFF org.mitk.gui.qt.renderwindowmanager:OFF org.mitk.gui.qt.toftutorial:OFF org.mitk.gui.qt.tofutil:OFF org.mitk.gui.qt.tubegraph:OFF org.mitk.gui.qt.ugvisualization:OFF org.mitk.gui.qt.photoacoustics.pausviewer:OFF org.mitk.gui.qt.photoacoustics.imageprocessing:OFF org.mitk.gui.qt.ultrasound:OFF org.mitk.gui.qt.volumevisualization:OFF org.mitk.gui.qt.eventrecorder:OFF org.mitk.gui.qt.xnat:OFF org.mitk.gui.qt.igt.app.echotrack:OFF org.mitk.gui.qt.spectrocamrecorder:OFF org.mitk.gui.qt.classificationsegmentation:OFF org.mitk.gui.qt.overlaymanager:OFF org.mitk.gui.qt.igt.app.hummelprotocolmeasurements:OFF org.mitk.gui.qt.multilabelsegmentation:OFF org.mitk.matchpoint.core.helper:OFF org.mitk.gui.qt.matchpoint.algorithm.browser:OFF org.mitk.gui.qt.matchpoint.algorithm.control:OFF org.mitk.gui.qt.matchpoint.algorithm.batch:OFF org.mitk.gui.qt.matchpoint.mapper:OFF org.mitk.gui.qt.matchpoint.framereg:OFF org.mitk.gui.qt.matchpoint.visualizer:OFF org.mitk.gui.qt.matchpoint.evaluator:OFF org.mitk.gui.qt.matchpoint.manipulator:OFF org.mitk.gui.qt.cest:OFF ) diff --git a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTDoseVisualizer.h b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTDoseVisualizer.h index 265bf49572..0b77184264 100644 --- a/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTDoseVisualizer.h +++ b/Plugins/org.mitk.gui.qt.dosevisualization/src/internal/RTDoseVisualizer.h @@ -1,171 +1,169 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef RTDoseVisualizer_h #define RTDoseVisualizer_h #include #include #include #include "ui_RTDoseVisualizerControls.h" #include #include #include "mitkDoseVisPreferenceHelper.h" // Shader #include -#include -#include #include #include #include #include #include /*forward declarations*/ class QmitkIsoDoseLevelSetModel; class QmitkDoseColorDelegate; class QmitkDoseValueDelegate; class QmitkDoseVisualStyleDelegate; class ctkEvent; /** \brief RTDoseVisualizer \warning This class is not yet documented. Use "git blame" and ask the author to provide basic documentation. \sa QmitkAbstractView \ingroup ${plugin_target}_internal */ class RTDoseVisualizer : public QmitkAbstractView { // this is needed for all Qt objects that should have a Qt meta-object // (everything that derives from QObject and wants to have signal/slots) Q_OBJECT public: RTDoseVisualizer(); virtual ~RTDoseVisualizer(); static const std::string VIEW_ID; void OnSliceChanged(itk::Object *sender, const itk::EventObject &e); protected slots: void OnAddFreeValueClicked(); void OnRemoveFreeValueClicked(); void OnUsePrescribedDoseClicked(); void OnDataChangedInIsoLevelSetView(); void OnAbsDoseToggled(bool); void OnGlobalVisColorWashToggled(bool); void OnGlobalVisIsoLineToggled(bool); void OnShowContextMenuIsoSet(const QPoint&); void OnCurrentPresetChanged(const QString&); void OnReferenceDoseChanged(double); void OnHandleCTKEventReferenceDoseChanged(const ctkEvent& event); void OnHandleCTKEventPresetsChanged(const ctkEvent& event); void OnHandleCTKEventGlobalVisChanged(const ctkEvent& event); void ActualizeFreeIsoLine(); void OnDoseClicked(); protected: virtual void CreateQtPartControl(QWidget *parent); virtual void SetFocus(); /// \brief called by QmitkFunctionality when DataManager's selection has changed virtual void OnSelectionChanged( berry::IWorkbenchPart::Pointer source, const QList& nodes ); /** Update the transfer funtion property for the color wash*/ void UpdateColorWashTransferFunction(); /** Method updates the list widget according to the current free iso values.*/ void UpdateFreeIsoValues(); /** Update the members according to the currently selected node */ void UpdateBySelectedNode(); /** Update the member widgets according to the information stored in the application preferences*/ void UpdateByPreferences(); /**helper function that iterates throug all data nodes and sets there iso level set property according to the selected preset. @TODO: should be moved outside the class, to be available for other classes at well.*/ void ActualizeIsoLevelsForAllDoseDataNodes(); /**helper function that iterates throug all data nodes and sets there reference dose value according to the preference. @TODO: should be moved outside the class, to be available for other classes at well.*/ void ActualizeReferenceDoseForAllDoseDataNodes(); /**helper function that iterates through all data nodes and sets there dose display style (relative/absolute) according to the preference. @TODO: should be moved outside the class, to be available for other classes at well.*/ void ActualizeDisplayStyleForAllDoseDataNodes(); void NodeRemoved(const mitk::DataNode* node) override; void NodeChanged(const mitk::DataNode *node) override; Ui::RTDoseVisualizerControls m_Controls; mitk::DataNode::Pointer m_selectedNode; unsigned int m_freeIsoValuesCount; mitk::PresetMapType m_Presets; std::string m_selectedPresetName; /** Prescribed Dose of the selected data.*/ mitk::DoseValueAbs m_PrescribedDose_Data; QmitkIsoDoseLevelSetModel* m_LevelSetModel; QmitkDoseColorDelegate* m_DoseColorDelegate; QmitkDoseValueDelegate* m_DoseValueDelegate; QmitkDoseVisualStyleDelegate* m_DoseVisualDelegate; bool m_internalUpdate; private: mitk::DataNode::Pointer GetIsoDoseNode(mitk::DataNode::Pointer doseNode); bool ModalityIsRTDose(const mitk::DataNode* dataNode) const; }; #endif // RTDoseVisualizer_h diff --git a/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/Filter/mitkUSNavigationTargetOcclusionFilter.cpp b/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/Filter/mitkUSNavigationTargetOcclusionFilter.cpp index 96c60f6604..ddb5e240e1 100644 --- a/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/Filter/mitkUSNavigationTargetOcclusionFilter.cpp +++ b/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/Filter/mitkUSNavigationTargetOcclusionFilter.cpp @@ -1,193 +1,193 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // MITK #include "mitkUSNavigationTargetOcclusionFilter.h" #include "mitkDataNode.h" #include "mitkSurface.h" // VTK #include "vtkSmartPointer.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkOBBTree.h" #include "vtkFloatArray.h" #include "vtkTransform.h" #include "vtkTransformPolyDataFilter.h" mitk::USNavigationTargetOcclusionFilter::USNavigationTargetOcclusionFilter() : m_StartPositionInput(0) { } mitk::USNavigationTargetOcclusionFilter::~USNavigationTargetOcclusionFilter() { } void mitk::USNavigationTargetOcclusionFilter::SetTargetStructure(itk::SmartPointer targetStructure) { m_TargetStructure = targetStructure; } void mitk::USNavigationTargetOcclusionFilter::SetObstacleStructures(DataStorage::SetOfObjects::ConstPointer obstacleStructures) { m_ObstacleStructures = obstacleStructures; } void mitk::USNavigationTargetOcclusionFilter::SelectStartPositionInput(unsigned int n) { m_StartPositionInput = n; } void mitk::USNavigationTargetOcclusionFilter::GenerateData() { mitk::NavigationDataPassThroughFilter::GenerateData(); // get vtk surface an the points vtkPolyData* targetSurfaceVtk = this->GetVtkPolyDataOfTarget(); if ( ! targetSurfaceVtk ) { return; } // cannot do anything without a target surface vtkIdType numberOfPoints = targetSurfaceVtk->GetNumberOfPoints(); // create array for scalar values vtkSmartPointer colors = vtkSmartPointer::New(); colors->SetNumberOfComponents(1); colors->SetName("USNavigation::Occlusion"); const mitk::NavigationData* nd = this->GetInput(m_StartPositionInput); // set every value to -1 if there is no (valid) navigation data if ( nd == 0 || ! nd->IsDataValid() ) { float intersection = -1; for ( vtkIdType n = 0; n < numberOfPoints; n++ ) { - colors->InsertNextTupleValue(&intersection); + colors->InsertNextTuple1(intersection); } if ( numberOfPoints > 0 ) { targetSurfaceVtk->GetPointData()->AddArray(colors); targetSurfaceVtk->GetPointData()->Update(); } return; } // initialize values with 0 (no intersection) if there is valid navigation // data and there are some obstacle structures defined else if ( m_ObstacleStructures.IsNull() ) { float intersection = 0; for ( vtkIdType n = 0; n < numberOfPoints; n++ ) { - colors->InsertNextTupleValue(&intersection); + colors->InsertNextTuple1(intersection); } if ( numberOfPoints > 0 ) { targetSurfaceVtk->GetPointData()->AddArray(colors); targetSurfaceVtk->GetPointData()->Update(); } return; } // get the current position from the navigation data mitk::Point3D position = nd->GetPosition(); double point1[3]; point1[0] = position[0]; point1[1] = position[1]; point1[2] = position[2]; // transform vtk polydata according to mitk geometry vtkSmartPointer transformFilter = vtkSmartPointer::New(); transformFilter->SetInputData(0, targetSurfaceVtk); transformFilter->SetTransform(m_TargetStructure->GetData()->GetGeometry()->GetVtkTransform()); transformFilter->Update(); vtkPolyData* targetSurfaceVtkTransformed = transformFilter->GetOutput(); std::vector occlusion(numberOfPoints, false); // calculate occlusion for every obstacle structure for (mitk::DataStorage::SetOfObjects::ConstIterator it = m_ObstacleStructures->Begin(); it != m_ObstacleStructures->End(); ++it) { vtkPolyData* polyData = dynamic_cast(it->Value()->GetData())->GetVtkPolyData(); // transform the obstacle strucutre according to the mitk geometry vtkSmartPointer transformFilter = vtkSmartPointer::New(); transformFilter->SetInputData(0, polyData); transformFilter->SetTransform(it->Value()->GetData()->GetGeometry()->GetVtkTransform()); transformFilter->Update(); polyData = transformFilter->GetOutput(); // build an obb tree locator vtkSmartPointer cellLocator = vtkSmartPointer::New(); cellLocator->SetDataSet(polyData); cellLocator->BuildLocator(); // test for intersection with every point on the surface for ( unsigned int n = 0; n < numberOfPoints; n++ ) { vtkSmartPointer points = vtkSmartPointer::New(); if ( cellLocator->IntersectWithLine(point1, targetSurfaceVtkTransformed->GetPoint(n), points, nullptr) != 0 ) { occlusion.at(n) = true; } } } if ( numberOfPoints > 0 ) { // set the occlusion values as scalar array to the vtkPolyData float one = 1.0f; float zero = 0.0f; for ( std::vector::iterator it = occlusion.begin(); it != occlusion.end(); ++it ) { - colors->InsertNextTupleValue(*it ? &one : &zero); + colors->InsertNextTuple1(*it ? one : zero); } targetSurfaceVtk->GetPointData()->AddArray(colors); targetSurfaceVtk->GetPointData()->Update(); } } vtkSmartPointer mitk::USNavigationTargetOcclusionFilter::GetVtkPolyDataOfTarget() { if ( m_TargetStructure.IsNull() ) { MITK_WARN("USNavigationTargetOcclusionFilter") << "Target structure must not be null."; return nullptr; } mitk::Surface::Pointer targetSurface = dynamic_cast(m_TargetStructure->GetData()); if ( targetSurface.IsNull() ) { MITK_WARN("USNavigationTargetOcclusionFilter") << "A mitk::Surface has to be set to the data node."; return nullptr; } vtkSmartPointer targetSurfaceVtk = targetSurface->GetVtkPolyData(); if( targetSurfaceVtk == 0 ) { MITK_WARN("USNavigationTargetOcclusionFilter") << "VtkPolyData of the mitk::Surface of the data node must not be null."; return nullptr; } return targetSurfaceVtk; } diff --git a/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/Filter/mitkUSNavigationTargetUpdateFilter.cpp b/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/Filter/mitkUSNavigationTargetUpdateFilter.cpp index 397185d4a7..47835e4675 100644 --- a/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/Filter/mitkUSNavigationTargetUpdateFilter.cpp +++ b/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/Filter/mitkUSNavigationTargetUpdateFilter.cpp @@ -1,270 +1,270 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkUSNavigationTargetUpdateFilter.h" #include #include "mitkDataNode.h" #include "mitkSurface.h" #include "vtkSmartPointer.h" #include "vtkUnsignedCharArray.h" #include "vtkPolyData.h" #include "vtkPointData.h" #include "vtkLookupTable.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "vtkFloatArray.h" #include "vtkTransformPolyDataFilter.h" #include "vtkLinearTransform.h" mitk::USNavigationTargetUpdateFilter::USNavigationTargetUpdateFilter() : m_NumberOfTargets(0), m_OptimalAngle(0), m_ScalarArrayIdentifier("USNavigation::NoIdentifierSet"), m_UseMaximumScore(false) { } mitk::USNavigationTargetUpdateFilter::~USNavigationTargetUpdateFilter() { } void mitk::USNavigationTargetUpdateFilter::SetTargetStructure(DataNode::Pointer targetStructure) { m_TargetStructure = targetStructure; // get vtk surface and the points vtkSmartPointer targetSurfaceVtk = this->GetVtkPolyDataOfTarget(); int numberOfPoints = targetSurfaceVtk->GetNumberOfPoints(); if ( numberOfPoints > 0 ) { // create vtk scalar array for score values vtkSmartPointer colors = vtkSmartPointer::New(); colors->SetNumberOfComponents(1); colors->SetName(m_ScalarArrayIdentifier.c_str()); // initialize with green color float color = 1; for (int n = 0; n < numberOfPoints ; ++n) { - colors->InsertNextTupleValue(&color); + colors->InsertNextTuple1(color); } // add the scores array to the target surface targetSurfaceVtk->GetPointData()->AddArray(colors); targetSurfaceVtk->GetPointData()->Update(); } } bool mitk::USNavigationTargetUpdateFilter::SetNumberOfTargets(unsigned int numberOfTargets) { if ( numberOfTargets < 1 || numberOfTargets > 4 ) { MITK_WARN << "Number of targets can only be between 1 and 4."; return false; } if ( numberOfTargets == 1 ) { m_OptimalAngle = 0; } else if ( numberOfTargets < 5 ) { // for every number of targets between 2 and 4 the optimal angle can be // calculated using the arcus cosinus m_OptimalAngle = acos(-1.0/(numberOfTargets-1)); } m_NumberOfTargets = numberOfTargets; return true; } void mitk::USNavigationTargetUpdateFilter::SetOptimalAngle(double optimalAngle) { m_OptimalAngle = optimalAngle; } double mitk::USNavigationTargetUpdateFilter::GetOptimalAngle() { return m_OptimalAngle; } void mitk::USNavigationTargetUpdateFilter::SetScalarArrayIdentifier(std::string scalarArrayIdentifier) { m_ScalarArrayIdentifier = scalarArrayIdentifier; } void mitk::USNavigationTargetUpdateFilter::SetUseMaximumScore(bool useMaximumScore) { m_UseMaximumScore = useMaximumScore; } void mitk::USNavigationTargetUpdateFilter::SetControlNode(unsigned int id, itk::SmartPointer controlNode) { // make sure that the node fit into the vector and insert it then if ( m_ControlNodesVector.size() <= id ) { m_ControlNodesVector.resize(id+1); } m_ControlNodesVector[id] = controlNode; this->UpdateTargetScores(); } void mitk::USNavigationTargetUpdateFilter::RemovePositionOfTarget(unsigned int id) { if ( id >= m_ControlNodesVector.size() ) { mitkThrow() << "Given id is larger than the vector size."; } m_ControlNodesVector.erase(m_ControlNodesVector.begin()+id); this->UpdateTargetScores(); } void mitk::USNavigationTargetUpdateFilter::Reset() { m_ControlNodesVector.clear(); if ( m_TargetStructure.IsNotNull() ) { this->UpdateTargetScores(); } } void mitk::USNavigationTargetUpdateFilter::UpdateTargetScores() { mitk::BaseGeometry::Pointer targetStructureGeometry = this->GetGeometryOfTarget(); mitk::Point3D targetStructureOrigin = targetStructureGeometry->GetOrigin(); // get vtk surface and the points vtkSmartPointer targetSurfaceVtk = this->GetVtkPolyDataOfTarget(); int numberOfPoints = targetSurfaceVtk->GetNumberOfPoints(); // transform vtk polydata according to mitk geometry vtkSmartPointer transformFilter = vtkSmartPointer::New(); transformFilter->SetInputData(0, targetSurfaceVtk); transformFilter->SetTransform(targetStructureGeometry->GetVtkTransform()); transformFilter->Update(); vtkPolyData* targetSurfaceVtkTransformed = transformFilter->GetOutput(); if ( numberOfPoints > 0 ) { vtkSmartPointer colors = vtkSmartPointer::New(); colors->SetNumberOfComponents(1); colors->SetName(m_ScalarArrayIdentifier.c_str()); for (int n = 0; n < numberOfPoints ; ++n) { float score = m_UseMaximumScore ? 0.0 : 1.0; if ( m_ControlNodesVector.empty() ) { // first target can be placed everywhere score = 1; } else if ( m_ControlNodesVector.size() == m_NumberOfTargets ) { // if all targets are placed, there is no // good position for another target score = 0; } else { double coordinates[3]; mitk::Point3D coordinatesMitk; targetSurfaceVtkTransformed->GetPoint(n, coordinates); coordinatesMitk[0] = coordinates[0]; coordinatesMitk[1] = coordinates[1]; coordinatesMitk[2] = coordinates[2]; // vector pointing from the current surface coordinates to the origin // of the target structure itk::Vector vector = targetStructureOrigin - coordinatesMitk; vector.Normalize(); for (std::vector::iterator it = m_ControlNodesVector.begin(); it != m_ControlNodesVector.end(); ++it) { if ( (*it)->GetData() == 0 || (*it)->GetData()->GetGeometry() == 0 ) { mitkThrow() << "Control data node and geometry of the node must not be null."; } itk::Vector controlPointToOriginVector = targetStructureOrigin - (*it)->GetData()->GetGeometry()->GetOrigin(); controlPointToOriginVector.Normalize(); float angle = acos( vector * controlPointToOriginVector ); float angleDifference = angle - m_OptimalAngle; float tmpScore = 1 - (angleDifference >= 0 ? angleDifference : -angleDifference); // update the score if the current score is larger (or lower) than // this score if ( (m_UseMaximumScore && tmpScore > score) || (!m_UseMaximumScore && tmpScore < score) ) { score = tmpScore; } } } - colors->InsertNextTupleValue(&score); + colors->InsertNextTuple1(score); } targetSurfaceVtk->GetPointData()->AddArray(colors); targetSurfaceVtk->GetPointData()->Update(); } } vtkSmartPointer mitk::USNavigationTargetUpdateFilter::GetVtkPolyDataOfTarget() { if ( m_TargetStructure.IsNull() ) { mitkThrow() << "Target structure must not be null."; } mitk::Surface::Pointer targetSurface = dynamic_cast(m_TargetStructure->GetData()); if ( targetSurface.IsNull() ) { mitkThrow() << "A mitk::Surface has to be set to the data node."; } vtkSmartPointer targetSurfaceVtk = targetSurface->GetVtkPolyData(); if( targetSurfaceVtk == 0 ) { mitkThrow() << "VtkPolyData of the mitk::Surface of the data node must not be null."; } return targetSurfaceVtk; } mitk::BaseGeometry::Pointer mitk::USNavigationTargetUpdateFilter::GetGeometryOfTarget() { if ( m_TargetStructure.IsNull() ) { mitkThrow() << "Target structure must be set before position of target is set."; } mitk::BaseData* targetStructureData = m_TargetStructure->GetData(); if ( ! targetStructureData ) { mitkThrow() << "Data of target structure must not be null."; } mitk::BaseGeometry::Pointer targetStructureGeometry = targetStructureData->GetGeometry(); if ( targetStructureGeometry.IsNull() ) { mitkThrow() << "Geometry of target structure must not be null."; } return targetStructureGeometry; } diff --git a/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/NavigationStepWidgets/QmitkUSNavigationStepMarkerIntervention.cpp b/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/NavigationStepWidgets/QmitkUSNavigationStepMarkerIntervention.cpp index 01997b4002..fe43a0e31d 100644 --- a/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/NavigationStepWidgets/QmitkUSNavigationStepMarkerIntervention.cpp +++ b/Plugins/org.mitk.gui.qt.igt.app.echotrack/src/internal/NavigationStepWidgets/QmitkUSNavigationStepMarkerIntervention.cpp @@ -1,1020 +1,1020 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkUSNavigationStepMarkerIntervention.h" #include "ui_QmitkUSNavigationStepMarkerIntervention.h" #include "mitkBaseRenderer.h" #include "mitkContourModel.h" #include "mitkNeedleProjectionFilter.h" #include "mitkNodeDisplacementFilter.h" #include "mitkSurface.h" #include "mitkTextAnnotation2D.h" #include #include #include "../Filter/mitkUSNavigationTargetIntersectionFilter.h" #include "../Filter/mitkUSNavigationTargetOcclusionFilter.h" #include "../Filter/mitkUSNavigationTargetUpdateFilter.h" #include "../USNavigationMarkerPlacement.h" #include "../Widgets/QmitkZoneProgressBar.h" #include "../mitkUSTargetPlacementQualityCalculator.h" #include "../Interactors/mitkUSPointMarkInteractor.h" #include "usModuleRegistry.h" #include "mitkLookupTable.h" #include "mitkLookupTableProperty.h" #include "mitkSurface.h" // VTK #include "vtkCellLocator.h" #include "vtkDataSet.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkIdList.h" #include "vtkLinearTransform.h" #include "vtkLookupTable.h" #include "vtkMath.h" #include "vtkOBBTree.h" #include "vtkPointData.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkSelectEnclosedPoints.h" #include "vtkSmartPointer.h" #include "vtkSphereSource.h" #include "vtkTransformPolyDataFilter.h" #include "vtkWarpScalar.h" QmitkUSNavigationStepMarkerIntervention::QmitkUSNavigationStepMarkerIntervention(QWidget *parent) : QmitkUSAbstractNavigationStep(parent), m_NumberOfTargets(0), m_TargetProgressBar(0), m_PlannedTargetProgressBar(0), m_CurrentTargetIndex(0), m_CurrentTargetReached(false), m_ShowPlanningColors(false), m_NeedleProjectionFilter(mitk::NeedleProjectionFilter::New()), m_NodeDisplacementFilter(mitk::NodeDisplacementFilter::New()), m_TargetUpdateFilter(mitk::USNavigationTargetUpdateFilter::New()), m_TargetOcclusionFilter(mitk::USNavigationTargetOcclusionFilter::New()), m_TargetIntersectionFilter(mitk::USNavigationTargetIntersectionFilter::New()), m_PlacementQualityCalculator(mitk::USTargetPlacementQualityCalculator::New()), m_TargetStructureWarnOverlay(mitk::TextAnnotation2D::New()), m_ReferenceSensorIndex(1), m_NeedleSensorIndex(0), m_ListenerTargetCoordinatesChanged(this, &QmitkUSNavigationStepMarkerIntervention::UpdateTargetCoordinates), ui(new Ui::QmitkUSNavigationStepMarkerIntervention) { m_ActiveTargetColor[0] = 1; m_ActiveTargetColor[1] = 1; m_ActiveTargetColor[2] = 0; m_InactiveTargetColor[0] = 1; m_InactiveTargetColor[1] = 1; m_InactiveTargetColor[2] = 0.5; m_ReachedTargetColor[0] = 0.6; m_ReachedTargetColor[1] = 1; m_ReachedTargetColor[2] = 0.6; ui->setupUi(this); connect(ui->freezeImageButton, SIGNAL(SignalFreezed(bool)), this, SLOT(OnFreeze(bool))); connect(ui->backToLastTargetButton, SIGNAL(clicked()), this, SLOT(OnBackToLastTargetClicked())); connect(ui->targetReachedButton, SIGNAL(clicked()), this, SLOT(OnTargetLeft())); connect(this, SIGNAL(TargetReached(int)), this, SLOT(OnTargetReached())); connect(this, SIGNAL(TargetLeft(int)), this, SLOT(OnTargetLeft())); connect(ui->riskStructuresRangeWidget, SIGNAL(SignalZoneViolated(const mitk::DataNode *, mitk::Point3D)), this, SLOT(OnRiskZoneViolated(const mitk::DataNode *, mitk::Point3D))); m_PointMarkInteractor = mitk::USPointMarkInteractor::New(); m_PointMarkInteractor->CoordinatesChangedEvent.AddListener(m_ListenerTargetCoordinatesChanged); this->GenerateTargetColorLookupTable(); m_TargetProgressBar = new QmitkZoneProgressBar(QString::fromStdString("Target: %1 mm"), 200, 0, this); m_TargetProgressBar->SetTextFormatInvalid("Target is not on Needle Path"); ui->targetStructuresRangeLayout->addWidget(m_TargetProgressBar); m_TargetUpdateFilter->SetScalarArrayIdentifier("USNavigation::ReachedTargetScores"); } QmitkUSNavigationStepMarkerIntervention::~QmitkUSNavigationStepMarkerIntervention() { mitk::DataStorage::Pointer dataStorage = this->GetDataStorage(false); if (dataStorage.IsNotNull()) { // remove the node for the needle path mitk::DataNode::Pointer node = this->GetNamedDerivedNode("Needle Path", QmitkUSAbstractNavigationStep::DATANAME_BASENODE); if (node.IsNotNull()) { dataStorage->Remove(node); } } if (m_SegmentationNode.IsNotNull()) { this->GetDataStorage()->Remove(m_SegmentationNode); } if (m_ForegroundModelPointsNode.IsNotNull()) { this->GetDataStorage()->Remove(m_ForegroundModelPointsNode); } delete ui; m_PointMarkInteractor->CoordinatesChangedEvent.RemoveListener(m_ListenerTargetCoordinatesChanged); } bool QmitkUSNavigationStepMarkerIntervention::OnStartStep() { m_NeedleProjectionFilter->SelectInput(m_NeedleSensorIndex); // create node for Needle Projection mitk::DataNode::Pointer node = this->GetNamedDerivedNodeAndCreate("Needle Path", QmitkUSAbstractNavigationStep::DATANAME_BASENODE); node->SetData(m_NeedleProjectionFilter->GetProjection()); node->SetBoolProperty("show contour", true); // initialize warning overlay (and do not display it, yet) m_TargetStructureWarnOverlay->SetText("Warning: Needle is Inside the Target Structure."); m_TargetStructureWarnOverlay->SetVisibility(false); // set position and font size for the text overlay mitk::Point2D overlayPosition; overlayPosition.SetElement(0, 10.0f); overlayPosition.SetElement(1, 10.0f); m_TargetStructureWarnOverlay->SetPosition2D(overlayPosition); m_TargetStructureWarnOverlay->SetFontSize(18); // overlay should be red mitk::Color color; color[0] = 1; color[1] = 0; color[2] = 0; m_TargetStructureWarnOverlay->SetColor(color); mitk::ManualPlacementAnnotationRenderer::AddAnnotation(m_TargetStructureWarnOverlay.GetPointer(), "stdmulti.widget4"); return true; } bool QmitkUSNavigationStepMarkerIntervention::OnStopStep() { mitk::DataStorage::Pointer dataStorage = this->GetDataStorage(); // remove all reached nodes from the data storage for (QVector>::iterator it = m_ReachedTargetsNodes.begin(); it != m_ReachedTargetsNodes.end(); ++it) { dataStorage->Remove(*it); } m_ReachedTargetsNodes.clear(); m_CurrentTargetIndex = 0; // reset button states ui->freezeImageButton->setEnabled(false); ui->backToLastTargetButton->setEnabled(false); ui->targetReachedButton->setEnabled(true); // make sure that it is unfreezed after stopping the step ui->freezeImageButton->Unfreeze(); // remove base node for reached targets from the data storage mitk::DataNode::Pointer reachedTargetsNode = this->GetNamedDerivedNode( QmitkUSAbstractNavigationStep::DATANAME_BASENODE, USNavigationMarkerPlacement::DATANAME_REACHED_TARGETS); if (reachedTargetsNode.IsNotNull()) { dataStorage->Remove(reachedTargetsNode); } return true; } bool QmitkUSNavigationStepMarkerIntervention::OnFinishStep() { return true; } bool QmitkUSNavigationStepMarkerIntervention::OnActivateStep() { this->ClearZones(); // clear risk zones before adding new ones // get target node from data storage and make sure that it contains data m_TargetNode = this->GetNamedDerivedNode(USNavigationMarkerPlacement::DATANAME_TARGETSURFACE, USNavigationMarkerPlacement::DATANAME_TUMOUR); if (m_TargetNode.IsNull() || m_TargetNode->GetData() == 0) { mitkThrow() << "Target node (" << USNavigationMarkerPlacement::DATANAME_TARGETSURFACE << ") must not be null."; } // get target data and make sure that it is a surface m_TargetSurface = dynamic_cast(m_TargetNode->GetData()); if (m_TargetSurface.IsNull()) { mitkThrow() << "Target node (" << USNavigationMarkerPlacement::DATANAME_TARGETSURFACE << ") data must be of type mitk::Surface"; } // delete progress bars for reinitializing them again afterwards if (m_PlannedTargetProgressBar) { ui->targetStructuresRangeLayout->removeWidget(m_PlannedTargetProgressBar); delete m_PlannedTargetProgressBar; m_PlannedTargetProgressBar = 0; } m_NodeDisplacementFilter->SelectInput(m_ReferenceSensorIndex); this->UpdateTargetProgressDisplay(); mitk::DataNode::Pointer tumourNode = this->GetNamedDerivedNode(USNavigationMarkerPlacement::DATANAME_TUMOUR, QmitkUSAbstractNavigationStep::DATANAME_BASENODE); if (tumourNode.IsNotNull()) { // do not show tumour node during intervention (target surface is shown) tumourNode->SetBoolProperty("visible", false); // add tumour as a risk structure ui->riskStructuresRangeWidget->AddZone(tumourNode); } // set target structure for target update filter m_TargetUpdateFilter->SetTargetStructure(m_TargetNode); m_TargetOcclusionFilter->SetTargetStructure(m_TargetNode); // set lookup table of tumour node m_TargetNode->SetProperty("LookupTable", m_TargetColorLookupTableProperty); // mitk::DataNode::Pointer targetsBaseNode = this->GetNamedDerivedNode(USNavigationMarkerPlacement::DATANAME_TARGETS, QmitkUSAbstractNavigationStep::DATANAME_BASENODE); mitk::DataStorage::SetOfObjects::ConstPointer plannedTargetNodes; if (targetsBaseNode.IsNotNull()) { plannedTargetNodes = this->GetDataStorage()->GetDerivations(targetsBaseNode); } if (plannedTargetNodes.IsNotNull() && plannedTargetNodes->Size() > 0) { for (mitk::DataStorage::SetOfObjects::ConstIterator it = plannedTargetNodes->Begin(); it != plannedTargetNodes->End(); ++it) { m_PlannedTargetsNodes.push_back(it->Value()); } m_PlannedTargetProgressBar = new QmitkZoneProgressBar(QString::fromStdString("Planned Target"), 200, 0); ui->targetStructuresRangeLayout->addWidget(m_PlannedTargetProgressBar); } // add progress bars for risk zone nodes mitk::DataNode::Pointer zonesBaseNode = this->GetNamedDerivedNode(USNavigationMarkerPlacement::DATANAME_ZONES, QmitkUSAbstractNavigationStep::DATANAME_BASENODE); // only add progress bars if the base node for zones was created if (zonesBaseNode.IsNotNull()) { mitk::DataStorage::SetOfObjects::ConstPointer zoneNodes = this->GetDataStorage()->GetDerivations(zonesBaseNode); for (mitk::DataStorage::SetOfObjects::ConstIterator it = zoneNodes->Begin(); it != zoneNodes->End(); ++it) { ui->riskStructuresRangeWidget->AddZone(it->Value()); } m_TargetOcclusionFilter->SelectStartPositionInput(m_NeedleSensorIndex); m_TargetOcclusionFilter->SetObstacleStructures(zoneNodes); } return true; } bool QmitkUSNavigationStepMarkerIntervention::OnDeactivateStep() { ui->freezeImageButton->Unfreeze(); return true; } void QmitkUSNavigationStepMarkerIntervention::OnUpdate() { // get navigation data source and make sure that it is not null mitk::NavigationDataSource::Pointer navigationDataSource = this->GetCombinedModality()->GetNavigationDataSource(); if (navigationDataSource.IsNull()) { MITK_ERROR("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepMarkerIntervention") << "Navigation Data Source of Combined Modality must not be null."; mitkThrow() << "Navigation Data Source of Combined Modality must not be null."; } ui->riskStructuresRangeWidget->UpdateDistancesToNeedlePosition(navigationDataSource->GetOutput(m_NeedleSensorIndex)); this->UpdateBodyMarkerStatus(navigationDataSource->GetOutput(m_ReferenceSensorIndex)); this->UpdateTargetColors(); this->UpdateTargetScore(); this->UpdateTargetViolationStatus(); } void QmitkUSNavigationStepMarkerIntervention::OnSettingsChanged(const itk::SmartPointer settingsNode) { if (settingsNode.IsNull()) { return; } int numberOfTargets; if (settingsNode->GetIntProperty("settings.number-of-targets", numberOfTargets)) { m_NumberOfTargets = numberOfTargets; m_TargetUpdateFilter->SetNumberOfTargets(numberOfTargets); m_PlacementQualityCalculator->SetOptimalAngle(m_TargetUpdateFilter->GetOptimalAngle()); } std::string referenceSensorName; if (settingsNode->GetStringProperty("settings.reference-name-selected", referenceSensorName)) { m_ReferenceSensorName = referenceSensorName; } std::string needleSensorName; if (settingsNode->GetStringProperty("settings.needle-name-selected", needleSensorName)) { m_NeedleSensorName = needleSensorName; } this->UpdateSensorsNames(); } QString QmitkUSNavigationStepMarkerIntervention::GetTitle() { return "Computer-assisted Intervention"; } bool QmitkUSNavigationStepMarkerIntervention::GetIsRestartable() { return true; } QmitkUSAbstractNavigationStep::FilterVector QmitkUSNavigationStepMarkerIntervention::GetFilter() { FilterVector filter; filter.push_back(m_NeedleProjectionFilter.GetPointer()); filter.push_back(m_NodeDisplacementFilter.GetPointer()); filter.push_back(m_TargetOcclusionFilter.GetPointer()); return filter; } void QmitkUSNavigationStepMarkerIntervention::OnSetCombinedModality() { mitk::USCombinedModality::Pointer combinedModality = this->GetCombinedModality(false); if (combinedModality.IsNotNull()) { mitk::AffineTransform3D::Pointer calibration = combinedModality->GetCalibration(); if (calibration.IsNotNull()) { m_NeedleProjectionFilter->SetTargetPlane(calibration); } } ui->freezeImageButton->SetCombinedModality(combinedModality, m_ReferenceSensorIndex); this->UpdateSensorsNames(); } void QmitkUSNavigationStepMarkerIntervention::OnTargetReached() { m_CurrentTargetReached = true; } void QmitkUSNavigationStepMarkerIntervention::OnTargetLeft() { m_CurrentTargetReached = false; m_CurrentTargetIndex++; if (m_CurrentTargetIndex >= 0 && static_cast(m_CurrentTargetIndex) >= m_NumberOfTargets) { ui->targetReachedButton->setDisabled(true); } ui->backToLastTargetButton->setEnabled(true); ui->freezeImageButton->setEnabled(true); this->UpdateTargetProgressDisplay(); if (m_ReachedTargetsNodes.size() < m_CurrentTargetIndex) { mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetName( (QString("Target ") + QString("%1").arg(m_CurrentTargetIndex, 2, 10, QLatin1Char('0'))).toStdString()); this->GetDataStorage()->Add( node, this->GetNamedDerivedNodeAndCreate(USNavigationMarkerPlacement::DATANAME_REACHED_TARGETS, QmitkUSAbstractNavigationStep::DATANAME_BASENODE)); m_ReachedTargetsNodes.push_back(node); } mitk::DataNode::Pointer node = m_ReachedTargetsNodes.at(m_CurrentTargetIndex - 1); mitk::Surface::Pointer zone = mitk::Surface::New(); // create a vtk sphere with given radius vtkSphereSource *vtkData = vtkSphereSource::New(); vtkData->SetRadius(5); vtkData->SetCenter(0, 0, 0); vtkData->Update(); zone->SetVtkPolyData(vtkData->GetOutput()); vtkData->Delete(); // set vtk sphere and origin to data node node->SetData(zone); node->GetData()->GetGeometry()->SetOrigin( this->GetCombinedModality()->GetNavigationDataSource()->GetOutput(m_NeedleSensorIndex)->GetPosition()); node->SetColor(0.2, 0.9, 0.2); this->UpdateTargetCoordinates(node); } void QmitkUSNavigationStepMarkerIntervention::OnBackToLastTargetClicked() { if (m_CurrentTargetIndex < 1) { MITK_WARN << "Cannot go back to last target as there is no last target."; return; } m_CurrentTargetIndex--; if (m_ReachedTargetsNodes.size() > m_CurrentTargetIndex) { this->GetDataStorage()->Remove(m_ReachedTargetsNodes.last()); MITK_INFO("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepMarkerIntervention") << "Removed Target " << m_ReachedTargetsNodes.size(); m_ReachedTargetsNodes.pop_back(); } if (m_CurrentTargetIndex == 0) { ui->backToLastTargetButton->setDisabled(true); } if (m_CurrentTargetIndex >= 0 && static_cast(m_CurrentTargetIndex) < m_NumberOfTargets) { ui->targetReachedButton->setEnabled(true); } ui->freezeImageButton->setEnabled(false); ui->freezeImageButton->Unfreeze(); this->UpdateTargetProgressDisplay(); m_TargetUpdateFilter->RemovePositionOfTarget(m_CurrentTargetIndex); } void QmitkUSNavigationStepMarkerIntervention::OnFreeze(bool freezed) { if (freezed) { this->GetCombinedModality()->SetIsFreezed(true); // load state machine and event config for data interactor m_PointMarkInteractor->LoadStateMachine("USPointMarkInteractions.xml", us::ModuleRegistry::GetModule("MitkUS")); m_PointMarkInteractor->SetEventConfig("globalConfig.xml"); if (m_CurrentTargetIndex < 1) { mitkThrow() << "Current target index has to be greater zero when freeze button is clicked."; } if (m_ReachedTargetsNodes.size() < m_CurrentTargetIndex) { mitk::DataNode::Pointer node = mitk::DataNode::New(); node->SetName( (QString("Target ") + QString("%1").arg(m_CurrentTargetIndex, 2, 10, QLatin1Char('0'))).toStdString()); this->GetDataStorage()->Add( node, this->GetNamedDerivedNodeAndCreate(USNavigationMarkerPlacement::DATANAME_REACHED_TARGETS, QmitkUSAbstractNavigationStep::DATANAME_BASENODE)); m_ReachedTargetsNodes.push_back(node); } m_PointMarkInteractor->SetDataNode(m_ReachedTargetsNodes.last()); } else { m_PointMarkInteractor->SetDataNode(0); this->GetCombinedModality()->SetIsFreezed(false); } } void QmitkUSNavigationStepMarkerIntervention::OnShowPlanningView(bool show) { m_ShowPlanningColors = show; } void QmitkUSNavigationStepMarkerIntervention::OnRiskZoneViolated(const mitk::DataNode *node, mitk::Point3D position) { MITK_INFO << "Risk zone (" << node->GetName() << ") violated at position " << position << "."; } void QmitkUSNavigationStepMarkerIntervention::ClearZones() { ui->riskStructuresRangeWidget->ClearZones(); // remove all reached target nodes from the data storage and clear the list mitk::DataStorage::Pointer dataStorage = this->GetDataStorage(); for (QVector::iterator it = m_ReachedTargetsNodes.begin(); it != m_ReachedTargetsNodes.end(); ++it) { if (it->IsNotNull()) { dataStorage->Remove(*it); } } m_ReachedTargetsNodes.clear(); } void QmitkUSNavigationStepMarkerIntervention::UpdateTargetCoordinates(mitk::DataNode *dataNode) { m_NodeDisplacementFilter->ResetNodes(); for (QVector>::iterator it = m_ReachedTargetsNodes.begin(); it != m_ReachedTargetsNodes.end(); ++it) { if (it->IsNotNull() && (*it)->GetData() != 0) { m_NodeDisplacementFilter->AddNode(*it); } } mitk::BaseData *baseData = dataNode->GetData(); if (!baseData) { mitkThrow() << "Data of the data node must not be null."; } mitk::BaseGeometry::Pointer geometry = baseData->GetGeometry(); if (geometry.IsNull()) { mitkThrow() << "Geometry of the data node must not be null."; } m_TargetUpdateFilter->SetControlNode(m_CurrentTargetIndex - 1, dataNode); if (m_PlannedTargetsNodes.size() > m_CurrentTargetIndex - 1) { m_PlannedTargetsNodes.at(m_CurrentTargetIndex - 1)->SetVisibility(false); } MITK_INFO("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepMarkerIntervention") << "Target " << m_CurrentTargetIndex << " reached at position " << geometry->GetOrigin(); this->CalculateTargetPlacementQuality(); } void QmitkUSNavigationStepMarkerIntervention::UpdateBodyMarkerStatus(mitk::NavigationData::Pointer bodyMarker) { if (bodyMarker.IsNull()) { MITK_ERROR("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepMarkerIntervention") << "Current Navigation Data for body marker of Combined Modality must not be null."; mitkThrow() << "Current Navigation Data for body marker of Combined Modality must not be null."; } bool valid = bodyMarker->IsDataValid(); // update body marker status label if (valid) { ui->bodyMarkerTrackingStatusLabel->setStyleSheet( "background-color: #8bff8b; margin-right: 1em; margin-left: 1em; border: 1px solid grey"); ui->bodyMarkerTrackingStatusLabel->setText("Body marker is inside the tracking volume."); } else { ui->bodyMarkerTrackingStatusLabel->setStyleSheet( "background-color: #ff7878; margin-right: 1em; margin-left: 1em; border: 1px solid grey"); ui->bodyMarkerTrackingStatusLabel->setText("Body marker is not inside the tracking volume."); } ui->targetStructuresRangeGroupBox->setEnabled(valid); ui->riskStructuresRangeGroupBox->setEnabled(valid); } void QmitkUSNavigationStepMarkerIntervention::GenerateTargetColorLookupTable() { vtkSmartPointer lookupTable = vtkSmartPointer::New(); lookupTable->SetHueRange(0.0, 0.33); lookupTable->SetSaturationRange(1.0, 1.0); lookupTable->SetValueRange(1.0, 1.0); lookupTable->SetTableRange(0.0, 1.0); lookupTable->Build(); mitk::LookupTable::Pointer lut = mitk::LookupTable::New(); lut->SetVtkLookupTable(lookupTable); m_TargetColorLookupTableProperty = mitk::LookupTableProperty::New(lut); } void QmitkUSNavigationStepMarkerIntervention::UpdateTargetColors() { if (m_TargetNode.IsNull()) { return; } m_TargetNode->SetColor(1, 1, 1); mitk::BaseData *targetNodeData = m_TargetNode->GetData(); if (targetNodeData == 0) { return; } mitk::Surface::Pointer targetNodeSurface = dynamic_cast(targetNodeData); vtkSmartPointer targetNodeSurfaceVtk = targetNodeSurface->GetVtkPolyData(); vtkPointData *targetPointData = targetNodeSurface->GetVtkPolyData()->GetPointData(); vtkFloatArray *scalars = dynamic_cast(targetPointData->GetScalars("USNavigation::Occlusion")); vtkFloatArray *targetScoreScalars; if (m_ShowPlanningColors) { targetScoreScalars = dynamic_cast(targetPointData->GetScalars("USNavigation::PlanningScalars")); } else { targetScoreScalars = dynamic_cast(targetPointData->GetScalars("USNavigation::ReachedTargetScores")); } if (!scalars || !targetScoreScalars) { return; } unsigned int numberOfTupels = scalars->GetNumberOfTuples(); vtkSmartPointer colors = vtkSmartPointer::New(); colors->SetNumberOfComponents(1); colors->SetNumberOfTuples(numberOfTupels); colors->SetName("Colors"); double color, intersection, markerScore; for (unsigned int n = 0; n < numberOfTupels; n++) { scalars->GetTuple(n, &intersection); targetScoreScalars->GetTuple(n, &markerScore); if (intersection > 0) { color = 0; } else { color = markerScore; } colors->SetTuple(n, &color); } if (numberOfTupels > 0) { targetNodeSurfaceVtk->GetPointData()->SetScalars(colors); targetNodeSurfaceVtk->GetPointData()->Update(); } } void QmitkUSNavigationStepMarkerIntervention::UpdateTargetScore() { if (m_NeedleProjectionFilter->GetProjection()->GetSize() != 2) { return; } vtkSmartPointer targetSurfaceVtk = m_TargetSurface->GetVtkPolyData(); m_TargetIntersectionFilter->SetTargetSurface(m_TargetSurface); m_TargetIntersectionFilter->SetLine(m_NeedleProjectionFilter->GetProjection()); m_TargetIntersectionFilter->CalculateIntersection(); if (m_TargetIntersectionFilter->GetIsIntersecting()) { vtkFloatArray *scalars = dynamic_cast(targetSurfaceVtk->GetPointData()->GetScalars("USNavigation::ReachedTargetScores")); double score; scalars->GetTuple(m_TargetIntersectionFilter->GetIntersectionNearestSurfacePointId(), &score); double color[3]; m_TargetColorLookupTableProperty->GetLookupTable()->GetVtkLookupTable()->GetColor(score, color); float colorF[3]; colorF[0] = color[0]; colorF[1] = color[1]; colorF[2] = color[2]; m_TargetProgressBar->SetColor(colorF); m_TargetProgressBar->SetBorderColor(colorF); m_TargetProgressBar->setValue(m_TargetIntersectionFilter->GetDistanceToIntersection()); if (m_PlannedTargetProgressBar) { vtkFloatArray *scalars = dynamic_cast(targetSurfaceVtk->GetPointData()->GetScalars("USNavigation::PlanningScalars")); if (scalars) { double score; scalars->GetTuple(m_TargetIntersectionFilter->GetIntersectionNearestSurfacePointId(), &score); double color[3]; m_TargetColorLookupTableProperty->GetLookupTable()->GetVtkLookupTable()->GetColor(score, color); float colorF[3]; colorF[0] = color[0]; colorF[1] = color[1]; colorF[2] = color[2]; m_PlannedTargetProgressBar->SetColor(colorF); m_PlannedTargetProgressBar->SetBorderColor(colorF); m_PlannedTargetProgressBar->SetTextFormatValid("Planned Target: %1 mm"); mitk::Point3D intersectionPoint = m_TargetIntersectionFilter->GetIntersectionPoint(); mitk::ScalarType minDistance = -1; for (QVector>::iterator it = m_PlannedTargetsNodes.begin(); it != m_PlannedTargetsNodes.end(); ++it) { mitk::ScalarType distance = intersectionPoint.EuclideanDistanceTo((*it)->GetData()->GetGeometry()->GetOrigin()); if (minDistance < 0 || distance < minDistance) { minDistance = distance; } } m_PlannedTargetProgressBar->setValue(minDistance); } } } else { m_TargetProgressBar->setValueInvalid(); } } void QmitkUSNavigationStepMarkerIntervention::UpdateTargetProgressDisplay() { QString description; if (m_CurrentTargetIndex >= static_cast(m_NumberOfTargets)) { description = "All Targets Reached"; if (m_TargetProgressBar) { m_TargetProgressBar->hide(); } } else { description = QString("Distance to Target ") + QString::number(m_CurrentTargetIndex + 1) + QString(" of ") + QString::number(m_NumberOfTargets); if (m_TargetProgressBar) { m_TargetProgressBar->show(); } } ui->targetStructuresRangeGroupBox->setTitle(description); } void QmitkUSNavigationStepMarkerIntervention::UpdatePlannedTargetProgressDisplay() { // make sure that the needle projection consists of two points if (m_NeedleProjectionFilter->GetProjection()->GetSize() != 2) { return; } vtkSmartPointer targetSurfaceVtk = m_TargetSurface->GetVtkPolyData(); m_TargetIntersectionFilter->SetTargetSurface(m_TargetSurface); m_TargetIntersectionFilter->SetLine(m_NeedleProjectionFilter->GetProjection()); m_TargetIntersectionFilter->CalculateIntersection(); // update target progress bar according to the color of the intersection // point on the target surface and the distance to the intersection if (m_TargetIntersectionFilter->GetIsIntersecting()) { vtkFloatArray *scalars = dynamic_cast(targetSurfaceVtk->GetPointData()->GetScalars("Colors")); double score; scalars->GetTuple(m_TargetIntersectionFilter->GetIntersectionNearestSurfacePointId(), &score); double color[3]; m_TargetColorLookupTableProperty->GetLookupTable()->GetVtkLookupTable()->GetColor(score, color); float colorF[3]; colorF[0] = color[0]; colorF[1] = color[1]; colorF[2] = color[2]; m_TargetProgressBar->SetColor(colorF); m_TargetProgressBar->SetBorderColor(colorF); m_TargetProgressBar->setValue(m_TargetIntersectionFilter->GetDistanceToIntersection()); } else { - float red[3] = {0.6, 0, 0}; + float red[3] = {0.6f, 0.0f, 0.0f}; m_TargetProgressBar->SetBorderColor(red); m_TargetProgressBar->setValueInvalid(); } } void QmitkUSNavigationStepMarkerIntervention::UpdateTargetViolationStatus() { // transform vtk polydata according to mitk geometry vtkSmartPointer transformFilter = vtkSmartPointer::New(); transformFilter->SetInputData(0, m_TargetSurface->GetVtkPolyData()); transformFilter->SetTransform(m_TargetSurface->GetGeometry()->GetVtkTransform()); transformFilter->Update(); vtkSmartPointer enclosedPoints = vtkSmartPointer::New(); enclosedPoints->Initialize(transformFilter->GetOutput()); mitk::Point3D needleTip = m_NeedleProjectionFilter->GetProjection()->GetPoint(0); // show warning if the needle tip is inside the target surface if (enclosedPoints->IsInsideSurface(needleTip[0], needleTip[1], needleTip[2])) { if (!m_TargetStructureWarnOverlay->IsVisible(NULL)) { m_TargetStructureWarnOverlay->SetVisibility(true); mitk::DataNode::Pointer targetViolationResult = mitk::DataNode::New(); targetViolationResult->SetName("TargetViolation"); targetViolationResult->SetProperty("USNavigation::TargetViolationPoint", mitk::Point3dProperty::New(needleTip)); emit SignalIntermediateResult(targetViolationResult); } MITK_INFO("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepMarkerIntervention") << "Target surface violated at " << needleTip << "."; } else { m_TargetStructureWarnOverlay->SetVisibility(false); } } void QmitkUSNavigationStepMarkerIntervention::CalculateTargetPlacementQuality() { // clear quality display if there aren't all targets reached if (m_ReachedTargetsNodes.size() != static_cast(m_NumberOfTargets)) { ui->placementQualityGroupBox->setEnabled(false); ui->angleDifferenceValue->setText(""); ui->centersOfMassValue->setText(""); return; } ui->placementQualityGroupBox->setEnabled(true); mitk::Surface::Pointer targetSurface = dynamic_cast(m_TargetNode->GetData()); if (targetSurface.IsNull()) { mitkThrow() << "Target surface must not be null."; } m_PlacementQualityCalculator->SetTargetSurface(targetSurface); mitk::PointSet::Pointer targetPointSet = mitk::PointSet::New(); // copy the origins of all reached target nodes into a point set // for the quality calculator mitk::PointSet::PointIdentifier n = 0; for (QVector>::iterator it = m_ReachedTargetsNodes.begin(); it != m_ReachedTargetsNodes.end(); ++it) { targetPointSet->InsertPoint(n++, (*it)->GetData()->GetGeometry()->GetOrigin()); } m_PlacementQualityCalculator->SetTargetPoints(targetPointSet); m_PlacementQualityCalculator->Update(); double centersOfMassDistance = m_PlacementQualityCalculator->GetCentersOfMassDistance(); ui->centersOfMassValue->setText(QString::number(centersOfMassDistance, 103, 2) + " mm"); double meanAnglesDifference = m_PlacementQualityCalculator->GetMeanAngleDifference(); ui->angleDifferenceValue->setText(QString::number(meanAnglesDifference, 103, 2) + QString::fromLatin1(" °")); // create an intermediate result of the placement quality mitk::DataNode::Pointer placementQualityResult = mitk::DataNode::New(); placementQualityResult->SetName("PlacementQuality"); placementQualityResult->SetFloatProperty("USNavigation::CentersOfMassDistance", centersOfMassDistance); placementQualityResult->SetFloatProperty("USNavigation::MeanAngleDifference", meanAnglesDifference); placementQualityResult->SetProperty( "USNavigation::AngleDifferences", mitk::GenericProperty::New(m_PlacementQualityCalculator->GetAngleDifferences())); if (m_PlannedTargetsNodes.size() == static_cast(m_NumberOfTargets)) { mitk::VnlVector reachedPlannedDifferences; double reachedPlannedDifferencesSum = 0; double reachedPlannedDifferencesMax = 0; reachedPlannedDifferences.set_size(m_NumberOfTargets); // get sum and maximum of the planning / reality differences for (unsigned int n = 0; n < m_NumberOfTargets; ++n) { mitk::ScalarType distance = m_PlannedTargetsNodes.at(n)->GetData()->GetGeometry()->GetOrigin().EuclideanDistanceTo( m_ReachedTargetsNodes.at(n)->GetData()->GetGeometry()->GetOrigin()); reachedPlannedDifferences.put(n, distance); reachedPlannedDifferencesSum += distance; if (distance > reachedPlannedDifferencesMax) { reachedPlannedDifferencesMax = distance; } } // add distances between planning and reality to the quality intermediate result placementQualityResult->SetProperty("USNavigation::PlanningRealityDistances", mitk::GenericProperty::New(reachedPlannedDifferences)); placementQualityResult->SetProperty( "USNavigation::MeanPlanningRealityDistance", mitk::DoubleProperty::New(reachedPlannedDifferencesSum / static_cast(m_NumberOfTargets))); placementQualityResult->SetProperty("USNavigation::MaximumPlanningRealityDistance", mitk::DoubleProperty::New(reachedPlannedDifferencesMax)); } emit SignalIntermediateResult(placementQualityResult); } void QmitkUSNavigationStepMarkerIntervention::UpdateSensorsNames() { mitk::USCombinedModality::Pointer combinedModality = this->GetCombinedModality(false); if (combinedModality.IsNull()) { return; } mitk::NavigationDataSource::Pointer navigationDataSource = combinedModality->GetNavigationDataSource(); if (navigationDataSource.IsNull()) { return; } if (!m_NeedleSensorName.empty()) { try { m_NeedleSensorIndex = navigationDataSource->GetOutputIndex(m_NeedleSensorName); } catch (const std::exception &e) { MITK_WARN("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepPlacementPlanning") << "Cannot get index for needle sensor name: " << e.what(); } } if (this->GetNavigationStepState() >= QmitkUSAbstractNavigationStep::State_Active) { m_NeedleProjectionFilter->SelectInput(m_NeedleSensorIndex); } if (!m_ReferenceSensorName.empty()) { try { m_ReferenceSensorIndex = navigationDataSource->GetOutputIndex(m_ReferenceSensorName); } catch (const std::exception &e) { MITK_WARN("QmitkUSAbstractNavigationStep") ("QmitkUSNavigationStepPlacementPlanning") << "Cannot get index for reference sensor name: " << e.what(); } } if (this->GetNavigationStepState() >= QmitkUSAbstractNavigationStep::State_Active) { m_NodeDisplacementFilter->SelectInput(m_ReferenceSensorIndex); } ui->freezeImageButton->SetCombinedModality(combinedModality, m_ReferenceSensorIndex); } diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp index f4ec9a943c..0ed3e54de0 100644 --- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp +++ b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.cpp @@ -1,249 +1,244 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkMITKSurfaceMaterialEditorView.h" #include "mitkBaseRenderer.h" #include "mitkNodePredicateDataType.h" #include "mitkProperties.h" #include "mitkIDataStorageService.h" #include "mitkDataNodeObject.h" #include "berryIEditorPart.h" #include "berryIWorkbenchPage.h" -#include "mitkShaderProperty.h" - #include "QmitkDataStorageComboBox.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include "mitkStandaloneDataStorage.h" const std::string QmitkMITKSurfaceMaterialEditorView::VIEW_ID = "org.mitk.views.mitksurfacematerialeditor"; QmitkMITKSurfaceMaterialEditorView::QmitkMITKSurfaceMaterialEditorView() : QmitkAbstractView(), m_Controls(nullptr) { fixedProperties.push_back( "shader" ); fixedProperties.push_back( "material.representation" ); fixedProperties.push_back( "color" ); fixedProperties.push_back( "opacity" ); fixedProperties.push_back( "material.wireframeLineWidth" ); fixedProperties.push_back( "material.ambientCoefficient" ); fixedProperties.push_back( "material.diffuseCoefficient" ); fixedProperties.push_back( "material.ambientColor" ); fixedProperties.push_back( "material.diffuseColor" ); fixedProperties.push_back( "material.specularColor" ); fixedProperties.push_back( "material.specularCoefficient" ); fixedProperties.push_back( "material.specularPower" ); fixedProperties.push_back( "material.interpolation" ); shaderProperties.push_back( "shader" ); shaderProperties.push_back( "material.representation" ); shaderProperties.push_back( "color" ); shaderProperties.push_back( "opacity" ); shaderProperties.push_back( "material.wireframeLineWidth" ); observerAllocated = false; } QmitkMITKSurfaceMaterialEditorView::~QmitkMITKSurfaceMaterialEditorView() { } void QmitkMITKSurfaceMaterialEditorView::InitPreviewWindow() { usedTimer=0; vtkSphereSource* sphereSource = vtkSphereSource::New(); sphereSource->SetThetaResolution(25); sphereSource->SetPhiResolution(25); sphereSource->Update(); vtkPolyData* sphere = sphereSource->GetOutput(); m_Surface = mitk::Surface::New(); m_Surface->SetVtkPolyData( sphere ); m_DataNode = mitk::DataNode::New(); m_DataNode->SetData( m_Surface ); m_DataTree = mitk::StandaloneDataStorage::New(); m_DataTree->Add( m_DataNode , (mitk::DataNode *)0 ); m_Controls->m_PreviewRenderWindow->GetRenderer()->SetDataStorage( m_DataTree ); m_Controls->m_PreviewRenderWindow->GetRenderer()->SetMapperID( mitk::BaseRenderer::Standard3D ); sphereSource->Delete(); } void QmitkMITKSurfaceMaterialEditorView::RefreshPropertiesList() { mitk::DataNode* SrcND = m_SelectedDataNode; mitk::DataNode* DstND = m_DataNode; mitk::PropertyList* DstPL = DstND->GetPropertyList(); m_Controls->m_ShaderPropertyList->SetPropertyList( 0 ); DstPL->Clear(); if(observerAllocated) { - observedProperty->RemoveObserver( observerIndex ); observerAllocated=false; } if(SrcND) { mitk::PropertyList* SrcPL = SrcND->GetPropertyList(); - mitk::ShaderProperty::Pointer shaderEnum = dynamic_cast(SrcPL->GetProperty("shader")); - std::string shaderState = "fixed"; - if(shaderEnum.IsNotNull()) - { - shaderState = shaderEnum->GetValueAsString(); +// if(shaderEnum.IsNotNull()) +// { +// shaderState = shaderEnum->GetValueAsString(); - itk::MemberCommand::Pointer propertyModifiedCommand = itk::MemberCommand::New(); - propertyModifiedCommand->SetCallbackFunction(this, &QmitkMITKSurfaceMaterialEditorView::shaderEnumChange); - observerIndex = shaderEnum->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand); - observedProperty = shaderEnum; - observerAllocated=true; - } +// itk::MemberCommand::Pointer propertyModifiedCommand = itk::MemberCommand::New(); +// propertyModifiedCommand->SetCallbackFunction(this, &QmitkMITKSurfaceMaterialEditorView::shaderEnumChange); +// observerIndex = shaderEnum->AddObserver(itk::ModifiedEvent(), propertyModifiedCommand); +// observedProperty = shaderEnum; +// observerAllocated=true; +// } MITK_INFO << "PROPERTIES SCAN BEGIN"; for(mitk::PropertyList::PropertyMap::const_iterator it=SrcPL->GetMap()->begin(); it!=SrcPL->GetMap()->end(); it++) { std::string name=it->first; mitk::BaseProperty *p=it->second; // MITK_INFO << "property '" << name << "' found"; if(shaderState.compare("fixed")==0) { if(std::find(fixedProperties.begin(), fixedProperties.end(), name) != fixedProperties.end()) { DstPL->SetProperty(name,p); } } else { //if(std::find(shaderProperties.begin(), shaderProperties.end(), name) != shaderProperties.end()) { DstPL->SetProperty(name,p); } } } MITK_INFO << "PROPERTIES SCAN END"; } m_Controls->m_ShaderPropertyList->SetPropertyList( DstPL ); //m_Controls->m_PreviewRenderWindow->GetRenderer()->GetVtkRenderer()->ResetCameraClippingRange(); } void QmitkMITKSurfaceMaterialEditorView::CreateQtPartControl(QWidget *parent) { if (!m_Controls) { // create GUI widgets m_Controls = new Ui::QmitkMITKSurfaceMaterialEditorViewControls; m_Controls->setupUi(parent); this->CreateConnections(); InitPreviewWindow(); RefreshPropertiesList(); } } void QmitkMITKSurfaceMaterialEditorView::SetFocus() { m_Controls->m_ShaderPropertyList->setFocus(); } void QmitkMITKSurfaceMaterialEditorView::CreateConnections() { } void QmitkMITKSurfaceMaterialEditorView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList& nodes) { if(!nodes.empty()) { m_SelectedDataNode = nodes.at(0); MITK_INFO << "Node '" << m_SelectedDataNode->GetName() << "' selected"; SurfaceSelected(); } } void QmitkMITKSurfaceMaterialEditorView::SurfaceSelected() { postRefresh(); } void QmitkMITKSurfaceMaterialEditorView::shaderEnumChange(const itk::Object * /*caller*/, const itk::EventObject & /*event*/) { postRefresh(); } void QmitkMITKSurfaceMaterialEditorView::postRefresh() { if(usedTimer) return; usedTimer=startTimer(0); } void QmitkMITKSurfaceMaterialEditorView::timerEvent( QTimerEvent *e ) { if(usedTimer!=e->timerId()) { MITK_ERROR << "INTERNAL ERROR: usedTimer[" << usedTimer << "] != timerId[" << e->timerId() << "]"; } if(usedTimer) { killTimer(usedTimer); usedTimer=0; } RefreshPropertiesList(); } diff --git a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h index d3e5a42d92..4df318e7b6 100644 --- a/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h +++ b/Plugins/org.mitk.gui.qt.materialeditor/src/internal/QmitkMITKSurfaceMaterialEditorView.h @@ -1,115 +1,113 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef _QMITKMITKSURFACEMATERIALEDITORVIEW_H_INCLUDED #define _QMITKMITKSURFACEMATERIALEDITORVIEW_H_INCLUDED #include #include #include #include "ui_QmitkMITKSurfaceMaterialEditorViewControls.h" /* #include #include #include #include #include #include #include "QtGui/QMenubarUpdatedEvent" */ #include "QmitkRenderWindow.h" #include "mitkCommon.h" #include "mitkDataStorage.h" #include "mitkDataNode.h" -#include "mitkShaderProperty.h" #include "mitkSurface.h" #include "vtkRenderer.h" #include "vtkTextActor.h" /*! \brief QmitkMITKSurfaceMaterialEditorView */ class QmitkMITKSurfaceMaterialEditorView : public QmitkAbstractView { // this is needed for all Qt objects that should have a MOC object (everything that derives from QObject) Q_OBJECT public: static const std::string VIEW_ID; QmitkMITKSurfaceMaterialEditorView(); virtual ~QmitkMITKSurfaceMaterialEditorView(); virtual void CreateQtPartControl(QWidget *parent) override; /// \brief Creation of the connections of main and control widget virtual void CreateConnections(); /// /// Sets the focus to an internal widget. /// virtual void SetFocus() override; virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer part, const QList& nodes) override; protected slots: void SurfaceSelected(); protected: Ui::QmitkMITKSurfaceMaterialEditorViewControls* m_Controls; private: mitk::Surface::Pointer m_Surface; mitk::DataStorage::Pointer m_DataTree; mitk::DataNode::Pointer m_DataNode; mitk::DataNode::Pointer m_SelectedDataNode; std::list fixedProperties; std::list shaderProperties; unsigned long observerIndex; bool observerAllocated; - mitk::ShaderProperty::Pointer observedProperty; void InitPreviewWindow(); int usedTimer; void timerEvent( QTimerEvent *e ) override; void RefreshPropertiesList(); void postRefresh(); void shaderEnumChange(const itk::Object *caller, const itk::EventObject &event); berry::IStructuredSelection::ConstPointer m_CurrentSelection; }; #endif // _QMITKMITKSURFACEMATERIALEDITORVIEW_H_INCLUDED diff --git a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp index 7264029b09..93272eced5 100644 --- a/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp +++ b/Plugins/org.mitk.gui.qt.measurementtoolbox/src/internal/QmitkImageStatisticsView.cpp @@ -1,1333 +1,1333 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkImageStatisticsView.h" // Qt includes #include #include #include // berry includes #include // mitk includes #include "mitkNodePredicateDataType.h" #include "mitkNodePredicateOr.h" #include "mitkPlanarFigureInteractor.h" #include "mitkImageTimeSelector.h" #include #include // itk includes #include "itksys/SystemTools.hxx" #include #include "itkImageRegionConstIteratorWithIndex.h" #include //blueberry includes #include #include const std::string QmitkImageStatisticsView::VIEW_ID = "org.mitk.views.imagestatistics"; const int QmitkImageStatisticsView::STAT_TABLE_BASE_HEIGHT = 180; QmitkImageStatisticsView::QmitkImageStatisticsView(QObject* /*parent*/, const char* /*name*/) : m_Controls( nullptr ), m_TimeStepperAdapter( nullptr ), m_SelectedImage( nullptr ), m_SelectedImageMask( nullptr ), m_SelectedPlanarFigure( nullptr ), m_ImageObserverTag( -1 ), m_ImageMaskObserverTag( -1 ), m_PlanarFigureObserverTag( -1 ), m_TimeObserverTag( -1 ), m_CurrentStatisticsValid( false ), m_StatisticsUpdatePending( false ), m_DataNodeSelectionChanged ( false ), m_Visible(false) { this->m_CalculationThread = new QmitkImageStatisticsCalculationThread; } QmitkImageStatisticsView::~QmitkImageStatisticsView() { if ( m_SelectedImage != nullptr ) m_SelectedImage->RemoveObserver( m_ImageObserverTag ); if ( m_SelectedImageMask != nullptr ) m_SelectedImageMask->RemoveObserver( m_ImageMaskObserverTag ); if ( m_SelectedPlanarFigure != nullptr ) m_SelectedPlanarFigure->RemoveObserver( m_PlanarFigureObserverTag ); while(this->m_CalculationThread->isRunning()) // wait until thread has finished { itksys::SystemTools::Delay(100); } delete this->m_CalculationThread; } void QmitkImageStatisticsView::CreateQtPartControl(QWidget *parent) { if (m_Controls == nullptr) { m_Controls = new Ui::QmitkImageStatisticsViewControls; m_Controls->setupUi(parent); CreateConnections(); m_Controls->m_ErrorMessageLabel->hide(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex(0); m_Controls->m_BinSizeFrame->setEnabled(false); } } void QmitkImageStatisticsView::OnPageSuccessfullyLoaded() { berry::IPreferencesService* prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); m_StylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); QString styleName = m_StylePref->Get(berry::QtPreferences::QT_STYLE_NAME, ""); if (styleName == ":/org.blueberry.ui.qt/darkstyle.qss") { this->m_Controls->m_JSHistogram->SetTheme(QmitkChartWidget::ChartStyle::darkstyle); } else { this->m_Controls->m_JSHistogram->SetTheme(QmitkChartWidget::ChartStyle::defaultstyle); } } void QmitkImageStatisticsView::CreateConnections() { if ( m_Controls ) { connect( (QObject*)(this->m_Controls->m_ButtonCopyHistogramToClipboard), SIGNAL(clicked()),(QObject*) this, SLOT(OnClipboardHistogramButtonClicked()) ); connect( (QObject*)(this->m_Controls->m_ButtonCopyStatisticsToClipboard), SIGNAL(clicked()),(QObject*) this, SLOT(OnClipboardStatisticsButtonClicked()) ); connect( (QObject*)(this->m_Controls->m_IgnoreZerosCheckbox), SIGNAL(clicked()),(QObject*) this, SLOT(OnIgnoreZerosCheckboxClicked()) ); connect( (QObject*) this->m_CalculationThread, SIGNAL(finished()),this, SLOT( OnThreadedStatisticsCalculationEnds()),Qt::QueuedConnection); connect( (QObject*) this, SIGNAL(StatisticsUpdate()),this, SLOT( RequestStatisticsUpdate()), Qt::QueuedConnection); connect( (QObject*) this->m_Controls->m_StatisticsTable, SIGNAL(cellDoubleClicked(int,int)),this, SLOT( JumpToCoordinates(int,int)) ); connect((QObject*)(this->m_Controls->m_barRadioButton), SIGNAL(clicked()), (QObject*)(this), SLOT(OnBarRadioButtonSelected())); connect((QObject*)(this->m_Controls->m_lineRadioButton), SIGNAL(clicked()), (QObject*)(this), SLOT(OnLineRadioButtonSelected())); connect( (QObject*) (this->m_Controls->m_HistogramBinSizeSpinbox), SIGNAL(editingFinished()), this, SLOT(OnHistogramBinSizeBoxValueChanged())); connect((QObject*)(this->m_Controls->m_UseDefaultBinSizeBox), SIGNAL(clicked()), (QObject*) this, SLOT(OnDefaultBinSizeBoxChanged())); connect((QObject*)(this->m_Controls->m_ShowSubchartCheckBox), SIGNAL(clicked()), (QObject*) this, SLOT(OnShowSubchartBoxChanged())); connect((QObject*)(this->m_Controls->m_JSHistogram), SIGNAL(PageSuccessfullyLoaded()), (QObject*) this, SLOT(OnPageSuccessfullyLoaded())); } } void QmitkImageStatisticsView::OnDefaultBinSizeBoxChanged() { m_Controls->m_BinSizeFrame->setEnabled(!m_Controls->m_UseDefaultBinSizeBox->isChecked()); if (m_CalculationThread != nullptr){ m_Controls->m_HistogramBinSizeSpinbox->setValue(m_CalculationThread->GetHistogramBinSize()); m_CalculationThread->SetUseDefaultNBins(m_Controls->m_UseDefaultBinSizeBox->isChecked()); } this->UpdateStatistics(); } void QmitkImageStatisticsView::OnShowSubchartBoxChanged() { bool showSubchart = this->m_Controls->m_ShowSubchartCheckBox->isChecked(); this->m_Controls->m_JSHistogram->Reload(showSubchart); } void QmitkImageStatisticsView::OnBarRadioButtonSelected() { this->m_Controls->m_JSHistogram->SetChartTypeAndReload(QmitkChartWidget::ChartType::bar); } void QmitkImageStatisticsView::OnLineRadioButtonSelected() { this->m_Controls->m_JSHistogram->SetChartTypeAndReload(QmitkChartWidget::ChartType::line); } void QmitkImageStatisticsView::PartClosed(const berry::IWorkbenchPartReference::Pointer& ) { } void QmitkImageStatisticsView::OnTimeChanged(const itk::EventObject& e) { if (this->m_SelectedDataNodes.isEmpty() || this->m_SelectedImage == nullptr) return; const mitk::SliceNavigationController::GeometryTimeEvent* timeEvent = dynamic_cast(&e); assert(timeEvent != nullptr); int timestep = timeEvent->GetPos(); if (this->m_SelectedImage->GetTimeSteps() > 1) { for (int x = 0; x < this->m_Controls->m_StatisticsTable->columnCount(); x++) { for (int y = 0; y < this->m_Controls->m_StatisticsTable->rowCount(); y++) { QTableWidgetItem* item = this->m_Controls->m_StatisticsTable->item(y, x); if (item == nullptr) break; if (x == timestep) { item->setBackgroundColor(Qt::yellow); } else { if (y % 2 == 0) item->setBackground(this->m_Controls->m_StatisticsTable->palette().base()); else item->setBackground(this->m_Controls->m_StatisticsTable->palette().alternateBase()); } } } this->m_Controls->m_StatisticsTable->viewport()->update(); } if ((this->m_SelectedImage->GetTimeSteps() == 1 && timestep == 0) || this->m_SelectedImage->GetTimeSteps() > 1) { // display histogram for selected timestep this->m_Controls->m_JSHistogram->Clear(); QmitkImageStatisticsCalculationThread::HistogramType::ConstPointer histogram = (QmitkImageStatisticsCalculationThread::HistogramType::ConstPointer)this->m_CalculationThread->GetTimeStepHistogram(timestep); if (histogram.IsNotNull()) { bool closedFigure = this->m_CalculationThread->GetStatisticsUpdateSuccessFlag(); if ( closedFigure ) { this->m_Controls->m_JSHistogram->AddData2D(ConvertHistogramToMap(histogram) ); if (this->m_Controls->m_lineRadioButton->isChecked()) { this->m_Controls->m_JSHistogram->SetChartType(QmitkChartWidget::ChartType::line); } else { this->m_Controls->m_JSHistogram->SetChartType(QmitkChartWidget::ChartType::bar); } this->m_Controls->m_JSHistogram->SetDataLabels({ m_Controls->m_SelectedFeatureImageLabel->text().toStdString() }); this->m_Controls->m_JSHistogram->SetXAxisLabel("Grey value"); this->m_Controls->m_JSHistogram->SetYAxisLabel("Frequency"); this->m_Controls->m_JSHistogram->Show(this->m_Controls->m_ShowSubchartCheckBox->isChecked()); } } } } void QmitkImageStatisticsView::JumpToCoordinates(int row ,int col) { if(m_SelectedDataNodes.isEmpty()) { MITK_WARN("QmitkImageStatisticsView") << "No data node selected for statistics calculation." ; return; } mitk::Point3D world; if (row==5 && !m_WorldMinList.empty()) world = m_WorldMinList[col]; else if (row==4 && !m_WorldMaxList.empty()) world = m_WorldMaxList[col]; else return; mitk::IRenderWindowPart* part = this->GetRenderWindowPart(); if (part) { part->GetQmitkRenderWindow("axial")->GetSliceNavigationController()->SelectSliceByPoint(world); part->GetQmitkRenderWindow("sagittal")->GetSliceNavigationController()->SelectSliceByPoint(world); part->GetQmitkRenderWindow("coronal")->GetSliceNavigationController()->SelectSliceByPoint(world); mitk::SliceNavigationController::GeometryTimeEvent timeEvent(this->m_SelectedImage->GetTimeGeometry(), col); part->GetQmitkRenderWindow("axial")->GetSliceNavigationController()->SetGeometryTime(timeEvent); } } void QmitkImageStatisticsView::OnIgnoreZerosCheckboxClicked() { emit StatisticsUpdate(); } void QmitkImageStatisticsView::OnClipboardHistogramButtonClicked() { if ( m_CurrentStatisticsValid && !( m_SelectedPlanarFigure != nullptr)) { const unsigned int t = this->GetRenderWindowPart()->GetTimeNavigationController()->GetTime()->GetPos(); typedef mitk::ImageStatisticsCalculator::HistogramType HistogramType; const HistogramType *histogram = this->m_CalculationThread->GetTimeStepHistogram(t).GetPointer(); QString clipboard( "Measurement \t Frequency\n" ); for ( HistogramType::ConstIterator it = histogram->Begin(); it != histogram->End(); ++it ) { if( m_Controls->m_HistogramBinSizeSpinbox->value() == 1.0) { clipboard = clipboard.append( "%L1 \t %L2\n" ) .arg( it.GetMeasurementVector()[0], 0, 'f', 0 ) .arg( it.GetFrequency() ); } else { clipboard = clipboard.append( "%L1 \t %L2\n" ) .arg( it.GetMeasurementVector()[0], 0, 'f', 2 ) .arg( it.GetFrequency() ); } } QApplication::clipboard()->setText( clipboard, QClipboard::Clipboard ); } // If a (non-closed) PlanarFigure is selected, display a line profile widget else if ( m_CurrentStatisticsValid && (m_SelectedPlanarFigure != nullptr )) { /*auto intensity = m_Controls->m_JSHistogram->GetFrequency(); auto pixel = m_Controls->m_JSHistogram->GetMeasurement(); QString clipboard( "Pixel \t Intensity\n" ); auto j = pixel.begin(); for (auto i = intensity.begin(); i < intensity.end(); i++) { assert(j != pixel.end()); clipboard = clipboard.append( "%L1 \t %L2\n" ) .arg( (*j).toString()) .arg( (*i).toString()); j++; } QApplication::clipboard()->setText( clipboard, QClipboard::Clipboard ); */ } else { QApplication::clipboard()->clear(); } } void QmitkImageStatisticsView::OnClipboardStatisticsButtonClicked() { QLocale tempLocal; QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates)); if ( m_CurrentStatisticsValid && !( m_SelectedPlanarFigure != nullptr)) { const std::vector &statistics = this->m_CalculationThread->GetStatisticsData(); // Set time borders for for loop ;) unsigned int startT, endT; if(this->m_Controls->m_CheckBox4dCompleteTable->checkState()==Qt::CheckState::Unchecked) { startT = this->GetRenderWindowPart()->GetTimeNavigationController()->GetTime()-> GetPos(); endT = startT+1; } else { startT = 0; endT = statistics.size(); } QVector< QVector > statisticsTable; QStringList headline; // Create Headline headline << " " << "Mean" << "Median" << "StdDev" << "RMS" << "Max" << "Min" << "NumberOfVoxels" << "Skewness" << "Kurtosis" << "Uniformity" << "Entropy" << "MPP" << "UPP" << "V [mm³]"; for(int i=0;i row; row.append(headline.at(i)); statisticsTable.append(row); } // Fill Table for(unsigned int t=startT;tGetMean()) << QString::number(statistics[t]->GetMedian()) << QString::number(statistics[t]->GetStd()) << QString::number(statistics[t]->GetRMS()) << QString::number(statistics[t]->GetMax()) << QString::number(statistics[t]->GetMin()) << QString::number(statistics[t]->GetN()) << QString::number(statistics[t]->GetSkewness()) << QString::number(statistics[t]->GetKurtosis()) << QString::number(statistics[t]->GetUniformity()) << QString::number(statistics[t]->GetEntropy()) << QString::number(statistics[t]->GetMPP()) << QString::number(statistics[t]->GetUPP()) << QString::number(m_Controls->m_StatisticsTable->item(7, 0)->data(Qt::DisplayRole).toDouble()); for(int z=0;zsetText(clipboard, QClipboard::Clipboard); } else { QApplication::clipboard()->clear(); } QLocale::setDefault(tempLocal); } void QmitkImageStatisticsView::OnSelectionChanged( berry::IWorkbenchPart::Pointer /*part*/, const QList &nodes ) { if (this->m_Visible) { this->SelectionChanged( nodes ); } else { this->m_DataNodeSelectionChanged = true; } } void QmitkImageStatisticsView::SelectionChanged(const QList &selectedNodes) { //Clear Histogram if data node is deselected m_Controls->m_JSHistogram->Clear(); if( this->m_StatisticsUpdatePending ) { this->m_DataNodeSelectionChanged = true; return; // not ready for new data now! } if (selectedNodes.size() == this->m_SelectedDataNodes.size()) { int i = 0; for (; i < selectedNodes.size(); ++i) { if (selectedNodes.at(i) != this->m_SelectedDataNodes.at(i)) { break; } } // node selection did not change if (i == selectedNodes.size()) return; } //reset the feature image and image mask field m_Controls->m_SelectedFeatureImageLabel->setText("None"); m_Controls->m_SelectedMaskLabel->setText("None"); this->ReinitData(); if (selectedNodes.isEmpty()) { m_Controls->m_lineRadioButton->setEnabled(true); m_Controls->m_barRadioButton->setEnabled(true); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(true); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(true); m_Controls->m_UseDefaultBinSizeBox->setEnabled(true); m_Controls->m_InfoLabel->setText(""); m_Controls->groupBox->setEnabled(false); m_Controls->groupBox_3->setEnabled(false); } else { m_Controls->groupBox->setEnabled(true); m_Controls->groupBox_3->setEnabled(true); m_Controls->m_barRadioButton->setChecked(true); } if(selectedNodes.size() == 1 || selectedNodes.size() == 2) { bool isBinary = false; selectedNodes.value(0)->GetBoolProperty("binary",isBinary); mitk::NodePredicateDataType::Pointer isLabelSet = mitk::NodePredicateDataType::New("LabelSetImage"); isBinary |= isLabelSet->CheckNode(selectedNodes.value(0)); if(isBinary) { m_Controls->m_lineRadioButton->setEnabled(true); m_Controls->m_barRadioButton->setEnabled(true); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(true); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(true); m_Controls->m_UseDefaultBinSizeBox->setEnabled(true); m_Controls->m_InfoLabel->setText(""); } for (int i= 0; i< selectedNodes.size(); ++i) { this->m_SelectedDataNodes.push_back(selectedNodes.at(i)); } this->m_DataNodeSelectionChanged = false; this->m_Controls->m_ErrorMessageLabel->setText( "" ); this->m_Controls->m_ErrorMessageLabel->hide(); emit StatisticsUpdate(); } else { this->m_DataNodeSelectionChanged = false; } } void QmitkImageStatisticsView::ReinitData() { while( this->m_CalculationThread->isRunning()) // wait until thread has finished { itksys::SystemTools::Delay(100); } if(this->m_SelectedImage != nullptr) { this->m_SelectedImage->RemoveObserver( this->m_ImageObserverTag); this->m_SelectedImage = nullptr; } if(this->m_SelectedImageMask != nullptr) { this->m_SelectedImageMask->RemoveObserver( this->m_ImageMaskObserverTag); this->m_SelectedImageMask = nullptr; } if(this->m_SelectedPlanarFigure != nullptr) { this->m_SelectedPlanarFigure->RemoveObserver( this->m_PlanarFigureObserverTag); this->m_SelectedPlanarFigure = nullptr; } this->m_SelectedDataNodes.clear(); this->m_StatisticsUpdatePending = false; m_Controls->m_ErrorMessageLabel->setText( "" ); m_Controls->m_ErrorMessageLabel->hide(); this->InvalidateStatisticsTableView(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); } void QmitkImageStatisticsView::OnThreadedStatisticsCalculationEnds() { std::stringstream message; message << ""; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->hide(); this->WriteStatisticsToGUI(); } void QmitkImageStatisticsView::UpdateStatistics() { mitk::IRenderWindowPart* renderPart = this->GetRenderWindowPart(); if ( renderPart == nullptr ) { this->m_StatisticsUpdatePending = false; return; } m_WorldMinList.clear(); m_WorldMaxList.clear(); // classify selected nodes mitk::NodePredicateDataType::Pointer isImage = mitk::NodePredicateDataType::New("Image"); mitk::NodePredicateDataType::Pointer isLabelSet = mitk::NodePredicateDataType::New("LabelSetImage"); mitk::NodePredicateOr::Pointer imagePredicate = mitk::NodePredicateOr::New(isImage, isLabelSet); std::string maskName; std::string maskType; std::string featureImageName; unsigned int maskDimension = 0; // reset data from last run ITKCommandType::Pointer changeListener = ITKCommandType::New(); changeListener->SetCallbackFunction( this, &QmitkImageStatisticsView::SelectedDataModified ); mitk::DataNode::Pointer planarFigureNode; for( int i= 0 ; i < this->m_SelectedDataNodes.size(); ++i) { mitk::PlanarFigure::Pointer planarFig = dynamic_cast(this->m_SelectedDataNodes.at(i)->GetData()); if( imagePredicate->CheckNode(this->m_SelectedDataNodes.at(i)) ) { bool isMask = false; this->m_SelectedDataNodes.at(i)->GetPropertyValue("binary", isMask); isMask |= isLabelSet->CheckNode(this->m_SelectedDataNodes.at(i)); if( this->m_SelectedImageMask == nullptr && isMask) { this->m_SelectedImageMask = dynamic_cast(this->m_SelectedDataNodes.at(i)->GetData()); this->m_ImageMaskObserverTag = this->m_SelectedImageMask->AddObserver(itk::ModifiedEvent(), changeListener); maskName = this->m_SelectedDataNodes.at(i)->GetName(); maskType = m_SelectedImageMask->GetNameOfClass(); maskDimension = 3; } else if( !isMask ) { if(this->m_SelectedImage == nullptr) { this->m_SelectedImage = static_cast(this->m_SelectedDataNodes.at(i)->GetData()); this->m_ImageObserverTag = this->m_SelectedImage->AddObserver(itk::ModifiedEvent(), changeListener); } featureImageName = this->m_SelectedDataNodes.at(i)->GetName(); } } else if (planarFig.IsNotNull()) { if(this->m_SelectedPlanarFigure == nullptr) { this->m_SelectedPlanarFigure = planarFig; this->m_PlanarFigureObserverTag = this->m_SelectedPlanarFigure->AddObserver(mitk::EndInteractionPlanarFigureEvent(), changeListener); maskName = this->m_SelectedDataNodes.at(i)->GetName(); maskType = this->m_SelectedPlanarFigure->GetNameOfClass(); maskDimension = 2; planarFigureNode = m_SelectedDataNodes.at(i); } } else { std::stringstream message; message << "" << "Invalid data node type!" << ""; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); } } if(maskName == "") { maskName = "None"; maskType = ""; maskDimension = 0; } if(featureImageName == "") { featureImageName = "None"; } if (m_SelectedPlanarFigure != nullptr && m_SelectedImage == nullptr) { mitk::DataStorage::SetOfObjects::ConstPointer parentSet = this->GetDataStorage()->GetSources(planarFigureNode); for (unsigned int i=0; iSize(); i++) { mitk::DataNode::Pointer node = parentSet->ElementAt(i); if( imagePredicate->CheckNode(node) ) { bool isMask = false; node->GetPropertyValue("binary", isMask); isMask |= isLabelSet->CheckNode(node); if( !isMask ) { if(this->m_SelectedImage == nullptr) { this->m_SelectedImage = static_cast(node->GetData()); this->m_ImageObserverTag = this->m_SelectedImage->AddObserver(itk::ModifiedEvent(), changeListener); } } } } } unsigned int timeStep = renderPart->GetTimeNavigationController()->GetTime()->GetPos(); if ( m_SelectedImage != nullptr && m_SelectedImage->IsInitialized()) { // Check if a the selected image is a multi-channel image. If yes, statistics // cannot be calculated currently. if ( m_SelectedImage->GetPixelType().GetNumberOfComponents() > 1 ) { std::stringstream message; message << "Multi-component images not supported."; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); this->InvalidateStatisticsTableView(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); m_CurrentStatisticsValid = false; this->m_StatisticsUpdatePending = false; m_Controls->m_lineRadioButton->setEnabled(true); m_Controls->m_barRadioButton->setEnabled(true); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(true); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(true); m_Controls->m_UseDefaultBinSizeBox->setEnabled(true); m_Controls->m_InfoLabel->setText(""); return; } std::stringstream maskLabel; maskLabel << maskName; if ( maskDimension > 0 ) { maskLabel << " [" << maskDimension << "D " << maskType << "]"; } m_Controls->m_SelectedMaskLabel->setText( maskLabel.str().c_str() ); m_Controls->m_SelectedFeatureImageLabel->setText(featureImageName.c_str()); // check time step validity if(m_SelectedImage->GetDimension() <= 3 && timeStep > m_SelectedImage->GetDimension(3)-1) { timeStep = m_SelectedImage->GetDimension(3)-1; } // Add the used mask time step to the mask label so the user knows which mask time step was used // if the image time step is bigger than the total number of mask time steps (see // ImageStatisticsCalculator::ExtractImageAndMask) if (m_SelectedImageMask != nullptr) { unsigned int maskTimeStep = timeStep; if (maskTimeStep >= m_SelectedImageMask->GetTimeSteps()) { maskTimeStep = m_SelectedImageMask->GetTimeSteps() - 1; } m_Controls->m_SelectedMaskLabel->setText(m_Controls->m_SelectedMaskLabel->text() + QString(" (t=") + QString::number(maskTimeStep) + QString(")")); } // check if the segmentation mask is empty if (m_SelectedImageMask != NULL) { typedef itk::Image ItkImageType; typedef itk::ImageRegionConstIteratorWithIndex< ItkImageType > IteratorType; ItkImageType::Pointer itkImage; mitk::CastToItkImage( m_SelectedImageMask, itkImage ); bool empty = true; IteratorType it( itkImage, itkImage->GetLargestPossibleRegion() ); while ( !it.IsAtEnd() ) { ItkImageType::ValueType val = it.Get(); if ( val != 0 ) { empty = false; break; } ++it; } if ( empty ) { std::stringstream message; message << "Empty segmentation mask selected..."; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); return; } } //// initialize thread and trigger it this->m_CalculationThread->SetIgnoreZeroValueVoxel( m_Controls->m_IgnoreZerosCheckbox->isChecked() ); this->m_CalculationThread->Initialize( m_SelectedImage, m_SelectedImageMask, m_SelectedPlanarFigure ); this->m_CalculationThread->SetTimeStep( timeStep ); std::stringstream message; message << "Calculating statistics..."; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); try { // Compute statistics // this->m_CalculationThread->SetUseDefaultBinSize(m_Controls->m_UseDefaultBinSizeBox->isChecked()); this->m_CalculationThread->start(); } catch ( const mitk::Exception& e) { std::stringstream message; message << "" << e.GetDescription() << ""; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); this->m_StatisticsUpdatePending = false; } catch ( const std::runtime_error &e ) { // In case of exception, print error message on GUI std::stringstream message; message << "" << e.what() << ""; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); this->m_StatisticsUpdatePending = false; } catch ( const std::exception &e ) { MITK_ERROR << "Caught exception: " << e.what(); // In case of exception, print error message on GUI std::stringstream message; message << "Error! Unequal Dimensions of Image and Segmentation. No recompute possible "; m_Controls->m_ErrorMessageLabel->setText( message.str().c_str() ); m_Controls->m_ErrorMessageLabel->show(); this->m_StatisticsUpdatePending = false; } } else { this->m_StatisticsUpdatePending = false; } } void QmitkImageStatisticsView::SelectedDataModified() { if( !m_StatisticsUpdatePending ) { emit StatisticsUpdate(); } } void QmitkImageStatisticsView::NodeRemoved(const mitk::DataNode *node) { while(this->m_CalculationThread->isRunning()) // wait until thread has finished { itksys::SystemTools::Delay(100); } if (node->GetData() == m_SelectedImage) { m_SelectedImage = nullptr; } } void QmitkImageStatisticsView::RequestStatisticsUpdate() { if ( !m_StatisticsUpdatePending ) { if(this->m_DataNodeSelectionChanged) { this->SelectionChanged(this->GetCurrentSelection()); } else { this->m_StatisticsUpdatePending = true; this->UpdateStatistics(); } } if (this->GetRenderWindowPart()) this->GetRenderWindowPart()->RequestUpdate(); } void QmitkImageStatisticsView::OnHistogramBinSizeBoxValueChanged() { if (m_Controls->m_HistogramBinSizeSpinbox->value() != m_HistogramBinSize) { m_HistogramBinSize = m_Controls->m_HistogramBinSizeSpinbox->value(); this->m_CalculationThread->SetHistogramBinSize(m_Controls->m_HistogramBinSizeSpinbox->value()); this->UpdateStatistics(); } } void QmitkImageStatisticsView::WriteStatisticsToGUI() { m_Controls->m_JSHistogram->Clear(); //Disconnect OnLineRadioButtonSelected() to prevent reloading chart when radiobutton is checked programmatically disconnect((QObject*)(this->m_Controls->m_JSHistogram), SIGNAL(PageSuccessfullyLoaded()), 0, 0); connect((QObject*)(this->m_Controls->m_JSHistogram), SIGNAL(PageSuccessfullyLoaded()), (QObject*) this, SLOT(OnPageSuccessfullyLoaded())); m_Controls->m_lineRadioButton->setEnabled(true); m_Controls->m_barRadioButton->setEnabled(true); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(true); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(true); m_Controls->m_InfoLabel->setText(""); if(m_DataNodeSelectionChanged) { this->m_StatisticsUpdatePending = false; this->RequestStatisticsUpdate(); return; // stop visualization of results and calculate statistics of new selection } if ( this->m_CalculationThread->GetStatisticsUpdateSuccessFlag()) { if ( this->m_CalculationThread->GetStatisticsChangedFlag() ) { // Do not show any error messages m_Controls->m_ErrorMessageLabel->hide(); m_CurrentStatisticsValid = true; } if (m_SelectedImage != nullptr) { //all statistics are now computed also on planar figures (lines, paths...)! // If a (non-closed) PlanarFigure is selected, display a line profile widget if (m_SelectedPlanarFigure != nullptr) { // Check if the (closed) planar figure is out of bounds and so no image mask could be calculated--> Intensity Profile can not be calculated bool outOfBounds = false; if ( m_SelectedPlanarFigure->IsClosed() && m_SelectedImageMask == nullptr) { outOfBounds = true; const QString message("Planar figure is on a rotated image plane or outside the image bounds."); m_Controls->m_InfoLabel->setText(message); } // check whether PlanarFigure is initialized const mitk::PlaneGeometry *planarFigurePlaneGeometry = m_SelectedPlanarFigure->GetPlaneGeometry(); if ( !(planarFigurePlaneGeometry == nullptr || outOfBounds)) { unsigned int timeStep = this->GetRenderWindowPart()->GetTimeNavigationController()->GetTime()->GetPos(); mitk::Image::Pointer image; if (this->m_CalculationThread->GetStatisticsImage()->GetDimension() == 4) { mitk::ImageTimeSelector::Pointer timeSelector = mitk::ImageTimeSelector::New(); timeSelector->SetInput(this->m_CalculationThread->GetStatisticsImage()); timeSelector->SetTimeNr(timeStep); timeSelector->Update(); image = timeSelector->GetOutput(); } else { image = this->m_CalculationThread->GetStatisticsImage(); } mitk::IntensityProfile::ConstPointer intensityProfile = (mitk::IntensityProfile::ConstPointer)mitk::ComputeIntensityProfile(image, m_SelectedPlanarFigure); auto intensityProfileList = ConvertIntensityProfileToVector(intensityProfile); m_Controls->m_JSHistogram->SetChartType(QmitkChartWidget::ChartType::line); m_Controls->m_JSHistogram->AddData1D(intensityProfileList); m_Controls->m_JSHistogram->SetDataLabels({ "Intensity profile " + m_Controls->m_SelectedMaskLabel->text().toStdString() }); m_Controls->m_JSHistogram->SetXAxisLabel("Distance"); m_Controls->m_JSHistogram->SetYAxisLabel("Intensity"); m_Controls->m_JSHistogram->Show(m_Controls->m_ShowSubchartCheckBox->isChecked()); m_Controls->m_lineRadioButton->setChecked(true); m_Controls->m_lineRadioButton->setEnabled(false); m_Controls->m_barRadioButton->setEnabled(false); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(false); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(false); m_Controls->m_UseDefaultBinSizeBox->setEnabled(false); //Reconnect OnLineRadioButtonSelected() connect((QObject*)(this->m_Controls->m_JSHistogram), SIGNAL(PageSuccessfullyLoaded()), (QObject*) this, SLOT(OnLineRadioButtonSelected())); auto statisticsVector = this->m_CalculationThread->GetStatisticsData(); //only one entry (current timestep) this->FillLinearProfileStatisticsTableView(statisticsVector.front().GetPointer(), this->m_CalculationThread->GetStatisticsImage()); QString message("Only linegraph available for an intensity profile!"); if (this->m_CalculationThread->GetStatisticsImage()->GetDimension() == 4) { message += "Only current timestep displayed!"; } message += ""; m_Controls->m_InfoLabel->setText(message); m_CurrentStatisticsValid = true; } else { // Clear statistics, histogram, and GUI this->InvalidateStatisticsTableView(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex( 0 ); m_CurrentStatisticsValid = false; m_Controls->m_ErrorMessageLabel->hide(); m_Controls->m_SelectedMaskLabel->setText( "None" ); this->m_StatisticsUpdatePending = false; m_Controls->m_lineRadioButton->setEnabled(true); m_Controls->m_barRadioButton->setEnabled(true); m_Controls->m_HistogramBinSizeSpinbox->setEnabled(true); m_Controls->m_HistogramBinSizeCaptionLabel->setEnabled(true); if (!outOfBounds) m_Controls->m_InfoLabel->setText(""); - return; + return; } } else { m_Controls->m_StatisticsWidgetStack->setCurrentIndex(0); m_Controls->m_HistogramBinSizeSpinbox->setValue(this->m_CalculationThread->GetHistogramBinSize()); auto histogram = this->m_CalculationThread->GetTimeStepHistogram(this->m_CalculationThread->GetTimeStep()).GetPointer(); m_Controls->m_JSHistogram->AddData2D(ConvertHistogramToMap(histogram)); m_Controls->m_JSHistogram->SetChartType(QmitkChartWidget::ChartType::bar); this->m_Controls->m_JSHistogram->SetDataLabels({ m_Controls->m_SelectedFeatureImageLabel->text().toStdString() }); this->m_Controls->m_JSHistogram->SetXAxisLabel("Gray value"); this->m_Controls->m_JSHistogram->SetYAxisLabel("Frequency"); m_Controls->m_JSHistogram->Show(this->m_Controls->m_ShowSubchartCheckBox->isChecked()); this->FillStatisticsTableView(this->m_CalculationThread->GetStatisticsData(), this->m_CalculationThread->GetStatisticsImage()); } m_CurrentStatisticsValid = true; } } else { m_Controls->m_SelectedMaskLabel->setText("None"); m_Controls->m_ErrorMessageLabel->setText(m_CalculationThread->GetLastErrorMessage().c_str()); m_Controls->m_ErrorMessageLabel->show(); // Clear statistics and histogram this->InvalidateStatisticsTableView(); m_Controls->m_StatisticsWidgetStack->setCurrentIndex(0); m_CurrentStatisticsValid = false; } berry::IPreferencesService* prefService = berry::WorkbenchPlugin::GetDefault()->GetPreferencesService(); m_StylePref = prefService->GetSystemPreferences()->Node(berry::QtPreferences::QT_STYLES_NODE); this->m_StatisticsUpdatePending = false; } void QmitkImageStatisticsView::FillStatisticsTableView( const std::vector &statistics, const mitk::Image *image ) { this->m_Controls->m_StatisticsTable->setColumnCount(image->GetTimeSteps()); this->m_Controls->m_StatisticsTable->horizontalHeader()->setVisible(image->GetTimeSteps() > 1); // Set Checkbox for complete copy of statistic table if(image->GetTimeSteps()>1) { this->m_Controls->m_CheckBox4dCompleteTable->setEnabled(true); } else { this->m_Controls->m_CheckBox4dCompleteTable->setEnabled(false); this->m_Controls->m_CheckBox4dCompleteTable->setChecked(false); } for (unsigned int t = 0; t < image->GetTimeSteps(); t++) { this->m_Controls->m_StatisticsTable->setHorizontalHeaderItem(t, new QTableWidgetItem(QString::number(t))); if (statistics.at(t)->GetMaxIndex().size()==3) { mitk::Point3D index, max, min; index[0] = statistics.at(t)->GetMaxIndex()[0]; index[1] = statistics.at(t)->GetMaxIndex()[1]; index[2] = statistics.at(t)->GetMaxIndex()[2]; m_SelectedImage->GetGeometry()->IndexToWorld(index, max); this->m_WorldMaxList.push_back(max); index[0] = statistics.at(t)->GetMinIndex()[0]; index[1] = statistics.at(t)->GetMinIndex()[1]; index[2] = statistics.at(t)->GetMinIndex()[2]; m_SelectedImage->GetGeometry()->IndexToWorld(index, min); this->m_WorldMinList.push_back(min); } auto statisticsVector = AssembleStatisticsIntoVector(statistics.at(t).GetPointer(), image); unsigned int count = 0; for (const auto& entry : statisticsVector) { auto item = new QTableWidgetItem(entry); this->m_Controls->m_StatisticsTable->setItem(count, t, item); count++; } } this->m_Controls->m_StatisticsTable->resizeColumnsToContents(); int height = STAT_TABLE_BASE_HEIGHT; if (this->m_Controls->m_StatisticsTable->horizontalHeader()->isVisible()) height += this->m_Controls->m_StatisticsTable->horizontalHeader()->height(); if (this->m_Controls->m_StatisticsTable->horizontalScrollBar()->isVisible()) height += this->m_Controls->m_StatisticsTable->horizontalScrollBar()->height(); this->m_Controls->m_StatisticsTable->setMinimumHeight(height); // make sure the current timestep's column is highlighted (and the correct histogram is displayed) unsigned int t = this->GetRenderWindowPart()->GetTimeNavigationController()->GetTime()-> GetPos(); mitk::SliceNavigationController::GeometryTimeEvent timeEvent(this->m_SelectedImage->GetTimeGeometry(), t); this->OnTimeChanged(timeEvent); t = std::min(image->GetTimeSteps() - 1, t); // See bug 18340 /*QString hotspotMean; hotspotMean.append(QString("%1").arg(s[t].GetHotspotStatistics().GetMean(), 0, 'f', decimals)); hotspotMean += " ("; for (int i=0; im_Controls->m_StatisticsTable->setItem( 7, t, new QTableWidgetItem( hotspotMean ) ); QString hotspotMax; hotspotMax.append(QString("%1").arg(s[t].GetHotspotStatistics().GetMax(), 0, 'f', decimals)); hotspotMax += " ("; for (int i=0; im_Controls->m_StatisticsTable->setItem( 8, t, new QTableWidgetItem( hotspotMax ) ); QString hotspotMin; hotspotMin.append(QString("%1").arg(s[t].GetHotspotStatistics().GetMin(), 0, 'f', decimals)); hotspotMin += " ("; for (int i=0; im_Controls->m_StatisticsTable->setItem( 9, t, new QTableWidgetItem( hotspotMin ) );*/ } std::vector QmitkImageStatisticsView::AssembleStatisticsIntoVector(mitk::ImageStatisticsCalculator::StatisticsContainer::ConstPointer statistics, mitk::Image::ConstPointer image, bool noVolumeDefined) const { std::vector result; unsigned int decimals = 2; //statistics of higher order should have 5 decimal places because they used to be very small unsigned int decimalsHigherOrderStatistics = 5; if (image->GetPixelType().GetComponentType() == itk::ImageIOBase::DOUBLE || image->GetPixelType().GetComponentType() == itk::ImageIOBase::FLOAT) { decimals = 5; } result.push_back(GetFormattedString(statistics->GetMean(), decimals)); result.push_back(GetFormattedString(statistics->GetMedian(), decimals)); result.push_back(GetFormattedString(statistics->GetStd(), decimals)); result.push_back(GetFormattedString(statistics->GetRMS(), decimals)); result.push_back(GetFormattedString(statistics->GetMax(), decimals) + " " + GetFormattedIndex(statistics->GetMaxIndex())); result.push_back(GetFormattedString(statistics->GetMin(), decimals) + " " + GetFormattedIndex(statistics->GetMinIndex())); //to prevent large negative values of empty image statistics if (statistics->GetN() != std::numeric_limits::max() + 1) { result.push_back(GetFormattedString(statistics->GetN(), 0)); const mitk::BaseGeometry *geometry = image->GetGeometry(); if (geometry != NULL && !noVolumeDefined) { const mitk::Vector3D &spacing = image->GetGeometry()->GetSpacing(); double volume = spacing[0] * spacing[1] * spacing[2] * static_cast(statistics->GetN()); result.push_back(GetFormattedString(volume, decimals)); } else { result.push_back("NA"); } } else { result.push_back("NA"); result.push_back("NA"); } result.push_back(GetFormattedString(statistics->GetSkewness(), decimalsHigherOrderStatistics)); result.push_back(GetFormattedString(statistics->GetKurtosis(), decimalsHigherOrderStatistics)); result.push_back(GetFormattedString(statistics->GetUniformity(), decimalsHigherOrderStatistics)); result.push_back(GetFormattedString(statistics->GetEntropy(), decimalsHigherOrderStatistics)); result.push_back(GetFormattedString(statistics->GetMPP(), decimals)); result.push_back(GetFormattedString(statistics->GetUPP(), decimalsHigherOrderStatistics)); return result; } void QmitkImageStatisticsView::FillLinearProfileStatisticsTableView(mitk::ImageStatisticsCalculator::StatisticsContainer::ConstPointer statistics, const mitk::Image *image) { this->m_Controls->m_StatisticsTable->setColumnCount(1); this->m_Controls->m_StatisticsTable->horizontalHeader()->setVisible(false); m_PlanarFigureStatistics = this->AssembleStatisticsIntoVector(statistics, image, true); for (unsigned int i = 0; i< m_PlanarFigureStatistics.size(); i++) { this->m_Controls->m_StatisticsTable->setItem( i, 0, new QTableWidgetItem(m_PlanarFigureStatistics[i] )); } this->m_Controls->m_StatisticsTable->resizeColumnsToContents(); int height = STAT_TABLE_BASE_HEIGHT; if (this->m_Controls->m_StatisticsTable->horizontalHeader()->isVisible()) height += this->m_Controls->m_StatisticsTable->horizontalHeader()->height(); if (this->m_Controls->m_StatisticsTable->horizontalScrollBar()->isVisible()) height += this->m_Controls->m_StatisticsTable->horizontalScrollBar()->height(); this->m_Controls->m_StatisticsTable->setMinimumHeight(height); } void QmitkImageStatisticsView::InvalidateStatisticsTableView() { this->m_Controls->m_StatisticsTable->horizontalHeader()->setVisible(false); this->m_Controls->m_StatisticsTable->setColumnCount(1); for ( int i = 0; i < this->m_Controls->m_StatisticsTable->rowCount(); ++i ) { { this->m_Controls->m_StatisticsTable->setItem( i, 0, new QTableWidgetItem( "NA" ) ); } } this->m_Controls->m_StatisticsTable->setMinimumHeight(STAT_TABLE_BASE_HEIGHT); } void QmitkImageStatisticsView::Activated() { } void QmitkImageStatisticsView::Deactivated() { } void QmitkImageStatisticsView::Visible() { m_Visible = true; mitk::IRenderWindowPart* renderWindow = GetRenderWindowPart(); if (renderWindow) { itk::ReceptorMemberCommand::Pointer cmdTimeEvent = itk::ReceptorMemberCommand::New(); cmdTimeEvent->SetCallbackFunction(this, &QmitkImageStatisticsView::OnTimeChanged); // It is sufficient to add the observer to the axial render window since the GeometryTimeEvent // is always triggered by all views. m_TimeObserverTag = renderWindow->GetQmitkRenderWindow("axial")-> GetSliceNavigationController()-> AddObserver(mitk::SliceNavigationController::GeometryTimeEvent(nullptr, 0), cmdTimeEvent); } if (m_DataNodeSelectionChanged) { if (this->IsCurrentSelectionValid()) { this->SelectionChanged(this->GetCurrentSelection()); } else { this->SelectionChanged(this->GetDataManagerSelection()); } m_DataNodeSelectionChanged = false; } } void QmitkImageStatisticsView::Hidden() { m_Visible = false; // The slice navigation controller observer is removed here instead of in the destructor. // If it was called in the destructor, the application would freeze because the view's // destructor gets called after the render windows have been destructed. if ( m_TimeObserverTag != 0 ) { mitk::IRenderWindowPart* renderWindow = GetRenderWindowPart(); if (renderWindow) { renderWindow->GetQmitkRenderWindow("axial")->GetSliceNavigationController()-> RemoveObserver( m_TimeObserverTag ); } m_TimeObserverTag = 0; } } void QmitkImageStatisticsView::SetFocus() { } std::map QmitkImageStatisticsView::ConvertHistogramToMap(itk::Statistics::Histogram::ConstPointer histogram) const { std::map histogramMap; auto endIt = histogram->End(); auto it = histogram->Begin(); // generating Lists of measurement and frequencies for (; it != endIt; ++it) { double frequency = it.GetFrequency(); double measurement = it.GetMeasurementVector()[0]; histogramMap.emplace(measurement, frequency); } return histogramMap; } std::vector QmitkImageStatisticsView::ConvertIntensityProfileToVector(mitk::IntensityProfile::ConstPointer intensityProfile) const { std::vector intensityProfileList; auto end = intensityProfile->End(); for (auto it = intensityProfile->Begin(); it != end; ++it) { intensityProfileList.push_back(it.GetMeasurementVector()[0]); } return intensityProfileList; } QString QmitkImageStatisticsView::GetFormattedString(double value, unsigned int decimals) const { typedef mitk::ImageStatisticsCalculator::StatisticsContainer::RealType RealType; RealType maxVal = std::numeric_limits::max(); if (value == maxVal) { return QString("NA"); } else { return QString("%1").arg(value, 0, 'f', decimals); } } QString QmitkImageStatisticsView::GetFormattedIndex(const vnl_vector& vector) const { if (vector.empty()) { return QString(); } QString formattedIndex("("); for (const auto& entry : vector) { formattedIndex += QString::number(entry); formattedIndex += ","; } formattedIndex.chop(1); formattedIndex += ")"; return formattedIndex; } diff --git a/Plugins/org.mitk.gui.qt.moviemaker/CMakeLists.txt b/Plugins/org.mitk.gui.qt.moviemaker/CMakeLists.txt index 08a202e5d0..d38a3d1797 100644 --- a/Plugins/org.mitk.gui.qt.moviemaker/CMakeLists.txt +++ b/Plugins/org.mitk.gui.qt.moviemaker/CMakeLists.txt @@ -1,10 +1,10 @@ # The project name must correspond to the directory name of your plug-in # and must not contain periods. project(org_mitk_gui_qt_moviemaker) mitk_create_plugin( EXPORT_DIRECTIVE MOVIEMAKER_EXPORT EXPORTED_INCLUDE_SUFFIXES src - MODULE_DEPENDS MitkQtWidgetsExt MitkOpenViewCore + MODULE_DEPENDS MitkQtWidgetsExt PACKAGE_DEPENDS VTK|vtkTestingCore ) diff --git a/Plugins/org.mitk.gui.qt.simulation/CMakeLists.txt b/Plugins/org.mitk.gui.qt.simulation/CMakeLists.txt deleted file mode 100644 index 87a8a37ede..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -project(org_mitk_gui_qt_simulation) - -mitk_create_plugin( - EXPORT_DIRECTIVE SIMULATION_EXPORT - EXPORTED_INCLUDE_SUFFIXES src - MODULE_DEPENDS MitkQtWidgets MitkSimulation -) diff --git a/Plugins/org.mitk.gui.qt.simulation/files.cmake b/Plugins/org.mitk.gui.qt.simulation/files.cmake deleted file mode 100644 index 744bd1618c..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/files.cmake +++ /dev/null @@ -1,47 +0,0 @@ -set(SRC_CPP_FILES -) - -set(INTERNAL_CPP_FILES - org_mitk_gui_qt_simulation_Activator.cpp - QmitkBaseItemDelegate.cpp - QmitkBaseTreeWidget.cpp - QmitkNoEditItemDelegate.cpp - QmitkSceneTreeWidget.cpp - QmitkSimulationPreferencePage.cpp - QmitkSimulationView.cpp -) - -set(UI_FILES - src/internal/QmitkSimulationPreferencePageControls.ui - src/internal/QmitkSimulationViewControls.ui -) - -set(MOC_H_FILES - src/internal/org_mitk_gui_qt_simulation_Activator.h - src/internal/QmitkBaseItemDelegate.h - src/internal/QmitkBaseTreeWidget.h - src/internal/QmitkNoEditItemDelegate.h - src/internal/QmitkSceneTreeWidget.h - src/internal/QmitkSimulationPreferencePage.h - src/internal/QmitkSimulationView.h -) - -set(CACHED_RESOURCE_FILES - resources/SOFAIcon.png - plugin.xml -) - -set(QRC_FILES - resources/Simulation.qrc -) - -set(CPP_FILES -) - -foreach(file ${SRC_CPP_FILES}) - set(CPP_FILES ${CPP_FILES} src/${file}) -endforeach() - -foreach(file ${INTERNAL_CPP_FILES}) - set(CPP_FILES ${CPP_FILES} src/internal/${file}) -endforeach() diff --git a/Plugins/org.mitk.gui.qt.simulation/manifest_headers.cmake b/Plugins/org.mitk.gui.qt.simulation/manifest_headers.cmake deleted file mode 100644 index 8ff31cfca6..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/manifest_headers.cmake +++ /dev/null @@ -1,5 +0,0 @@ -set(Plugin-Name "MITK Simulation") -set(Plugin-Version "0.1") -set(Plugin-Vendor "DKFZ, Medical and Biological Informatics") -set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin org.mitk.simulation org.mitk.gui.qt.datamanager) diff --git a/Plugins/org.mitk.gui.qt.simulation/plugin.xml b/Plugins/org.mitk.gui.qt.simulation/plugin.xml deleted file mode 100644 index 5c5526c5a7..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/plugin.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.simulation/resources/Node_16x16.png b/Plugins/org.mitk.gui.qt.simulation/resources/Node_16x16.png deleted file mode 100644 index 411df8608d..0000000000 Binary files a/Plugins/org.mitk.gui.qt.simulation/resources/Node_16x16.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.simulation/resources/Object_16x16.png b/Plugins/org.mitk.gui.qt.simulation/resources/Object_16x16.png deleted file mode 100644 index 4832b76336..0000000000 Binary files a/Plugins/org.mitk.gui.qt.simulation/resources/Object_16x16.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.simulation/resources/SOFAIcon.png b/Plugins/org.mitk.gui.qt.simulation/resources/SOFAIcon.png deleted file mode 100644 index 3e0ce703ea..0000000000 Binary files a/Plugins/org.mitk.gui.qt.simulation/resources/SOFAIcon.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.simulation/resources/Simulation.qrc b/Plugins/org.mitk.gui.qt.simulation/resources/Simulation.qrc deleted file mode 100644 index 2684648ed4..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/resources/Simulation.qrc +++ /dev/null @@ -1,8 +0,0 @@ - - - Node_16x16.png - Object_16x16.png - Slave_16x16.png - SOFAIcon.png - - diff --git a/Plugins/org.mitk.gui.qt.simulation/resources/Slave_16x16.png b/Plugins/org.mitk.gui.qt.simulation/resources/Slave_16x16.png deleted file mode 100644 index 77a02cd4fa..0000000000 Binary files a/Plugins/org.mitk.gui.qt.simulation/resources/Slave_16x16.png and /dev/null differ diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseItemDelegate.cpp b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseItemDelegate.cpp deleted file mode 100644 index 27c630c59b..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseItemDelegate.cpp +++ /dev/null @@ -1,77 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "QmitkBaseItemDelegate.h" -#include - -using namespace sofa::defaulttype; -using namespace sofa::core::objectmodel; - -static inline BaseData* GetBaseData(const QModelIndex& index) -{ - return index.data(Qt::UserRole).value(); -} - -QmitkBaseItemDelegate::QmitkBaseItemDelegate(QObject* parent) - : QStyledItemDelegate(parent) -{ -} - -QmitkBaseItemDelegate::~QmitkBaseItemDelegate() -{ -} - -QWidget* QmitkBaseItemDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const -{ - BaseData* baseData = GetBaseData(index); - const AbstractTypeInfo* typeInfo = baseData->getValueTypeInfo(); - - if (typeInfo->name() == "bool") - { - assert(false && "Bool type is directly handled by QmitkBaseTreeWidget!"); - } - else if (typeInfo->size() == 1) - { - if (typeInfo->Integer() || typeInfo->Scalar() || typeInfo->Text()) - { - // TODO: TagSet - return QStyledItemDelegate::createEditor(parent, option, index); - } - - // TODO - } - else - { - // TODO - } - - return nullptr; -} - -void QmitkBaseItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const -{ - QStyledItemDelegate::paint(painter, option, index); -} - -void QmitkBaseItemDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const -{ - QStyledItemDelegate::setEditorData(editor, index); -} - -void QmitkBaseItemDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const -{ - QStyledItemDelegate::setModelData(editor, model, index); -} diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseItemDelegate.h b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseItemDelegate.h deleted file mode 100644 index 3ec0e70969..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseItemDelegate.h +++ /dev/null @@ -1,39 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef QmitkBaseItemDelegate_h -#define QmitkBaseItemDelegate_h - -#include -#include - -class QmitkBaseItemDelegate : public QStyledItemDelegate -{ - Q_OBJECT - -public: - explicit QmitkBaseItemDelegate(QObject* parent = nullptr); - ~QmitkBaseItemDelegate(); - - QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override; - void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override; - void setEditorData(QWidget* editor, const QModelIndex& index) const override; - void setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const override; -}; - -Q_DECLARE_METATYPE(sofa::core::objectmodel::BaseData*) - -#endif diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseTreeWidget.cpp b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseTreeWidget.cpp deleted file mode 100644 index 8e0b67255c..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseTreeWidget.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include -#include "QmitkBaseTreeWidget.h" -#include "QmitkBaseItemDelegate.h" -#include "QmitkNoEditItemDelegate.h" -#include "QmitkSceneTreeWidget.h" - -QmitkBaseTreeWidget::QmitkBaseTreeWidget(QWidget* parent) - : QTreeWidget(parent), - m_Base(nullptr) -{ - this->setItemDelegateForColumn(0, new QmitkNoEditItemDelegate); - this->setItemDelegateForColumn(1, new QmitkBaseItemDelegate); - - this->setSortingEnabled(true); - this->header()->setSortIndicator(0, Qt::AscendingOrder); -} - -QmitkBaseTreeWidget::~QmitkBaseTreeWidget() -{ -} - -void QmitkBaseTreeWidget::clear() -{ - m_Base = nullptr; - m_GroupItemMap.clear(); - - QTreeWidget::clear(); -} - -void QmitkBaseTreeWidget::OnSelectedBaseChanged(Base* base) -{ - this->clear(); - - m_Base = base; - - if (base != nullptr) - this->FillTreeWidget(); -} - -void QmitkBaseTreeWidget::FillTreeWidget() -{ - const Base::VecData& dataFields = m_Base->getDataFields(); - - for (auto dataField = dataFields.begin(); dataField != dataFields.end(); ++dataField) - { - if (!(*dataField)->isDisplayed()) - continue; - - QString name = QString::fromStdString((*dataField)->getName()); - - if (name.isEmpty()) - continue; - - QString group = (*dataField)->getGroup(); - - if (!group.isEmpty() && !m_GroupItemMap.contains(group)) - m_GroupItemMap.insert(group, new QTreeWidgetItem(this, QStringList() << group)); - - QTreeWidgetItem* item = new QTreeWidgetItem(QStringList() << name); - item->setToolTip(0, (*dataField)->getHelp()); - - item->setFlags(!(*dataField)->isReadOnly() - ? item->flags() | Qt::ItemIsEditable - : Qt::ItemIsSelectable); - - QString type = QString::fromStdString((*dataField)->getValueTypeString()); - - if (type == "bool") - { - item->setFlags((item->flags() & ~Qt::EditRole) | Qt::ItemIsUserCheckable); - item->setCheckState(1, (*dataField)->getValueString() == "1" ? Qt::Checked : Qt::Unchecked); - } - else - { - if (type == "double" || type == "float" || type == "int" || type == "string" || type == "unsigned int") - { - item->setData(1, Qt::DisplayRole, QVariant::fromValue(QString::fromStdString((*dataField)->getValueString()))); - } - else - { - item->setData(1, Qt::DisplayRole, QVariant::fromValue("[" + type + "]")); - } - - item->setData(1, Qt::UserRole, QVariant::fromValue(*dataField)); - } - - if (group.isEmpty()) - { - this->addTopLevelItem(item); - } - else - { - m_GroupItemMap[group]->addChild(item); - } - } - - this->setRootIsDecorated(!m_GroupItemMap.isEmpty()); - this->expandAll(); -} diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseTreeWidget.h b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseTreeWidget.h deleted file mode 100644 index 730695631f..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkBaseTreeWidget.h +++ /dev/null @@ -1,60 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef QmitkBaseTreeWidget_h -#define QmitkBaseTreeWidget_h - -#include -#include - -namespace sofa -{ - namespace core - { - namespace objectmodel - { - class Base; - } - } -} - -class QmitkSceneTreeWidget; - -class QmitkBaseTreeWidget : public QTreeWidget -{ - Q_OBJECT - -public: - typedef sofa::core::objectmodel::Base Base; - - explicit QmitkBaseTreeWidget(QWidget* parent = nullptr); - ~QmitkBaseTreeWidget(); - - // QTreeWidget, QTreeView, and QAbstractItemView Interfaces ///////////////// - void clear(); - ///////////////////////////////////////////////////////////////////////////// - -public slots: - void OnSelectedBaseChanged(Base* base); - -private: - void FillTreeWidget(); - - Base* m_Base; - QMap m_GroupItemMap; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkNoEditItemDelegate.cpp b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkNoEditItemDelegate.cpp deleted file mode 100644 index 7685bf5ffc..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkNoEditItemDelegate.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "QmitkNoEditItemDelegate.h" - -QmitkNoEditItemDelegate::QmitkNoEditItemDelegate(QObject* parent) - : QStyledItemDelegate(parent) -{ -} - -QmitkNoEditItemDelegate::~QmitkNoEditItemDelegate() -{ -} - -QWidget* QmitkNoEditItemDelegate::createEditor(QWidget*, const QStyleOptionViewItem&, const QModelIndex&) const -{ - return nullptr; -} diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkNoEditItemDelegate.h b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkNoEditItemDelegate.h deleted file mode 100644 index 67bb3fcb82..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkNoEditItemDelegate.h +++ /dev/null @@ -1,33 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef QmitkNoEditItemDelegate_h -#define QmitkNoEditItemDelegate_h - -#include - -class QmitkNoEditItemDelegate : public QStyledItemDelegate -{ - Q_OBJECT - -public: - explicit QmitkNoEditItemDelegate(QObject* parent = nullptr); - ~QmitkNoEditItemDelegate(); - - QWidget* createEditor(QWidget *parent, const QStyleOptionViewItem& option, const QModelIndex& index) const override; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSceneTreeWidget.cpp b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSceneTreeWidget.cpp deleted file mode 100644 index c3946e27a3..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSceneTreeWidget.cpp +++ /dev/null @@ -1,384 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "QmitkSceneTreeWidget.h" -#include -#include -#include -#include - -template -static inline T* as(QmitkSceneTreeWidget::Base* base) -{ - return dynamic_cast(base); -} - -template -static inline bool is(QmitkSceneTreeWidget::Base* base) -{ - return dynamic_cast(base) != nullptr; -} - -template -static inline bool is(QmitkSceneTreeWidget::Base* base) -{ - return is(base) || is(base); -} - -template -static inline bool is(QmitkSceneTreeWidget::Base* base) -{ - return is(base) || is(base) || is(base); -} - -static inline bool isBaseInteractionForceField(QmitkSceneTreeWidget::Base* base) -{ - sofa::core::behavior::BaseInteractionForceField* iff = dynamic_cast(base); - return iff != nullptr && iff->getMechModel1() != iff->getMechModel2(); -} - -static inline bool isMechanicalMapping(QmitkSceneTreeWidget::Base* base) -{ - sofa::core::BaseMapping* mm = dynamic_cast(base); - return mm != nullptr && mm->isMechanical(); -} - -static QRgb GetColor(QmitkSceneTreeWidget::Base* base) -{ - using namespace sofa::core; - using namespace sofa::core::behavior; - using namespace sofa::core::collision; - using namespace sofa::core::loader; - using namespace sofa::core::objectmodel; - using namespace sofa::core::topology; - using namespace sofa::core::visual; - using namespace sofa::simulation::Colors; - - QString hexColor; - - if (is(base)) - { - hexColor = COLOR[NODE]; - } - else if (is(base)) - { - if (is(base)) - hexColor = COLOR[sofa::simulation::Colors::CONTEXT]; - else if (is(base)) - hexColor = COLOR[BMODEL]; - else if (is(base)) - hexColor = COLOR[CMODEL]; - else if (is(base)) - hexColor = COLOR[MMODEL]; - else if (is(base)) - hexColor = COLOR[PROJECTIVECONSTRAINTSET]; - else if (is(base)) - hexColor = COLOR[CONSTRAINTSET]; - else if (is(base)) - hexColor = COLOR[MASS]; - else if (isBaseInteractionForceField(base)) - hexColor = COLOR[IFFIELD]; - else if (is(base)) - hexColor = COLOR[FFIELD]; - else if (is(base)) - hexColor = COLOR[SOLVER]; - else if (is(base)) - hexColor = COLOR[COLLISION]; - else if (isMechanicalMapping(base)) - hexColor = COLOR[MMAPPING]; - else if (is(base)) - hexColor = COLOR[MAPPING]; - else if (is(base)) - hexColor = COLOR[TOPOLOGY]; - else if (is(base)) - hexColor = COLOR[LOADER]; - else if (is(base)) - hexColor = COLOR[CONFIGURATIONSETTING]; - else if (is(base)) - hexColor = COLOR[VMODEL]; - else - hexColor = COLOR[OBJECT]; - } - else - { - hexColor = "#000"; - } - - QColor color; - color.setNamedColor(hexColor); - - return color.rgb(); -} - -static QPixmap ReplaceColor(const QPixmap& pixmap, QRgb from, QRgb to) -{ - QImage image = pixmap.toImage(); - - const int width = image.width(); - const int height = image.height(); - int x, y; - - for (y = 0; y < height; ++y) - { - for (x = 0; x < width; ++x) - { - if (image.pixel(x, y) == from) - image.setPixel(x, y, to); - } - } - - return QPixmap::fromImage(image); -} - -static inline QIcon CreateObjectIcon(QmitkSceneTreeWidget::Base* base) -{ - return QIcon(ReplaceColor(QPixmap(":/Simulation/Object"), 0xff00ff00, GetColor(base))); -} - -static inline QIcon CreateNodeIcon(QmitkSceneTreeWidget::BaseNode* node) -{ - return QIcon(ReplaceColor(QPixmap(":/Simulation/Node"), 0xff00ff00, GetColor(node))); -} - -static inline QIcon CreateSlaveIcon(QmitkSceneTreeWidget::Base* base) -{ - return QIcon(ReplaceColor(QPixmap(":/Simulation/Slave"), 0xff00ff00, GetColor(base))); -} - -static inline QString GetName(QmitkSceneTreeWidget::Base* base) -{ - return QString::fromStdString(base->getName()); -} - -static inline QString GetClassName(QmitkSceneTreeWidget::Base* base) -{ - return QString::fromStdString(base->getClassName()); -} - -QmitkSceneTreeWidget::QmitkSceneTreeWidget(QWidget* parent) - : QTreeWidget(parent) -{ -} - -QmitkSceneTreeWidget::~QmitkSceneTreeWidget() -{ -} - -void QmitkSceneTreeWidget::clear() -{ - QTreeWidgetItem* rootItem = this->topLevelItem(0); - - if (rootItem != nullptr) - this->removeChild(nullptr, as(m_ItemBaseMap[rootItem])); - - this->ClearMaps(); - - QTreeWidget::clear(); -} - -void QmitkSceneTreeWidget::addChild(Node* parent, Node* child) -{ - assert(child != nullptr && "Child node is nullptr!"); - assert(!m_BaseItemMap.contains(child) && "TODO: Support nodes with multiple parents!"); - - QTreeWidgetItem* item; - - if (parent == nullptr) - { - item = new QTreeWidgetItem(QStringList() << GetName(child)); - this->addTopLevelItem(item); - } - else - { - assert(m_BaseItemMap.contains(parent) && "Unknown parent node!"); - item = new QTreeWidgetItem(m_BaseItemMap[parent], QStringList() << GetName(child)); - } - - item->setIcon(0, CreateNodeIcon(child)); - this->InsertIntoMaps(child, item); - - MutationListener::addChild(parent, child); -} - -void QmitkSceneTreeWidget::removeChild(Node* parent, Node* child) -{ - assert(child != nullptr && "Child node is nullptr!"); - assert(m_BaseItemMap.contains(child) && "Child node has already been removed!"); - - MutationListener::removeChild(parent, child); - - if (parent == nullptr) - { - delete m_BaseItemMap[child]; - } - else - { - assert(m_BaseItemMap.contains(parent) && "Unknown parent node!"); - m_BaseItemMap[parent]->removeChild(m_BaseItemMap[child]); - } - - this->RemoveFromMaps(child); -} - -void QmitkSceneTreeWidget::moveChild(Node* previous, Node* parent, Node* child) -{ - if (previous == nullptr) - { - this->addChild(parent, child); - } - else if (parent == nullptr) - { - this->removeChild(previous, child); - } - else - { - assert(child != nullptr && "Child node is nullptr!"); - assert(m_BaseItemMap.contains(previous) && "Unknown previous parent node!"); - assert(m_BaseItemMap.contains(parent) && "Unknown parent node!"); - assert(m_BaseItemMap.contains(child) && "Unknown child node!"); - - QTreeWidgetItem* previousItem = m_BaseItemMap[previous]; - m_BaseItemMap[parent]->addChild(previousItem->takeChild(previousItem->indexOfChild(m_BaseItemMap[child]))); - } -} - -void QmitkSceneTreeWidget::addObject(Node* parent, BaseObject* object) -{ - assert(parent != nullptr && "Parent node is nullptr!"); - assert(object != nullptr && "Object is nullptr!"); - assert(m_BaseItemMap.contains(parent) && "Unknown parent node!"); - // assert(!m_BaseItemMap.contains(object) && "Object has already been added!"); - - if (!m_BaseItemMap.contains(object)) - { - QTreeWidgetItem* item = new QTreeWidgetItem(m_BaseItemMap[parent], QStringList() << GetName(object)); - item->setToolTip(0, GetClassName(object)); - item->setIcon(0, CreateObjectIcon(object)); - this->InsertIntoMaps(object, item); - } - - MutationListener::addObject(parent, object); -} - -void QmitkSceneTreeWidget::removeObject(Node* parent, BaseObject* object) -{ - assert(parent != nullptr && "Parent node is nullptr!"); - assert(object != nullptr && "Object is nullptr!"); - assert(m_BaseItemMap.contains(parent) && "Unknown parent node!"); - assert(m_BaseItemMap.contains(object) && "Object has already been removed!"); - - MutationListener::removeObject(parent, object); - - m_BaseItemMap[parent]->removeChild(m_BaseItemMap[object]); - this->RemoveFromMaps(object); -} - -void QmitkSceneTreeWidget::moveObject(Node* previous, Node* parent, BaseObject* object) -{ - if (previous == nullptr) - { - this->addObject(parent, object); - } - else if (parent == nullptr) - { - this->removeObject(previous, object); - } - else - { - assert(object != nullptr && "Object is nullptr!"); - assert(m_BaseItemMap.contains(previous) && "Unknown previous parent node!"); - assert(m_BaseItemMap.contains(parent) && "Unknown parent node!"); - assert(m_BaseItemMap.contains(object) && "Unknown object!"); - - QTreeWidgetItem* previousItem = m_BaseItemMap[previous]; - m_BaseItemMap[parent]->addChild(previousItem->takeChild(previousItem->indexOfChild(m_BaseItemMap[object]))); - } -} - -void QmitkSceneTreeWidget::addSlave(BaseObject* master, BaseObject* slave) -{ - assert(master != nullptr && "Master object is nullptr!"); - assert(slave != nullptr && "Slave object is nullptr!"); - assert(m_BaseItemMap.contains(master) && "Unknown master object!"); - assert(!m_BaseItemMap.contains(slave) && "Slave object has already been added!"); - - QTreeWidgetItem* item = new QTreeWidgetItem(m_BaseItemMap[master], QStringList() << GetName(slave)); - item->setToolTip(0, GetClassName(slave)); - item->setIcon(0, CreateSlaveIcon(slave)); - this->InsertIntoMaps(slave, item); - - MutationListener::addSlave(master, slave); -} - -void QmitkSceneTreeWidget::removeSlave(BaseObject* master, BaseObject* slave) -{ - assert(master != nullptr && "Master object is nullptr!"); - assert(slave != nullptr && "Slave object is nullptr!"); - assert(m_BaseItemMap.contains(master) && "Unknown master object!"); - assert(m_BaseItemMap.contains(slave) && "Slave object has already been removed!"); - - MutationListener::removeSlave(master, slave); - - m_BaseItemMap[master]->removeChild(m_BaseItemMap[slave]); - this->RemoveFromMaps(slave); -} - -void QmitkSceneTreeWidget::moveSlave(BaseObject* previousMaster, BaseObject* master, BaseObject* slave) -{ - if (previousMaster == nullptr) - { - this->addSlave(master, slave); - } - else if (master == nullptr) - { - this->removeSlave(previousMaster, slave); - } - else - { - assert(slave != nullptr && "Slave object is nullptr!"); - assert(m_BaseItemMap.contains(previousMaster) && "Unknown previous master object!"); - assert(m_BaseItemMap.contains(master) && "Unknown master object!"); - assert(m_BaseItemMap.contains(slave) && "Unknown slave object!"); - - QTreeWidgetItem* previousMasterItem = m_BaseItemMap[previousMaster]; - m_BaseItemMap[master]->addChild(previousMasterItem->takeChild(previousMasterItem->indexOfChild(m_BaseItemMap[slave]))); - } -} - -QmitkSceneTreeWidget::Base* QmitkSceneTreeWidget::GetBaseFromItem(QTreeWidgetItem* item) const -{ - return m_ItemBaseMap.contains(item) - ? m_ItemBaseMap[item] - : nullptr; -} - -void QmitkSceneTreeWidget::ClearMaps() -{ - m_BaseItemMap.clear(); - m_ItemBaseMap.clear(); -} - -void QmitkSceneTreeWidget::InsertIntoMaps(Base* base, QTreeWidgetItem* item) -{ - m_BaseItemMap.insert(base, item); - m_ItemBaseMap.insert(item, base); -} - -void QmitkSceneTreeWidget::RemoveFromMaps(Base* base) -{ - m_ItemBaseMap.remove(m_BaseItemMap[base]); - m_BaseItemMap.remove(base); -} diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSceneTreeWidget.h b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSceneTreeWidget.h deleted file mode 100644 index 09fe9f431e..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSceneTreeWidget.h +++ /dev/null @@ -1,82 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef QmitkSceneTreeWidget_h -#define QmitkSceneTreeWidget_h - -#include -#include -#include - -namespace sofa -{ - namespace core - { - namespace objectmodel - { - class Base; - class BaseNode; - class BaseObject; - } - } - - namespace simulation - { - class Node; - } -} - -class QmitkSceneTreeWidget : public QTreeWidget, public sofa::simulation::MutationListener -{ - Q_OBJECT - -public: - typedef sofa::core::objectmodel::Base Base; - typedef sofa::core::objectmodel::BaseNode BaseNode; - typedef sofa::core::objectmodel::BaseObject BaseObject; - typedef sofa::simulation::Node Node; - - explicit QmitkSceneTreeWidget(QWidget* parent = nullptr); - ~QmitkSceneTreeWidget(); - - Base* GetBaseFromItem(QTreeWidgetItem* item) const; - - // QTreeWidget, QTreeView, and QAbstractItemView Interfaces ///////////////// - void clear(); - ///////////////////////////////////////////////////////////////////////////// - - // MutationListener Interface /////////////////////////////////////////////// - void addChild(Node* parent, Node* child) override; - void removeChild(Node* parent, Node* child) override; - void moveChild(Node* previous, Node* parent, Node* child) override; - void addObject(Node* parent, BaseObject* object) override; - void removeObject(Node* parent, BaseObject* object) override; - void moveObject(Node* previous, Node* parent, BaseObject* object) override; - void addSlave(BaseObject* master, BaseObject* slave) override; - void removeSlave(BaseObject* master, BaseObject* slave) override; - void moveSlave(BaseObject* previousMaster, BaseObject* master, BaseObject* slave) override; - ///////////////////////////////////////////////////////////////////////////// - -private: - void ClearMaps(); - void InsertIntoMaps(Base* base, QTreeWidgetItem* item); - void RemoveFromMaps(Base* base); - - QMap m_BaseItemMap; - QMap m_ItemBaseMap; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePage.cpp b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePage.cpp deleted file mode 100644 index 0ec393bfd4..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePage.cpp +++ /dev/null @@ -1,209 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "QmitkSimulationPreferencePage.h" -#include -#include -#include -#include - -typedef sofa::helper::system::Plugin Plugin; -typedef sofa::helper::system::PluginManager PluginManager; -typedef sofa::helper::system::PluginManager::PluginIterator PluginIterator; -typedef sofa::helper::system::PluginManager::PluginMap PluginMap; - -QmitkSimulationPreferencePage::QmitkSimulationPreferencePage() - : m_Preferences(mitk::GetSimulationPreferences()), - m_Control(nullptr) -{ -} - -QmitkSimulationPreferencePage::~QmitkSimulationPreferencePage() -{ -} - -void QmitkSimulationPreferencePage::CreateQtControl(QWidget* parent) -{ - m_Control = new QWidget(parent); - m_Controls.setupUi(m_Control); - - QStringList headerLabels; - headerLabels << "Name" << "License" << "Version" << "Path"; - m_Controls.pluginsTreeWidget->setHeaderLabels(headerLabels); - - connect(m_Controls.pluginsTreeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(OnSelectedPluginChanged())); - connect(m_Controls.addButton, SIGNAL(clicked()), this, SLOT(OnAddButtonClicked())); - connect(m_Controls.removeButton, SIGNAL(clicked()), this, SLOT(OnRemoveButtonClicked())); - - this->Update(); -} - -QWidget* QmitkSimulationPreferencePage::GetQtControl() const -{ - return m_Control; -} - -void QmitkSimulationPreferencePage::Init(berry::IWorkbench::Pointer) -{ -} - -void QmitkSimulationPreferencePage::OnAddButtonClicked() -{ - QString filter = "SOFA Plugins "; - -#if defined(__APPLE__) - filter += "(*.dylib*)"; -#elif defined(WIN32) - filter += "(*.dll)"; -#else - filter += "(*.so)"; -#endif - - std::string path = QFileDialog::getOpenFileName(m_Control, "Add SOFA Plugin", "", filter).toStdString(); - - if (path.empty()) - return; - - PluginManager &pluginManager = PluginManager::getInstance(); - std::ostringstream errlog; - - if (pluginManager.loadPlugin(path, &errlog)) - { - if (!errlog.str().empty()) - { - auto messageBox = new QMessageBox(m_Control); - messageBox->setIcon(QMessageBox::Warning); - messageBox->setStandardButtons(QMessageBox::Ok); - messageBox->setText(errlog.str().c_str()); - messageBox->setWindowTitle("Warning"); - messageBox->show(); - } - - Plugin& plugin = pluginManager.getPluginMap()[path]; - plugin.initExternalModule(); - - QStringList pluginItem; - - pluginItem - << plugin.getModuleName() - << plugin.getModuleLicense() - << plugin.getModuleVersion() - << path.c_str(); - - m_Controls.pluginsTreeWidget->addTopLevelItem(new QTreeWidgetItem(pluginItem)); - } - else - { - auto messageBox = new QMessageBox(m_Control); - messageBox->setIcon(QMessageBox::Critical); - messageBox->setStandardButtons(QMessageBox::Ok); - messageBox->setText(errlog.str().c_str()); - messageBox->setWindowTitle("Error"); - messageBox->show(); - } -} - -void QmitkSimulationPreferencePage::OnSelectedPluginChanged() -{ - QList selectedItems = m_Controls.pluginsTreeWidget->selectedItems(); - - m_Controls.componentsListWidget->clear(); - - if (!selectedItems.isEmpty()) - { - PluginMap& pluginMap = sofa::helper::system::PluginManager::getInstance().getPluginMap(); - std::string path = selectedItems[0]->text(3).toStdString(); - - m_Controls.descriptionPlainTextEdit->setPlainText(pluginMap[path].getModuleDescription()); - m_Controls.componentsListWidget->addItems(QString(pluginMap[path].getModuleComponentList()).split(' ', QString::SkipEmptyParts)); - m_Controls.removeButton->setEnabled(true); - } - else - { - m_Controls.descriptionPlainTextEdit->clear(); - m_Controls.removeButton->setEnabled(false); - } -} - -void QmitkSimulationPreferencePage::OnRemoveButtonClicked() -{ - QList selectedItems = m_Controls.pluginsTreeWidget->selectedItems(); - - if (selectedItems.isEmpty()) - return; - - std::string path = selectedItems[0]->text(3).toStdString(); - - PluginManager& pluginManager = PluginManager::getInstance(); - std::ostringstream errlog; - - if (pluginManager.unloadPlugin(path, &errlog)) - { - delete selectedItems[0]; - } - else - { - auto messageBox = new QMessageBox(m_Control); - messageBox->setIcon(QMessageBox::Critical); - messageBox->setStandardButtons(QMessageBox::Ok); - messageBox->setText(errlog.str().c_str()); - messageBox->setWindowTitle("Error"); - messageBox->show(); - } -} - -void QmitkSimulationPreferencePage::PerformCancel() -{ -} - -bool QmitkSimulationPreferencePage::PerformOk() -{ - PluginManager& pluginManager = PluginManager::getInstance(); - PluginMap& pluginMap = pluginManager.getPluginMap(); - QString plugins; - - for (auto it = pluginMap.begin(); it != pluginMap.end(); ++it) - { - if (!plugins.isEmpty()) - plugins += ";"; - - plugins += QString::fromStdString(it->first); - } - - m_Preferences->Put("plugins", plugins); - return true; -} - -void QmitkSimulationPreferencePage::Update() -{ - PluginManager& pluginManager = PluginManager::getInstance(); - PluginMap& pluginMap = pluginManager.getPluginMap(); - - for (auto it = pluginMap.begin(); it != pluginMap.end(); ++it) - { - Plugin& plugin = it->second; - - QStringList pluginItem; - - pluginItem - << plugin.getModuleName() - << plugin.getModuleLicense() - << plugin.getModuleVersion() - << it->first.c_str(); - - m_Controls.pluginsTreeWidget->addTopLevelItem(new QTreeWidgetItem(pluginItem)); - } -} diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePage.h b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePage.h deleted file mode 100644 index 291fe656d3..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePage.h +++ /dev/null @@ -1,52 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef QmitkSimulationPreferencePage_h -#define QmitkSimulationPreferencePage_h - -#include -#include -#include -#include - -class SIMULATION_EXPORT QmitkSimulationPreferencePage : public QObject, public berry::IQtPreferencePage -{ - Q_OBJECT - Q_INTERFACES(berry::IPreferencePage); - -public: - QmitkSimulationPreferencePage(); - ~QmitkSimulationPreferencePage(); - - void CreateQtControl(QWidget* parent) override; - QWidget* GetQtControl() const override; - void Init(berry::IWorkbench::Pointer) override; - void PerformCancel() override; - bool PerformOk() override; - void Update() override; - -private slots: - void OnAddButtonClicked(); - void OnSelectedPluginChanged(); - void OnRemoveButtonClicked(); - -private: - berry::IPreferences::Pointer m_Preferences; - Ui::QmitkSimulationPreferencePageControls m_Controls; - QWidget* m_Control; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePageControls.ui b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePageControls.ui deleted file mode 100644 index a7320be2ce..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationPreferencePageControls.ui +++ /dev/null @@ -1,157 +0,0 @@ - - - QmitkSimulationPreferencePageControls - - - - 0 - 0 - 640 - 480 - - - - - - - Plugins - - - - - - - QAbstractItemView::NoEditTriggers - - - true - - - QAbstractItemView::SingleSelection - - - QAbstractItemView::SelectRows - - - 0 - - - false - - - false - - - true - - - false - - - 4 - - - false - - - - 1 - - - - - 2 - - - - - 3 - - - - - 4 - - - - - - - - - - Components - - - - - - - Description - - - - - - - true - - - - - - - QAbstractItemView::NoEditTriggers - - - QAbstractItemView::NoSelection - - - QAbstractItemView::SelectRows - - - true - - - - - - - - - - - Add... - - - - - - - false - - - Remove - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - - - - diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationView.cpp b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationView.cpp deleted file mode 100644 index cdbc729651..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationView.cpp +++ /dev/null @@ -1,345 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "org_mitk_gui_qt_simulation_Activator.h" -#include "QmitkBaseItemDelegate.h" -#include "QmitkNoEditItemDelegate.h" -#include "QmitkSimulationView.h" -#include -#include -#include -#include -#include -#include -#include - -template -static T* GetService() -{ - ctkPluginContext* context = mitk::org_mitk_gui_qt_simulation_Activator::GetContext(); - - if (context == nullptr) - return nullptr; - - ctkServiceReference serviceReference = context->getServiceReference(); - - return serviceReference - ? context->getService(serviceReference) - : nullptr; -} - -static mitk::SimulationInteractor::Pointer CreateSimulationInteractor() -{ - const us::Module* simulationModule = us::ModuleRegistry::GetModule("MitkSimulation"); - - mitk::SimulationInteractor::Pointer interactor = mitk::SimulationInteractor::New(); - interactor->LoadStateMachine("Simulation.xml", simulationModule); - interactor->SetEventConfig("SimulationConfig.xml", simulationModule); - - return interactor; -} - -class Equals -{ -public: - explicit Equals(mitk::DataNode::Pointer dataNode) - : m_DataNode(dataNode) - { - } - - bool operator()(const mitk::DataStorage::SetOfObjects::value_type& object) - { - return object == m_DataNode; - } - -private: - mitk::DataNode::Pointer m_DataNode; -}; - -QmitkSimulationView::QmitkSimulationView() - : m_SimulationService(GetService()), - m_Interactor(CreateSimulationInteractor()), - m_VtkModelContextMenu(nullptr), - m_Timer(this) -{ - this->GetDataStorage()->RemoveNodeEvent.AddListener( - mitk::MessageDelegate1(this, &QmitkSimulationView::OnNodeRemovedFromDataStorage)); - - connect(&m_Timer, SIGNAL(timeout()), this, SLOT(OnTimeout())); -} - -QmitkSimulationView::~QmitkSimulationView() -{ - this->GetDataStorage()->RemoveNodeEvent.RemoveListener( - mitk::MessageDelegate1(this, &QmitkSimulationView::OnNodeRemovedFromDataStorage)); -} - -void QmitkSimulationView::CreateQtPartControl(QWidget* parent) -{ - m_Ui.setupUi(parent); - - m_Ui.simulationComboBox->SetDataStorage(this->GetDataStorage()); - m_Ui.simulationComboBox->SetPredicate(mitk::NodePredicateDataType::New("Simulation")); - - QAction* vtkModelModeAction = new QAction(/*QIcon(":/Qmitk/Surface_48.png"),*/ "Render to Surface", m_VtkModelContextMenu); - vtkModelModeAction->setCheckable(true); - - m_VtkModelContextMenu = new QMenu(m_Ui.sceneTreeWidget); - m_VtkModelContextMenu->addAction(vtkModelModeAction); - - connect(m_Ui.simulationComboBox, SIGNAL(OnSelectionChanged(const mitk::DataNode*)), this, SLOT(OnSelectedSimulationChanged(const mitk::DataNode*))); - connect(m_Ui.animateButton, SIGNAL(toggled(bool)), this, SLOT(OnAnimateButtonToggled(bool))); - connect(m_Ui.stepButton, SIGNAL(clicked()), this, SLOT(OnStepButtonClicked())); - connect(m_Ui.resetButton, SIGNAL(clicked()), this, SLOT(OnResetButtonClicked())); - connect(m_Ui.dtSpinBox, SIGNAL(valueChanged(double)), this, SLOT(OnDtChanged(double))); - connect(m_Ui.sceneTreeWidget, SIGNAL(itemSelectionChanged()), this, SLOT(OnSelectedBaseChanged())); - connect(m_Ui.sceneTreeWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(OnBaseContextMenuRequested(const QPoint&))); - - if (m_Ui.simulationComboBox->GetSelectedNode().IsNotNull()) - { - this->OnSelectedSimulationChanged(m_Ui.simulationComboBox->GetSelectedNode()); - } - else - { - this->SetSimulationControlsEnabled(false); - } -} - -void QmitkSimulationView::OnAnimateButtonToggled(bool toggled) -{ - mitk::Scheduler* scheduler = m_SimulationService->GetScheduler(); - - if (toggled) - { - mitk::Simulation::Pointer simulation = static_cast(m_Selection->GetData()); - - simulation->SetAnimationFlag(true); - scheduler->AddProcess(simulation); - - m_Ui.stepButton->setEnabled(false); - } - else if (m_Selection.IsNotNull()) - { - mitk::Simulation::Pointer simulation = static_cast(m_Selection->GetData()); - - scheduler->RemoveProcess(simulation); - simulation->SetAnimationFlag(false); - - m_Ui.stepButton->setEnabled(true); - } - - if (!scheduler->IsEmpty()) - { - if (!m_Timer.isActive()) - m_Timer.start(0); - } - else - { - m_Timer.stop(); - } -} - -void QmitkSimulationView::OnBaseContextMenuRequested(const QPoint& point) -{ - typedef mitk::DataStorage::SetOfObjects SetOfObjects; - - QTreeWidgetItem* item = m_Ui.sceneTreeWidget->itemAt(point); - - if (item == nullptr) - return; - - QmitkSceneTreeWidget::Base* base = m_Ui.sceneTreeWidget->GetBaseFromItem(item); - - if (base == nullptr) - return; - - mitk::VtkModel* vtkModel = dynamic_cast(base); - - if (vtkModel == nullptr) - return; - - m_VtkModelContextMenu->actions().first()->setChecked(vtkModel->GetMode() == mitk::VtkModel::Surface); - - QAction* action = m_VtkModelContextMenu->exec(m_Ui.sceneTreeWidget->mapToGlobal(point)); - - if (action == nullptr) - return; - - if (action->text() == "Render to Surface") - { - mitk::DataStorage::Pointer dataStorage = this->GetDataStorage(); - SetOfObjects::ConstPointer objects = dataStorage->GetSubset(nullptr); - - if (action->isChecked()) - { - vtkModel->SetMode(mitk::VtkModel::Surface); - mitk::DataNode::Pointer dataNode = vtkModel->GetDataNode(); - - if (std::find_if(objects->begin(), objects->end(), Equals(dataNode)) == objects->end()) - dataStorage->Add(dataNode, m_Selection); - } - else - { - mitk::DataNode::Pointer dataNode = vtkModel->GetDataNode(); - - if (std::find_if(objects->begin(), objects->end(), Equals(dataNode)) != objects->end()) - dataStorage->Remove(dataNode); - - vtkModel->SetMode(mitk::VtkModel::OpenGL); - } - } -} - -void QmitkSimulationView::OnDtChanged(double dt) -{ - if (m_Selection.IsNull()) - return; - - mitk::Simulation::Pointer simulation = static_cast(m_Selection->GetData()); - simulation->SetDt(std::max(0.0, dt)); -} - -void QmitkSimulationView::OnNodeRemovedFromDataStorage(const mitk::DataNode* node) -{ - mitk::Simulation::Pointer simulation = dynamic_cast(node->GetData()); - - if (simulation.IsNotNull()) - { - mitk::Scheduler* scheduler = m_SimulationService->GetScheduler(); - - scheduler->RemoveProcess(simulation); - - if (scheduler->IsEmpty() && m_Timer.isActive()) - m_Timer.stop(); - - if (m_SimulationService->GetActiveSimulation() == simulation) - m_SimulationService->SetActiveSimulation(nullptr); - } -} - -void QmitkSimulationView::OnResetButtonClicked() -{ - mitk::Simulation::Pointer simulation = static_cast(m_Selection->GetData()); - m_SimulationService->SetActiveSimulation(simulation); - - m_Ui.dtSpinBox->setValue(simulation->GetRootNode()->getDt()); - simulation->Reset(); - - this->RequestRenderWindowUpdate(mitk::RenderingManager::REQUEST_UPDATE_ALL); -} - -void QmitkSimulationView::OnSelectedSimulationChanged(const mitk::DataNode* node) -{ - if (node != nullptr) - { - m_Selection = m_Ui.simulationComboBox->GetSelectedNode(); - mitk::Simulation* simulation = static_cast(m_Selection->GetData()); - - m_Ui.animateButton->setChecked(simulation->GetAnimationFlag()); - m_Ui.dtSpinBox->setValue(simulation->GetRootNode()->getDt()); - this->SetSimulationControlsEnabled(true); - } - else - { - m_Selection = nullptr; - - this->SetSimulationControlsEnabled(false); - m_Ui.animateButton->setChecked(false); - m_Ui.dtSpinBox->setValue(0.0); - } - - m_Interactor->SetDataNode(m_Selection); - - this->ResetSceneTreeWidget(); -} - -void QmitkSimulationView::OnSelectedBaseChanged() -{ - QList selectedBaseItems = m_Ui.sceneTreeWidget->selectedItems(); - - m_Ui.baseTreeWidget->OnSelectedBaseChanged(!selectedBaseItems.isEmpty() - ? m_Ui.sceneTreeWidget->GetBaseFromItem(selectedBaseItems[0]) - : nullptr); -} - -void QmitkSimulationView::OnStep(bool renderWindowUpdate) -{ - mitk::Scheduler* scheduler = m_SimulationService->GetScheduler(); - mitk::Simulation::Pointer simulation = dynamic_cast(scheduler->GetNextProcess()); - - m_SimulationService->SetActiveSimulation(simulation); - - if (simulation.IsNotNull()) - simulation->Animate(); - - if (renderWindowUpdate) - this->RequestRenderWindowUpdate(mitk::RenderingManager::REQUEST_UPDATE_ALL); -} - -void QmitkSimulationView::OnStepButtonClicked() -{ - if (m_Selection.IsNull()) - return; - - mitk::Simulation::Pointer simulation = static_cast(m_Selection->GetData()); - - m_SimulationService->SetActiveSimulation(simulation); - simulation->Animate(); - - this->RequestRenderWindowUpdate(mitk::RenderingManager::REQUEST_UPDATE_ALL); -} - -void QmitkSimulationView::OnTimeout() -{ - QTime currentTime = QTime::currentTime(); - - if (currentTime.msecsTo(m_NextRenderWindowUpdate) > 0) - { - this->OnStep(false); - } - else - { - m_NextRenderWindowUpdate = currentTime.addMSecs(MSecsPerFrame); - this->OnStep(true); - } -} - -void QmitkSimulationView::ResetSceneTreeWidget() -{ - m_Ui.sceneTreeWidget->clear(); - - if (m_Selection.IsNull()) - return; - - mitk::Simulation::Pointer simulation = static_cast(m_Selection->GetData()); - - m_Ui.sceneTreeWidget->addChild(nullptr, simulation->GetRootNode().get()); - m_Ui.sceneTreeWidget->expandItem(m_Ui.sceneTreeWidget->topLevelItem(0)); -} - -void QmitkSimulationView::SetSimulationControlsEnabled(bool enabled) -{ - m_Ui.animateButton->setEnabled(enabled); - m_Ui.stepButton->setEnabled(enabled); - m_Ui.resetButton->setEnabled(enabled); - m_Ui.dtLabel->setEnabled(enabled); - m_Ui.dtSpinBox->setEnabled(enabled); -} - -void QmitkSimulationView::SetFocus() -{ - m_Ui.animateButton->setFocus(); -} diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationView.h b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationView.h deleted file mode 100644 index 6e33c1904e..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationView.h +++ /dev/null @@ -1,70 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef QmitkSimulationView_h -#define QmitkSimulationView_h - -#include -#include -#include -#include -#include -#include - -namespace mitk -{ - class ISimulationService; -} - -class QmitkSimulationView : public QmitkAbstractView -{ - Q_OBJECT - -public: - QmitkSimulationView(); - ~QmitkSimulationView(); - - void CreateQtPartControl(QWidget* parent) override; - void SetFocus() override; - -private slots: - void OnAnimateButtonToggled(bool toggled); - void OnBaseContextMenuRequested(const QPoint& point); - void OnDtChanged(double dt); - void OnResetButtonClicked(); - void OnSelectedSimulationChanged(const mitk::DataNode* node); - void OnSelectedBaseChanged(); - void OnStep(bool renderWindowUpdate); - void OnStepButtonClicked(); - void OnTimeout(); - -private: - void OnNodeRemovedFromDataStorage(const mitk::DataNode* node); - void ResetSceneTreeWidget(); - void SetSimulationControlsEnabled(bool enabled); - - static const int MSecsPerFrame = 17; - - Ui::QmitkSimulationViewControls m_Ui; - mitk::ISimulationService* m_SimulationService; - mitk::DataNode::Pointer m_Selection; - mitk::SimulationInteractor::Pointer m_Interactor; - QMenu* m_VtkModelContextMenu; - QTimer m_Timer; - QTime m_NextRenderWindowUpdate; -}; - -#endif diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationViewControls.ui b/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationViewControls.ui deleted file mode 100644 index f1943335fa..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/QmitkSimulationViewControls.ui +++ /dev/null @@ -1,182 +0,0 @@ - - - QmitkSimulationViewControls - - - true - - - - 0 - 0 - 248 - 751 - - - - Simulation - - - - - - - - - 0 - 0 - - - - - - - - - 0 - 0 - - - - Animate - - - true - - - false - - - - - - - - 0 - 0 - - - - Step - - - - - - - - 0 - 0 - - - - Reset - - - - - - - - 0 - 0 - - - - dt - - - - - - - - 0 - 0 - - - - s - - - 3 - - - 0.010000000000000 - - - - - - - - - Qt::Vertical - - - - Qt::CustomContextMenu - - - QAbstractItemView::NoEditTriggers - - - true - - - false - - - 1 - - - false - - - - Name - - - - - - true - - - 120 - - - - Property - - - - - Value - - - - - - - - - - QmitkDataStorageComboBox - QComboBox -
QmitkDataStorageComboBox.h
-
- - QmitkSceneTreeWidget - QTreeWidget -
internal/QmitkSceneTreeWidget.h
-
- - QmitkBaseTreeWidget - QTreeWidget -
internal/QmitkBaseTreeWidget.h
-
-
- - -
diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/org_mitk_gui_qt_simulation_Activator.cpp b/Plugins/org.mitk.gui.qt.simulation/src/internal/org_mitk_gui_qt_simulation_Activator.cpp deleted file mode 100644 index de183e97ad..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/org_mitk_gui_qt_simulation_Activator.cpp +++ /dev/null @@ -1,38 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "org_mitk_gui_qt_simulation_Activator.h" -#include "QmitkSimulationPreferencePage.h" -#include "QmitkSimulationView.h" - -ctkPluginContext* mitk::org_mitk_gui_qt_simulation_Activator::Context = nullptr; - -ctkPluginContext* mitk::org_mitk_gui_qt_simulation_Activator::GetContext() -{ - return Context; -} - -void mitk::org_mitk_gui_qt_simulation_Activator::start(ctkPluginContext* context) -{ - BERRY_REGISTER_EXTENSION_CLASS(QmitkSimulationPreferencePage, context); - BERRY_REGISTER_EXTENSION_CLASS(QmitkSimulationView, context); - Context = context; -} - -void mitk::org_mitk_gui_qt_simulation_Activator::stop(ctkPluginContext*) -{ - Context = nullptr; -} diff --git a/Plugins/org.mitk.gui.qt.simulation/src/internal/org_mitk_gui_qt_simulation_Activator.h b/Plugins/org.mitk.gui.qt.simulation/src/internal/org_mitk_gui_qt_simulation_Activator.h deleted file mode 100644 index 2efd8b73b0..0000000000 --- a/Plugins/org.mitk.gui.qt.simulation/src/internal/org_mitk_gui_qt_simulation_Activator.h +++ /dev/null @@ -1,41 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef org_mitk_gui_qt_simulation_Activator_h -#define org_mitk_gui_qt_simulation_Activator_h - -#include - -namespace mitk -{ - class org_mitk_gui_qt_simulation_Activator : public QObject, public ctkPluginActivator - { - Q_OBJECT - Q_PLUGIN_METADATA(IID "org_mitk_gui_qt_simulation") - Q_INTERFACES(ctkPluginActivator); - - public: - static ctkPluginContext* GetContext(); - - void start(ctkPluginContext* context) override; - void stop(ctkPluginContext*) override; - - private: - static ctkPluginContext* Context; - }; -} - -#endif diff --git a/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization.dox b/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization.dox index 87b5e157ab..45c93fb7c7 100644 --- a/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization.dox +++ b/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization.dox @@ -1,151 +1,154 @@ /** \page org_mitk_views_volumevisualization The Volume Visualization Plugin \imageMacro{QmitkVolumeVisualization_Icon.png,"Icon of the Volume Visualization Plugin",2.00} \tableofcontents \section QVV_Overview Overview The Volume Visualization Plugin is a basic tool for visualizing three dimensional medical images. MITK provides generic transfer function presets for medical CT data. These functions, that map the gray-value to color and opacity, can be interactively edited. Additionally, there are controls to quickly generate common used transfer function shapes like the threshold and bell curve to help identify a range of grey-values. \imageMacro{QmitkVolumeVisualization_Overview.png,"",16.00} \section QVV_EnableVRPage Enable Volume Rendering \subsection QVV_LoadingImage Loading an image into the application Load an image into the application by
  • dragging a file into the application window.
  • selecting file / load from the menu.
Volume Visualization imposes following restrictions on images:
  • It has to be a 3D-Image Scalar image, that means a normal CT or MRT.
  • 3D+T are supported for rendering, but the histograms are not computed.
  • Also be aware that volume visualization requires a huge amount of memory. Very large images may not work, unless you use the 64bit version.
\subsection QVV_EnableVR Enable Volumerendering \imageMacro{QmitkVolumeVisualization_Checkboxen.png,"",8.21} Select an image in datamanager and click on the checkbox left of "Volumerendering". Please be patient, while the image is prepared for rendering, which can take up to a half minute. -\subsection QVV_LODGPU The LOD & GPU checkboxes +\subsection QVV_LODGPU Dropdown menus for the rendering and blend modes -Volume Rendering requires a lot of computing resources including processor, memory and graphics card. +Two dropdown menus allow selection of rendering mode (Default, RayCast, GPU) and the blend mode (Composite, Max, Min, Avg, Add). -To run volume rendering on smaller platforms, -enable the LOD checkbox (level-of-detail rendering). -Level-of-detail first renders a lower quality preview to increase interactivity. -If the user stops to interact a normal quality rendering is issued. - -The GPU checkbox tries to use computing resources on the graphics card to accelerate volume rendering. +Any Volume Rendering mode requires a lot of computing resources including processor, memory and often also graphics card. +The Default selection usually finds the best rendering mode for the available hardware. +Alternatively, it is possible to manually specify the selections RayCast and GPU. +The RayCast selection is based on CPU computation and therefore typically slow, but allows to render without hardware acceleration. +The GPU selection uses computing resources on the graphics card to accelerate volume rendering. It requires a powerful graphics card and OpenGL hardware support for shaders, but achieves much higher frame rates than software-rendering. +Blend modes define how the volume voxels intersected by the rendering rays are pooled. The composite mode specifies standard volume rendering, +for which each voxel contributes equally with opacity and color. Other blend modes simply visualize the voxel of maximum / +minimum intensity and average / add the intentities along the rendering ray. + \section QVV_PresetPage Applying premade presets \subsection QVV_Preset Internal presets There are some internal presets given, that can be used with normal CT data (given in Houndsfield units). A large set of medical data has been tested with that presets, but it may not suit on some special cases. Click on the "Preset" tab for using internal or custom presets. \imageMacro{QmitkVolumeVisualization_InternalPresets.png,"",8.30}
  • "CT Generic" is the default transferfunction that is first applied.
  • "CT Black&White" does not use any colors, as it may be distracting on some data.
  • "CT Cardiac" tries to increase detail on CTs from the heart.
  • "CT Bone" emphasizes bones and shows other areas more transparent.
  • "CT Bone (Gradient)" is like "CT Bone", but shows from other organs only the surface by using the gradient.
  • "MR Generic" is the default transferfunction that we use on MRT data (which is not normalized like CT data).
  • "CT Thorax small" tries to increase detail.
  • "CT Thorax large" tries to increase detail.
\subsection QVV_CustomPreset Saving and loading custom presets After creating or editing a transferfunction (see \ref QVV_Editing or \ref QVV_ThresholdBell), the custom transferfunction can be stored and later retrieved on the filesystem. Click "Save" (respectively "Load") button to save (load) the threshold-, color- and gradient function combined in a single .xml file. \section QVV_ThresholdBell Interactively create transferfunctions Beside the possibility to directly edit the transferfunctions (\ref QVV_Editing), a one-click generation of two commonly known shapes is given. Both generators have two parameters, that can be modified by first clicking on the cross and then moving the mouse up/down and left/right. The first parameter "center" (controlled by horizontal movement of the mouse) specifies the gravalue where the center of the shape will be located. The second parameter "width" (controlled by vertical movement of the mouse) specifies the width (or steepness) of the shape. \subsection Threshold Click on the "Threshold" tab to active the threshold function generator. \imageMacro{QmitkVolumeVisualization_Threshold.png,"",8.21} A threshold shape begins with zero and raises to one across the "center" parameter. Lower widths results in steeper threshold functions. \subsection Bell Click on the "Bell" tab to active the threshold function generator. \imageMacro{QmitkVolumeVisualization_Bell.png,"",8.23} A threshold shape begins with zero and raises to one at the "center" parameter and the lowers agains to zero. The "width" parameter correspondens to the width of the bell. \section QVV_Editing Customize transferfunctions in detail \subsection QVV_Navigate Choosing grayvalue interval to edit \imageMacro{QmitkVolumeVisualization_Slider.png,"",8.23} To navigate across the grayvalue range or to zoom in some ranges use the "range"-slider. All three function editors have in common following:
  • By left-clicking a new point is added.
  • By right-clicking a point is deleted.
  • By left-clicking and holding, an exisiting point can be dragged.
  • By pressing arrow keys, the currently selected point is moved.
  • By pressing the "DELETE" key, the currently selected point is deleted.
  • Between points the transferfunctions are linear interpolated.
There are three transferfunctions to customize: \subsection QVV_GO Grayvalue -> Opacity \imageMacro{QmitkVolumeVisualization_Opacity.png,"grayvalues will be mapped to opacity.",8.04} An opacity of 0 means total transparent, an opacity of 1 means total opaque. \subsection QVV_GC Grayvalue -> Color \imageMacro{QmitkVolumeVisualization_Color.png,"grayvalues will be mapped to color.",8.81} The color transferfunction editor also allows by double-clicking a point to change its color. \subsection QVV_GGO Grayvalue and Gradient -> Opacity \imageMacro{QmitkVolumeVisualization_Gradient.png,"",8.85} Here the influence of the gradient is controllable at specific grayvalues. */ diff --git a/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization_Checkboxen.png b/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization_Checkboxen.png index 473bdcf868..31f968a1ac 100644 Binary files a/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization_Checkboxen.png and b/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization_Checkboxen.png differ diff --git a/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization_Overview.png b/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization_Overview.png index 495e19e807..70621fbd52 100644 Binary files a/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization_Overview.png and b/Plugins/org.mitk.gui.qt.volumevisualization/documentation/UserManual/QmitkVolumeVisualization_Overview.png differ diff --git a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp index f6ab96e5b9..8dc1efe285 100755 --- a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp +++ b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.cpp @@ -1,350 +1,344 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "QmitkVolumeVisualizationView.h" #include #include +#include #include #include #include //#include #include #include #include #include #include #include #include "mitkHistogramGenerator.h" #include "QmitkPiecewiseFunctionCanvas.h" #include "QmitkColorTransferFunctionCanvas.h" #include "mitkBaseRenderer.h" #include "mitkVtkVolumeRenderingProperty.h" #include #include const std::string QmitkVolumeVisualizationView::VIEW_ID = "org.mitk.views.volumevisualization"; -enum RenderMode -{ - RM_CPU_COMPOSITE_RAYCAST = 0, - RM_CPU_MIP_RAYCAST = 1, - RM_GPU_COMPOSITE_SLICING = 2, - RM_GPU_COMPOSITE_RAYCAST = 3, - RM_GPU_MIP_RAYCAST = 4 -}; +enum {DEFAULT_RENDERMODE = 0, RAYCAST_RENDERMODE = 1, GPU_RENDERMODE = 2}; QmitkVolumeVisualizationView::QmitkVolumeVisualizationView() : QmitkAbstractView(), m_Controls(nullptr) { } QmitkVolumeVisualizationView::~QmitkVolumeVisualizationView() { } void QmitkVolumeVisualizationView::CreateQtPartControl(QWidget* parent) { if (!m_Controls) { m_Controls = new Ui::QmitkVolumeVisualizationViewControls; m_Controls->setupUi(parent); // Fill the tf presets in the generator widget std::vector names; mitk::TransferFunctionInitializer::GetPresetNames(names); for (std::vector::const_iterator it = names.begin(); it != names.end(); ++it) { m_Controls->m_TransferFunctionGeneratorWidget->AddPreset(QString::fromStdString(*it)); } - - m_Controls->m_RenderMode->addItem("CPU raycast"); - m_Controls->m_RenderMode->addItem("CPU MIP raycast"); - m_Controls->m_RenderMode->addItem("GPU slicing"); -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) )) - m_Controls->m_RenderMode->addItem("GPU raycast"); - m_Controls->m_RenderMode->addItem("GPU MIP raycast"); -#endif + + // see enum in vtkSmartVolumeMapper + m_Controls->m_RenderMode->addItem("Default"); + m_Controls->m_RenderMode->addItem("RayCast"); + m_Controls->m_RenderMode->addItem("GPU"); + + // see vtkVolumeMapper::BlendModes + m_Controls->m_BlendMode->addItem("Comp"); + m_Controls->m_BlendMode->addItem("Max"); + m_Controls->m_BlendMode->addItem("Min"); + m_Controls->m_BlendMode->addItem("Avg"); + m_Controls->m_BlendMode->addItem("Add"); connect( m_Controls->m_EnableRenderingCB, SIGNAL( toggled(bool) ),this, SLOT( OnEnableRendering(bool) )); - connect( m_Controls->m_EnableLOD, SIGNAL( toggled(bool) ),this, SLOT( OnEnableLOD(bool) )); - connect( m_Controls->m_RenderMode, SIGNAL( activated(int) ),this, SLOT( OnRenderMode(int) )); + connect(m_Controls->m_RenderMode, SIGNAL(activated(int)), this, SLOT(OnRenderMode(int))); + connect(m_Controls->m_BlendMode, SIGNAL(activated(int)), this, SLOT(OnBlendMode(int))); connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL( SignalUpdateCanvas( ) ), m_Controls->m_TransferFunctionWidget, SLOT( OnUpdateCanvas( ) ) ); connect( m_Controls->m_TransferFunctionGeneratorWidget, SIGNAL(SignalTransferFunctionModeChanged(int)), SLOT(OnMitkInternalPreset(int))); m_Controls->m_EnableRenderingCB->setEnabled(false); - m_Controls->m_EnableLOD->setEnabled(false); + m_Controls->m_BlendMode->setEnabled(false); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); - } } void QmitkVolumeVisualizationView::OnMitkInternalPreset( int mode ) { if (m_SelectedNode.IsNull()) return; mitk::DataNode::Pointer node(m_SelectedNode.GetPointer()); mitk::TransferFunctionProperty::Pointer transferFuncProp; if (node->GetProperty(transferFuncProp, "TransferFunction")) { //first item is only information if( --mode == -1 ) return; // -- Creat new TransferFunction mitk::TransferFunctionInitializer::Pointer tfInit = mitk::TransferFunctionInitializer::New(transferFuncProp->GetValue()); tfInit->SetTransferFunctionMode(mode); RequestRenderWindowUpdate(); m_Controls->m_TransferFunctionWidget->OnUpdateCanvas(); } } void QmitkVolumeVisualizationView::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*part*/, const QList& nodes) { bool weHadAnImageButItsNotThreeDeeOrFourDee = false; mitk::DataNode::Pointer node; for (mitk::DataNode::Pointer currentNode: nodes) { if( currentNode.IsNotNull() && dynamic_cast(currentNode->GetData()) ) { if( dynamic_cast(currentNode->GetData())->GetDimension()>=3 ) { if (node.IsNull()) { node = currentNode; } } else { weHadAnImageButItsNotThreeDeeOrFourDee = true; } } } if( node.IsNotNull() ) { m_Controls->m_NoSelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_SelectedImageLabel->show(); std::string infoText; if (node->GetName().empty()) infoText = std::string("Selected Image: [currently selected image has no name]"); else infoText = std::string("Selected Image: ") + node->GetName(); m_Controls->m_SelectedImageLabel->setText( QString( infoText.c_str() ) ); m_SelectedNode = node; } else { if(weHadAnImageButItsNotThreeDeeOrFourDee) { m_Controls->m_NoSelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->show(); std::string infoText; infoText = std::string("only 3D or 4D images are supported"); m_Controls->m_ErrorImageLabel->setText( QString( infoText.c_str() ) ); } else { m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_NoSelectedImageLabel->show(); } m_SelectedNode = 0; } UpdateInterface(); } void QmitkVolumeVisualizationView::UpdateInterface() { if(m_SelectedNode.IsNull()) { // turnoff all m_Controls->m_EnableRenderingCB->setChecked(false); m_Controls->m_EnableRenderingCB->setEnabled(false); - m_Controls->m_EnableLOD->setChecked(false); - m_Controls->m_EnableLOD->setEnabled(false); + m_Controls->m_BlendMode->setCurrentIndex(0); + m_Controls->m_BlendMode->setEnabled(false); m_Controls->m_RenderMode->setCurrentIndex(0); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->SetDataNode(0); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); return; } bool enabled = false; m_SelectedNode->GetBoolProperty("volumerendering",enabled); m_Controls->m_EnableRenderingCB->setEnabled(true); m_Controls->m_EnableRenderingCB->setChecked(enabled); if(!enabled) { // turnoff all except volumerendering checkbox - m_Controls->m_EnableLOD->setChecked(false); - m_Controls->m_EnableLOD->setEnabled(false); + m_Controls->m_BlendMode->setCurrentIndex(0); + m_Controls->m_BlendMode->setEnabled(false); m_Controls->m_RenderMode->setCurrentIndex(0); m_Controls->m_RenderMode->setEnabled(false); m_Controls->m_TransferFunctionWidget->SetDataNode(0); m_Controls->m_TransferFunctionWidget->setEnabled(false); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(0); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(false); return; } // otherwise we can activate em all - enabled = false; - m_SelectedNode->GetBoolProperty("volumerendering.uselod",enabled); - m_Controls->m_EnableLOD->setEnabled(true); - m_Controls->m_EnableLOD->setChecked(enabled); - + m_Controls->m_BlendMode->setEnabled(true); m_Controls->m_RenderMode->setEnabled(true); // Determine Combo Box mode { bool usegpu=false; bool useray=false; bool usemip=false; m_SelectedNode->GetBoolProperty("volumerendering.usegpu",usegpu); -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) )) m_SelectedNode->GetBoolProperty("volumerendering.useray",useray); -#endif m_SelectedNode->GetBoolProperty("volumerendering.usemip",usemip); + + int blendMode; + if (m_SelectedNode->GetIntProperty("volumerendering.blendmode", blendMode)) + m_Controls->m_BlendMode->setCurrentIndex(blendMode); - int mode = 0; + if (usemip) + m_Controls->m_BlendMode->setCurrentIndex(vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND); - if(useray) - { - if(usemip) - mode=RM_GPU_MIP_RAYCAST; - else - mode=RM_GPU_COMPOSITE_RAYCAST; - } - else if(usegpu) - mode=RM_GPU_COMPOSITE_SLICING; - else - { - if(usemip) - mode=RM_CPU_MIP_RAYCAST; - else - mode=RM_CPU_COMPOSITE_RAYCAST; - } + int mode = DEFAULT_RENDERMODE; + if (useray) + mode = RAYCAST_RENDERMODE; + else if(usegpu) + mode = GPU_RENDERMODE; + m_Controls->m_RenderMode->setCurrentIndex(mode); + } m_Controls->m_TransferFunctionWidget->SetDataNode(m_SelectedNode); m_Controls->m_TransferFunctionWidget->setEnabled(true); m_Controls->m_TransferFunctionGeneratorWidget->SetDataNode(m_SelectedNode); m_Controls->m_TransferFunctionGeneratorWidget->setEnabled(true); } void QmitkVolumeVisualizationView::OnEnableRendering(bool state) { if(m_SelectedNode.IsNull()) return; m_SelectedNode->SetProperty("volumerendering",mitk::BoolProperty::New(state)); UpdateInterface(); RequestRenderWindowUpdate(); } -void QmitkVolumeVisualizationView::OnEnableLOD(bool state) +void QmitkVolumeVisualizationView::OnBlendMode(int mode) { - if(m_SelectedNode.IsNull()) + if (m_SelectedNode.IsNull()) return; - m_SelectedNode->SetProperty("volumerendering.uselod",mitk::BoolProperty::New(state)); + bool usemip = false; + if (mode == vtkVolumeMapper::MAXIMUM_INTENSITY_BLEND) + usemip = true; + + m_SelectedNode->SetProperty("volumerendering.usemip", mitk::BoolProperty::New(usemip)); + m_SelectedNode->SetProperty("volumerendering.blendmode", mitk::IntProperty::New(mode)); + RequestRenderWindowUpdate(); } void QmitkVolumeVisualizationView::OnRenderMode(int mode) { if(m_SelectedNode.IsNull()) return; - - bool usegpu=mode==RM_GPU_COMPOSITE_SLICING; -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) )) - bool useray=(mode==RM_GPU_COMPOSITE_RAYCAST)||(mode==RM_GPU_MIP_RAYCAST); -#endif - bool usemip=(mode==RM_GPU_MIP_RAYCAST)||(mode==RM_CPU_MIP_RAYCAST); + + bool usegpu = false; + if (mode == GPU_RENDERMODE) + usegpu = true; + + bool useray = false; + if (mode == RAYCAST_RENDERMODE) + useray = true; + + if (mode == DEFAULT_RENDERMODE) + { + useray = true; + usegpu = true; + } m_SelectedNode->SetProperty("volumerendering.usegpu",mitk::BoolProperty::New(usegpu)); -// Only with VTK 5.6 or above -#if ((VTK_MAJOR_VERSION > 5) || ((VTK_MAJOR_VERSION==5) && (VTK_MINOR_VERSION>=6) )) m_SelectedNode->SetProperty("volumerendering.useray",mitk::BoolProperty::New(useray)); -#endif - m_SelectedNode->SetProperty("volumerendering.usemip",mitk::BoolProperty::New(usemip)); RequestRenderWindowUpdate(); } void QmitkVolumeVisualizationView::SetFocus() { } void QmitkVolumeVisualizationView::NodeRemoved(const mitk::DataNode* node) { if(m_SelectedNode == node) { m_SelectedNode=0; m_Controls->m_SelectedImageLabel->hide(); m_Controls->m_ErrorImageLabel->hide(); m_Controls->m_NoSelectedImageLabel->show(); UpdateInterface(); } } diff --git a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h index 601a8e1009..8bd075f564 100755 --- a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h +++ b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationView.h @@ -1,83 +1,82 @@ /*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #ifndef QMITKVOLUMEVISUALIZATIONVIEW_H_ #define QMITKVOLUMEVISUALIZATIONVIEW_H_ #include #include #include #include #include "mitkDataStorage.h" #include #include #include #include "ui_QmitkVolumeVisualizationViewControls.h" /** * \ingroup org_mitk_gui_qt_volumevisualization_internal */ class QmitkVolumeVisualizationView : public QmitkAbstractView { Q_OBJECT public: void SetFocus() override; QmitkVolumeVisualizationView(); virtual ~QmitkVolumeVisualizationView(); virtual void CreateQtPartControl(QWidget *parent) override; /// /// Invoked when the DataManager selection changed /// virtual void OnSelectionChanged(berry::IWorkbenchPart::Pointer, const QList& nodes) override; static const std::string VIEW_ID; protected slots: void OnMitkInternalPreset( int mode ); void OnEnableRendering( bool state ); - void OnEnableLOD( bool state ); void OnRenderMode( int mode ); - + void OnBlendMode(int mode); protected: Ui::QmitkVolumeVisualizationViewControls* m_Controls; private: mitk::WeakPointer m_SelectedNode; void UpdateInterface(); void NodeRemoved(const mitk::DataNode* node) override; }; #endif /*QMITKVOLUMEVISUALIZATIONVIEW_H_*/ diff --git a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationViewControls.ui b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationViewControls.ui index 982bc0f0a9..2a0476f821 100644 --- a/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationViewControls.ui +++ b/Plugins/org.mitk.gui.qt.volumevisualization/src/internal/QmitkVolumeVisualizationViewControls.ui @@ -1,334 +1,327 @@ QmitkVolumeVisualizationViewControls 0 0 324 679 0 0 16777215 16777215 QmitkTemplate 0 0 191 0 0 191 0 0 191 0 0 191 0 0 191 0 0 191 0 0 120 120 120 120 120 120 120 120 120 0 0 197 0 0 191 0 0 189 0 0 197 0 0 191 0 0 189 0 0 120 120 120 120 120 120 120 120 120 Please select a volume image! 0 0 Click this checkbox to enable volumerendering in the 3D view of the selected image. Volumerendering - - - - Level of detail (LOD) enables a fast but lower quality preview rendering to increase interactivity. - - - LOD - - - 0 1 Select render mode + + + 0 0 0 0 0 1 QmitkTransferFunctionWidget QWidget
QmitkTransferFunctionWidget.h
QmitkTransferFunctionGeneratorWidget QWidget
QmitkTransferFunctionGeneratorWidget.h
1
QmitkDataStorageComboBox.h
diff --git a/Plugins/org.mitk.simulation/CMakeLists.txt b/Plugins/org.mitk.simulation/CMakeLists.txt deleted file mode 100644 index 4f22676df7..0000000000 --- a/Plugins/org.mitk.simulation/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -project(org_mitk_simulation) - -mitk_create_plugin( - EXPORT_DIRECTIVE SIMULATION_INIT_EXPORT - EXPORTED_INCLUDE_SUFFIXES src - MODULE_DEPENDS MitkQtWidgets MitkSimulation -) diff --git a/Plugins/org.mitk.simulation/files.cmake b/Plugins/org.mitk.simulation/files.cmake deleted file mode 100644 index 93637cdfb7..0000000000 --- a/Plugins/org.mitk.simulation/files.cmake +++ /dev/null @@ -1,31 +0,0 @@ -set(SRC_CPP_FILES - mitkGetSimulationPreferences.cpp - mitkMeshMitkLoader.cpp -) - -set(INTERNAL_CPP_FILES - org_mitk_simulation_Activator.cpp -) - -set(MOC_H_FILES - src/internal/org_mitk_simulation_Activator.h -) - -set(CACHED_RESOURCE_FILES - resources/SOFAIcon.png -) - -set(QRC_FILES - resources/Simulation.qrc -) - -set(CPP_FILES -) - -foreach(file ${SRC_CPP_FILES}) - set(CPP_FILES ${CPP_FILES} src/${file}) -endforeach() - -foreach(file ${INTERNAL_CPP_FILES}) - set(CPP_FILES ${CPP_FILES} src/internal/${file}) -endforeach() diff --git a/Plugins/org.mitk.simulation/manifest_headers.cmake b/Plugins/org.mitk.simulation/manifest_headers.cmake deleted file mode 100644 index 893c3d887f..0000000000 --- a/Plugins/org.mitk.simulation/manifest_headers.cmake +++ /dev/null @@ -1,6 +0,0 @@ -set(Plugin-Name "MITK Simulation Initialization") -set(Plugin-Version "0.1") -set(Plugin-Vendor "DKFZ, Medical and Biological Informatics") -set(Plugin-ContactAddress "http://www.mitk.org") -set(Require-Plugin org.mitk.gui.common) -set(Plugin-ActivationPolicy eager) diff --git a/Plugins/org.mitk.simulation/resources/SOFAIcon.png b/Plugins/org.mitk.simulation/resources/SOFAIcon.png deleted file mode 100644 index 3e0ce703ea..0000000000 Binary files a/Plugins/org.mitk.simulation/resources/SOFAIcon.png and /dev/null differ diff --git a/Plugins/org.mitk.simulation/resources/Simulation.qrc b/Plugins/org.mitk.simulation/resources/Simulation.qrc deleted file mode 100644 index 53480e1d88..0000000000 --- a/Plugins/org.mitk.simulation/resources/Simulation.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - SOFAIcon.png - - diff --git a/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp b/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp deleted file mode 100644 index 78fdd5fffe..0000000000 --- a/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.cpp +++ /dev/null @@ -1,106 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "org_mitk_simulation_Activator.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static void RegisterSofaClasses() -{ - int MeshMitkLoaderClass = sofa::core::RegisterObject("").add(); - boost::ignore_unused(MeshMitkLoaderClass); -} - -static void LoadSofaPlugins() -{ - berry::IPreferences::Pointer preferences = mitk::GetSimulationPreferences(); - - if (preferences.IsNull()) - return; - - QString plugins = preferences->Get("plugins", ""); - - if (plugins.isEmpty()) - return; - - QStringList pluginList = plugins.split(';', QString::SkipEmptyParts); - QStringListIterator it(pluginList); - - typedef sofa::helper::system::PluginManager PluginManager; - PluginManager& pluginManager = PluginManager::getInstance(); - - while (it.hasNext()) - { - std::string plugin = it.next().toStdString(); - std::ostringstream errlog; - - pluginManager.loadPlugin(plugin, &errlog); - - if (errlog.str().empty()) - pluginManager.getPluginMap()[plugin].initExternalModule(); - } -} - -static void AddPropertyFilters() -{ - mitk::IPropertyFilters* filters = mitk::org_mitk_simulation_Activator::GetService(); - - if (filters == nullptr) - return; - - mitk::PropertyFilter filter; - - filter.AddEntry("layer", mitk::PropertyFilter::Blacklist); - filter.AddEntry("name", mitk::PropertyFilter::Blacklist); - filter.AddEntry("path", mitk::PropertyFilter::Blacklist); - filter.AddEntry("selected", mitk::PropertyFilter::Blacklist); - filter.AddEntry("visible", mitk::PropertyFilter::Blacklist); - - filters->AddFilter(filter, "Simulation"); -} - -ctkPluginContext* mitk::org_mitk_simulation_Activator::Context = nullptr; - -void mitk::org_mitk_simulation_Activator::start(ctkPluginContext* context) -{ - Context = context; - - RegisterSimulationObjectFactory(); - RegisterSofaClasses(); - LoadSofaPlugins(); - AddPropertyFilters(); - - QmitkNodeDescriptorManager* nodeDescriptorManager = QmitkNodeDescriptorManager::GetInstance(); - - if (nodeDescriptorManager != nullptr) - { - mitk::NodePredicateDataType::Pointer simulationPredicate = mitk::NodePredicateDataType::New("Simulation"); - nodeDescriptorManager->AddDescriptor(new QmitkNodeDescriptor("Simulation", ":/Simulation/SOFAIcon.png", simulationPredicate, nodeDescriptorManager)); - } -} - -void mitk::org_mitk_simulation_Activator::stop(ctkPluginContext*) -{ - Context = nullptr; -} diff --git a/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.h b/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.h deleted file mode 100644 index ad63a1f394..0000000000 --- a/Plugins/org.mitk.simulation/src/internal/org_mitk_simulation_Activator.h +++ /dev/null @@ -1,52 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef org_mitk_simulation_Activator_h -#define org_mitk_simulation_Activator_h - -#include - -namespace mitk -{ - class org_mitk_simulation_Activator : public QObject, public ctkPluginActivator - { - Q_OBJECT - Q_PLUGIN_METADATA(IID "org_mitk_simulation") - Q_INTERFACES(ctkPluginActivator); - - public: - template - static T* GetService() - { - if (Context == nullptr) - return nullptr; - - ctkServiceReference serviceReference = Context->getServiceReference(); - - return serviceReference - ? Context->getService(serviceReference) - : nullptr; - } - - void start(ctkPluginContext* context) override; - void stop(ctkPluginContext*) override; - - private: - static ctkPluginContext* Context; - }; -} - -#endif diff --git a/Plugins/org.mitk.simulation/src/mitkGetSimulationPreferences.cpp b/Plugins/org.mitk.simulation/src/mitkGetSimulationPreferences.cpp deleted file mode 100644 index ecbccb38ca..0000000000 --- a/Plugins/org.mitk.simulation/src/mitkGetSimulationPreferences.cpp +++ /dev/null @@ -1,24 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "mitkGetSimulationPreferences.h" -#include -#include - -berry::IPreferences::Pointer mitk::GetSimulationPreferences() -{ - return berry::Platform::GetPreferencesService()->GetSystemPreferences()->Node("/org.mitk.views.simulation"); -} diff --git a/Plugins/org.mitk.simulation/src/mitkGetSimulationPreferences.h b/Plugins/org.mitk.simulation/src/mitkGetSimulationPreferences.h deleted file mode 100644 index debded83a3..0000000000 --- a/Plugins/org.mitk.simulation/src/mitkGetSimulationPreferences.h +++ /dev/null @@ -1,28 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkGetSimulationPreferences_h -#define mitkGetSimulationPreferences_h - -#include -#include - -namespace mitk -{ - SIMULATION_INIT_EXPORT berry::IPreferences::Pointer GetSimulationPreferences(); -} - -#endif diff --git a/Plugins/org.mitk.simulation/src/mitkMeshMitkLoader.cpp b/Plugins/org.mitk.simulation/src/mitkMeshMitkLoader.cpp deleted file mode 100644 index f69e1eaa2d..0000000000 --- a/Plugins/org.mitk.simulation/src/mitkMeshMitkLoader.cpp +++ /dev/null @@ -1,184 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#include "internal/org_mitk_simulation_Activator.h" -#include "mitkMeshMitkLoader.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include - -static mitk::DataStorage::Pointer GetDataStorage() -{ - mitk::IDataStorageService* dataStorageService = mitk::org_mitk_simulation_Activator::GetService(); - - if (dataStorageService != nullptr) - { - mitk::IDataStorageReference::Pointer dataStorageReference = dataStorageService->GetDefaultDataStorage(); - - if (dataStorageReference.IsNotNull()) - return dataStorageReference->GetDataStorage(); - } - - return nullptr; -} - -template -typename T::Pointer GetData(const std::string& name) -{ - mitk::DataStorage::Pointer dataStorage = GetDataStorage(); - - if (dataStorage.IsNull()) - return nullptr; - - typename mitk::TNodePredicateDataType::Pointer predicate = mitk::TNodePredicateDataType::New(); - mitk::DataStorage::SetOfObjects::ConstPointer subset = dataStorage->GetSubset(predicate); - - for (mitk::DataStorage::SetOfObjects::ConstIterator it = subset->Begin(); it != subset->End(); ++it) - { - mitk::DataNode::Pointer dataNode = it.Value(); - - if (dataNode->GetName() == name) - { - typename T::Pointer data = static_cast(dataNode->GetData()); - - if (data.IsNotNull()) - return data; - } - } - - return nullptr; -} - -mitk::MeshMitkLoader::MeshMitkLoader() -{ - this->addAlias(&m_filename, "dataNode"); - this->addAlias(&m_filename, "surface"); -} - -mitk::MeshMitkLoader::~MeshMitkLoader() -{ -} - -bool mitk::MeshMitkLoader::canLoad() -{ - Surface::Pointer surface = GetData(m_filename.getValue()); - - if (surface.IsNull()) - return false; - - vtkPolyData* polyData = surface->GetVtkPolyData(); - - if (polyData == nullptr || polyData->GetNumberOfCells() == 0) - return false; - - return true; -} - -bool mitk::MeshMitkLoader::load() -{ - Surface::Pointer surface = GetData(m_filename.getValue()); - vtkPolyData* polyData = surface->GetVtkPolyData(); - - // vtkSmartPointer transformFilter = vtkSmartPointer::New(); - // transformFilter->SetTransform(surface->GetGeometry()->GetVtkTransform()); - // transformFilter->SetInputConnection(polyData->GetProducerPort()); - // transformFilter->Update(); - - // polyData = vtkPolyData::SafeDownCast(transformFilter->GetOutputDataObject(0)); - - sofa::helper::vector& positions = *this->positions.beginEdit(); - sofa::helper::vector& edges = *this->edges.beginEdit(); - sofa::helper::vector& triangles = *this->triangles.beginEdit(); - sofa::helper::vector& quads = *this->quads.beginEdit(); - sofa::helper::vector > polygons = *this->polygons.beginEdit(); - - vtkPoints* points = polyData->GetPoints(); - vtkIdType numPoints = points->GetNumberOfPoints(); - double point[3]; - - for (vtkIdType i = 0; i < numPoints; ++i) - { - points->GetPoint(i, point); - positions.push_back(sofa::defaulttype::Vec3d(point[0], point[1], point[2])); - } - - vtkCellArray* polys = polyData->GetPolys(); - vtkSmartPointer poly = vtkSmartPointer::New(); - Edge edge; - Triangle triangle; - Quad quad; - - polys->InitTraversal(); - - while (polys->GetNextCell(poly) != 0) - { - switch (poly->GetNumberOfIds()) - { - case 1: - break; - - case 2: - edge[0] = poly->GetId(0); - edge[1] = poly->GetId(1); - - edges.push_back(edge); - break; - - case 3: - triangle[0] = poly->GetId(0); - triangle[1] = poly->GetId(1); - triangle[2] = poly->GetId(2); - - triangles.push_back(triangle); - break; - - case 4: - quad[0] = poly->GetId(0); - quad[1] = poly->GetId(1); - quad[2] = poly->GetId(2); - quad[3] = poly->GetId(3); - - quads.push_back(quad); - break; - - default: - sofa::helper::vector polygon; - vtkIdType numIds = poly->GetNumberOfIds(); - - polygon.reserve(numIds); - - for (vtkIdType i = 0; i < numIds; ++i) - polygon.push_back(poly->GetId(i)); - - polygons.push_back(polygon); - break; - } - } - - this->positions.endEdit(); - this->edges.endEdit(); - this->triangles.endEdit(); - this->quads.endEdit(); - this->polygons.endEdit(); - - return true; -} diff --git a/Plugins/org.mitk.simulation/src/mitkMeshMitkLoader.h b/Plugins/org.mitk.simulation/src/mitkMeshMitkLoader.h deleted file mode 100644 index 6c48f5b501..0000000000 --- a/Plugins/org.mitk.simulation/src/mitkMeshMitkLoader.h +++ /dev/null @@ -1,42 +0,0 @@ -/*=================================================================== - -The Medical Imaging Interaction Toolkit (MITK) - -Copyright (c) German Cancer Research Center, -Division of Medical and Biological Informatics. -All rights reserved. - -This software is distributed WITHOUT ANY WARRANTY; without -even the implied warranty of MERCHANTABILITY or FITNESS FOR -A PARTICULAR PURPOSE. - -See LICENSE.txt or http://www.mitk.org for details. - -===================================================================*/ - -#ifndef mitkMeshMitkLoader_h -#define mitkMeshMitkLoader_h - -#include -#include - -namespace mitk -{ - class SIMULATION_INIT_EXPORT MeshMitkLoader : public sofa::core::loader::MeshLoader - { - public: - SOFA_CLASS(MeshMitkLoader, sofa::core::loader::MeshLoader); - - bool canLoad() override; - bool load() override; - - private: - MeshMitkLoader(); - ~MeshMitkLoader(); - - MeshMitkLoader(const MyType&); - MyType& operator=(const MyType&); - }; -} - -#endif